Factory Girl create association with existing object Factory Girl create association with existing object ruby-on-rails ruby-on-rails

Factory Girl create association with existing object


You could achieve what you want by both not using a factory for your Gender instances and using callbacks in your Customer factory.

You're not gaining a lot from the Gender factory as it stands (although I appreciate it may be simplified for the purposes of asking this question). You could just as easily do this to get a Gender:

Gender.find_or_create_by_code!('Male')

Then in your Customer factory you can use a before callback to set the Gender:

factory :dumas, :class => Customer do  first_name 'Mary'  last_name 'Dumas'  before_create do |customer|    customer.gender = Gender.find_or_create_by_code!('Female')  endend

The format for using callbacks in factory_girl has recently changed so if you're using 3.3 or later you'll need to do:

before(:create) do |customer|

instead of before_create.

If creating a gender is more complex than your example you can still create the genders using a factory but hook them up with your customers using callbacks using find_by_code! insteand of find_or_create_by_code!.


ignore has been deprecated and will be removed on version 5 of Factory Girl.

Instead, you can use transient attributes:

factory :dumas, :class => Customer do  transient do    female { Gender.find_by_code('Female') || create(:female) }  end  first_name 'Mary'  last_name 'Dumas'  gender { female }end


The ignore block can be used to wrap this up as well:

factory :dumas, :class => Customer do  ignore do    female { Gender.find_by_code('Female') || create(:female) }  end  first_name 'Mary'  last_name 'Dumas'  gender { female }end