How to create has_and_belongs_to_many associations in Factory girl

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

    Update for Rails 5:

    Instead of using has_and_belongs_to_many association, you should consider: has_many :through association.

    The user factory for this association looks like this:

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

    You can create the company factory in a similar way.

    Once both factories are set, you can create user_with_companies factory with companies_count option. Here you can specify how many companies the user belongs to: create(:user_with_companies, companies_count: 15)

    You can find detailed explanation about factory girl associations here.

提交回复
热议问题