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

后端 未结 4 1098
误落风尘
误落风尘 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:14

    This worked for me

    FactoryGirl.define do
      factory :job do
    
        # ... Do whatever with the job attributes here
    
        factory :job_with_detail do
    
          # In later (as of this writing, unreleased) versions of FactoryGirl
          # you will need to use `transitive` instead of `ignore` here
          ignore do
            detail { create :detail }
          end
    
          after :create do |job, evaluator|
            job.details << evaluator.detail
            job.save
            job_detail = job.job_details.where(detail:evaluator.detail).first
    
            # ... do anything with the JobDetail here
    
            job_detail.save
          end
        end
      end
    end
    

    Then later

    # A Detail object is created automatically and associated with the new Job.
    FactoryGirl.create :job_with_detail
    
    # To supply a detail object to be associated with the new Job.
    FactoryGirl.create :job_with_detail detail:@detail
    

提交回复
热议问题