Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create has_and_belongs_to_many associations in Factory girl

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.


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.


In my opinion, Just create two different factories like:

 Factory.define :user, :class => User do |u|
  # Just normal attributes initialization
 end

 Factory.define :company, :class => Company do |u|
  # Just normal attributes initialization
 end

When you write the test-cases for user then just write like this

 Factory(:user, :companies => [Factory(:company)])

Hope it will work.


I couldn´t find an example for the above mentioned case on the provided website. (Only 1:N and polymorphic assocations, but no habtm). I had a similar case and my code looks like this:

Factory.define :user do |user|
 user.name "Foo Bar"
 user.after_create { |u| Factory(:company, :users => [u]) }
end

Factory.define :company do |c|
 c.name "Acme"
end

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!