Factory Girl: How to set up a has_many/through association

后端 未结 4 1094
误落风尘
误落风尘 2020-12-30 20:57

I\'ve been struggling with setting up a has_many/through relationship using Factory Girl.

I have the following models:

class Job < Ac         


        
4条回答
  •  天涯浪人
    2020-12-30 21:32

    I faced this issue today and I found a solution. Hope this helps someone.

    FactoryGirl.define do
      factory :job do
    
        transient do
          details_count 5 # if details count is not given while creating job, 5 is taken as default count
        end
    
        factory :job_with_details do
          after(:create) do |job, evaluator|
            (0...evaluator.details_count).each do |i|
              job.details << FactoryGirl.create(:detail)
            end
          end
        end
      end  
    end
    

    This allows to create a job like this

    create(:job_with_details) #job created with 5 detail objects
    create(:job_with_details, details_count: 3) # job created with 3 detail objects
    

提交回复
热议问题