views:

1776

answers:

3

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?

+2  A: 

First of all I strongly encourage you to use has_many :through instead of habtm (more about this here), so you'll end up with something like:

Employment has_many :users
Employment has_many :companies

User has_many :employments
User has_many :companies, :through => :employments 

Company has_many :employments
Company has_many :users, :through => :employments

After this you'll have has_many association on both sides and can assign to them in factory_girl in the way you did it.

Milan Novota
Shouldn't that be `Employment belongs_to :user` and `Employment belongs_to :company` with the join model connecting one Company with one User?
Daniel Beardsley
+3  A: 

Factorygirl has since been updated and now includes callbacks to solve this problem. Take a look at http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl for more info.

opsb
A: 

What worked for me was setting the association when using the factory. Using your example:

user = Factory(:user) company = Factory(:company)

company.users << user company.save!

Larry Kooper