Sig*_*Sig 4 ruby-on-rails factory-bot
我有以下关联
class Training < ApplicationRecord
has_many :attendances
has_many :attendees, through: :attendances
end
class Attendance < ApplicationRecord
belongs_to :training
belongs_to :attendee, class_name: 'Employee'
Run Code Online (Sandbox Code Playgroud)
出勤表有attendee_id和training_id。
现在,我如何Attendance使用 FactoryGirl创建一个有效的?
目前,我有以下代码
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
Run Code Online (Sandbox Code Playgroud)
但我得到
NoMethodError:
undefined method `employee=' for #<Attendance:0x007f83b163b8e8>
Run Code Online (Sandbox Code Playgroud)
我也试过
FactoryGirl.define do
factory :attendance do
training
association :attendee, factory: :employee
end
end
Run Code Online (Sandbox Code Playgroud)
同样的结果。
感谢您的帮助(或者在 SO 上不允许有礼貌???)。
您可能知道 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
Run Code Online (Sandbox Code Playgroud)
或者可以手动分配关系(例如,如果您不希望此时将员工实例保存到数据库中):
FactoryGirl.build(:attendance, attendee: FactoryGirl.build(:employee))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2298 次 |
| 最近记录: |