How to create has_and_belongs_to_many associations in Factory girl

前端 未结 11 651
生来不讨喜
生来不讨喜 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:50

    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.

提交回复
热议问题