I wanted to create a factory that would link various states to my model, but from a specified list instead of automatically generated. I discovered that these are transient attributes:
FactoryGirl.define do
factory :business do
name "MyString"
#
#
#
trait :with_states do
ignore do
state_list []
end
# add association equal to state code
after(:create) do |business, evaluator|
evaluator.state_list.each do |state_code|
business.states << State.find_by(state_code: state_code)
end
end
end
end
end
This factory can now be called with:
FactoryGirl.create(:business, :with_states. state_list: %w(KY IN))
Of course, now that I’m passing in the attributes, I can probably just use:
FactoryGirl.define do
factory :business do
name "MyString"
#
#
#
ignore do
with_states []
end
# add association equal to state code
after(:create) do |business, evaluator|
evaluator.with_states.each do |state_code|
business.states << State.find_by(state_code: state_code)
end
end
end
end
and then the call is even simpler:
FactoryGirl.create(:business, with_states: %w(KY IN))