Populating an association with children in factory_girl Populating an association with children in factory_girl ruby ruby

Populating an association with children in factory_girl


The Factory.after_ hooks appear to be the only way to do this successfully. I've figured out a way to maintain the build strategy without duplicating code:

Factory.define :foo do |f|  f.name "A Foo"  f.after(:build) { |foo|    foo.bars << Factory.build(:bar, :foo => foo)  }  f.after(:create) { |foo|    foo.bars.each { |bar| bar.save! }  }end

The documentation states that after_build will be called before after_create if the :create build strategy is used. If :build is used, then only after_build is called, and everyone is happy.

I've also created an abstracted generally-applicable version at this gist to keep things DRY.


You can use the association method both ways:

Factory.define :foo do |f|  # ...  f.association :barend

If that won't work, you can associate them manually using a callback. Here's an example from one of my apps:

Factory.define :live_raid do |raid|endFactory.define :live_raid_with_attendee, :parent => :live_raid do |raid|  raid.after_create { |r| Factory(:live_attendee, :live_raid => r) }end


FactoryGirl now has a :method => :build option you can use on the association, which will build the associated object rather than creating it.

#64: Building an object creates associations