I'm trying to figure out how to write a factory that belongs to 2 different models that each should have the same parent model. Here's the contrived sample code:
class User < ActiveRecord::Base
  has_many :widgets
  has_many :suppliers
  attr_accessible :username
end
class Widget < ActiveRecord::Base
  belongs_to :user
  has_many :parts
  attr_accessible :name
end
class Supplier < ActiveRecord::Base
  belongs_to :user
  has_many :parts
  attr_accessible :name
end
class Part < ActiveRecord::Base
  belongs_to :supplier
  belongs_to :widget
  attr_accessible :name
end
Here's what I have so far:
factory :user do
  name 'foo'
end
factory :widget do
  association :user
  name 'widget'
end
factory :supplier do
  association :user
  name 'supplier'
end
factory :part do
  association :widget
  association :supplier
  name 'part'
end
The problem with this is that the part.widget.user != part.supplier.user  and they have to be the same.
I've tried the following with no success:
factory :part do
  association :widget
  association :supplier, user: widget.user
  name 'part'
end
Any suggestions? Or do I have to modify it after I create the part?
Thank you
I believe you could do this with a callback:
factory :part do
  association :widget
  association :supplier
  name 'part'
  after(:create) do |part|
    user = FactoryGirl.create(:user)
    part.widget.user = part.supplier.user = user
  end
end
See also: Get two associations within a Factory to share another association
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With