FactoryGirl association with different name
Asked Answered
S

1

6

I have the following associations

class Training < ApplicationRecord
  has_many :attendances
  has_many :attendees, through: :attendances
end

class Attendance < ApplicationRecord
  belongs_to :training
  belongs_to :attendee, class_name: 'Employee'

The Attendance table has attendee_id and training_id.

Now, How can I create a valid Attendance with FactoryGirl?

Currently, I have the following code

FactoryGirl.define do
  factory :attendance do
    training
    attendee
  end
end

FactoryGirl.define do
  factory :employee, aliases: [:attendee] do
    sequence(:full_name) { |n| "John Doe#{n}" }
    department
  end
end

But I get

  NoMethodError:
       undefined method `employee=' for #<Attendance:0x007f83b163b8e8>

I have also tried

FactoryGirl.define do
  factory :attendance do
    training
    association :attendee, factory: :employee
  end
end

With the same outcome.

Thanks for your help (or being polite is not allowed on SO???).

Sinistrality answered 14/11, 2016 at 9:25 Comment(0)
D
8

As you are probably aware FactoryGirl uses the symbol to infer what the class is, however when you are creating another factory with a different symbol for the same model you will need to tell FactoryGirl what the class to use is:

FactoryGirl.define do
  factory :attendance do
    training = { FactoryGirl.create(:training) }
    attendee = { FactoryGirl.create(:employee) }
  end
end

FactoryGirl.define do
  factory :employee, class: Attendee do
    sequence(:full_name) { |n| "John Doe#{n}" }
    department
  end
end

or can manually assign the relation (for example if you didn't want employee instance to be saved to database at this point):

FactoryGirl.build(:attendance, attendee: FactoryGirl.build(:employee))
Dogface answered 14/11, 2016 at 10:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.