ruby on rails - Improving factories of associated models -
i have 3 models : user, product , ownership. ownership belongs user , product. product , user have many ownerships.
i created following factories factorygirl gem :
factory :user sequence(:name) { |n| "robot #{n}" } sequence(:email) { |n| "numero#{n}@robots.com"} association :location, factory: :location end factory :product sequence(:name) { |n| "objet #{n}" } association :location, factory: :location end factory :ownership association :user, factory: :user association :product, factory: :product end
and use :
let(:user) { factorygirl.create(:user) } let(:product) { factorygirl.create(:product) } let(:ownership) { factorygirl.create(:current_ownership, user: user, product: product) }
but want improve factories, in order :
let(:user) { factorygirl.create(:user) } let(:product) { factorygirl.create(:product, owner: user) }
do have idea how ?
you can using factory girl after_create callback:
factorygirl.define factory :product # ... ignore owner nil end after :create |product, ev| if ev.owner create :ownership, user: ev.owner, product: product end end end end
this way configure factory so, can pass owner attribute it. ignore block ensures attribute won't passed object's constructor, can use in factory girl's callbacks.
you can find more information on factory girl callbacks here.
Comments
Post a Comment