Search code examples
ruby-on-railsbddfactory-bot

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


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

I have the following models:

class Job < ActiveRecord::Base
  has_many :job_details, :dependent => :destroy
  has_many :details, :through => :job_details
end

class Detail < ActiveRecord::Base
  has_many :job_details, :dependent => :destroy
  has_many :jobs, :through => :job_details
end

class JobDetail < ActiveRecord::Base
  attr_accessible :job_id, :detail_id
  belongs_to :job
  belongs_to :detail
end

My Factory:

factory :job do
  association     :tenant
  title           { Faker::Company.catch_phrase }
  company         { Faker::Company.name }
  company_url     { Faker::Internet.domain_name }
  purchaser_email { Faker::Internet.email }
  description     { Faker::Lorem.paragraphs(3) }
  how_to_apply    { Faker::Lorem.sentence }
  location        "New York, NY"
end

factory :detail do
  association :detail_type <--another Factory not show here
  description "Full Time"
end

factory :job_detail do
  association :job
  association :detail
end

What I want is for my job factory to be created with a default Detail of "Full Time".

I've been trying to follow this, but have not had any luck: FactoryGirl Has Many through

I'm not sure how the after_create should be used to attach the Detail via JobDetail.


Solution

  • Try something like this. You want to build a detail object and append it to the job's detail association. When you use after_create, the created job will be yielded to the block. So you can use FactoryGirl to create a detail object, and add it to that job's details directly.

    factory :job do
      ...
    
      after_create do |job|
        job.details << FactoryGirl.create(:detail)
      end
    end