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 endend
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.