How to create has_and_belongs_to_many associations in Factory girl

opsb picture opsb · Sep 27, 2009 · Viewed 46.1k times · Source

Given the following

class User < ActiveRecord::Base
  has_and_belongs_to_many :companies
end

class Company < ActiveRecord::Base
  has_and_belongs_to_many :users
end

how do you define factories for companies and users including the bidirectional association? Here's my attempt

Factory.define :company do |f|
  f.users{ |users| [users.association :company]}
end

Factory.define :user do |f|
  f.companies{ |companies| [companies.association :user]}
end

now I try

Factory :user

Perhaps unsurprisingly this results in an infinite loop as the factories recursively use each other to define themselves.

More surprisingly I haven't found a mention of how to do this anywhere, is there a pattern for defining the necessary factories or I am doing something fundamentally wrong?

Answer

Suborx picture Suborx · Apr 18, 2012

Here is the solution that works for me.

FactoryGirl.define do

  factory :company do
    #company attributes
  end

  factory :user do
   companies {[FactoryGirl.create(:company)]}
   #user attributes
  end

end

if you will need specific company you can use factory this way

company = FactoryGirl.create(:company, #{company attributes})
user = FactoryGirl.create(:user, :companies => [company])

Hope this will be helpful for somebody.