Reputation: 774
I have some not too common issue with factory. I've got several models related with each other. I created quite fine factory that creates that whole "chain" invoking only below
FactoryGirl.create(:application)
Above command creates like I've mentioned before several related models. I user Faker to populate attributes' names. Everything works fine but, I would like to overwrite one deep related model called 'service' with application model. I thought about trait but I can't invoke that trait within
trait :my_trait do
name 'Overwritten name'
end
FactoryGirl.create(:application, :my_trait)
Obviously above is wrong because trait regards to application instead of nested service model. One solution I found is update it after create factory but I would prefer to do it more globally.
Upvotes: 0
Views: 108
Reputation: 31467
In these cases we usually create a separate "lower" instance and pass that to the "upper" instance.
Like:
service = FactoryGirl.build(:service, name: 'Something else')
application = FactoryGirl.create(:application, service: service)
Of course you could also achieve the same behavior if you use this pattern very much in your codebase with the following factory:
factory :application do
transient do
service_name nil
end
association :service
after(:build) do |application, evaluator|
if evaluator.service_name
application.service.name = evaluator.service_name
end
end
end
Upvotes: 1