How to create has_and_belongs_to_many associations in Factory girl

前端 未结 11 658
生来不讨喜
生来不讨喜 2020-12-07 09:27

Given the following

class User < ActiveRecord::Base
  has_and_belongs_to_many :companies
end

class Company < ActiveRecord::Base
  has_and_belongs_to_m         


        
11条回答
  •  被撕碎了的回忆
    2020-12-07 09:48

    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.

提交回复
热议问题