2016-11-14 18 views
2

FactoryGirl协会,我有以下的关联用不同的名字

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

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

考勤表有attendee_idtraining_id

现在,我如何使用FactoryGirl创建有效的Attendance

目前,我有以下的代码

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 

,但我得到

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

我也曾尝试

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

有了相同的结果。

感谢您的帮助(或有礼貌是不允许的SO ???)。

回答

4

正如你可能知道FactoryGirl使用符号来推断类是什么,但是当你创建了另一家工厂与同型号不同的符号,你需要告诉FactoryGirl如何使用类:

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 

或可以手动分配的关系(例如,如果你不想员工实例在这一点上保存到数据库):

FactoryGirl.build(:attendance, attendee: FactoryGirl.build(:employee))