How to create has_and_belongs_to_many associations in Factory girl

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

    You can define new factory and use after(:create) callback to create a list of associations. Let's see how to do it in this example:

    FactoryBot.define do
    
      # user factory without associated companies
      factory :user do
        # user attributes
    
        factory :user_with_companies do
          transient do
            companies_count 10
          end
    
          after(:create) do |user, evaluator|
            create_list(:companies, evaluator.companies_count, user: user)
          end
        end
      end
    end
    

    Attribute companies_count is a transient and available in attributes of the factory and in the callback via the evaluator. Now, you can create a user with companies with the option to specify how many companies you want:

    create(:user_with_companies).companies.length # 10
    create(:user_with_companies, companies_count: 15).companies.length # 15
    

提交回复
热议问题