ruby-on-rails - 具有不同名称的 FactoryGirl 协会

标签 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'

考勤表有attendee_idtraining_id .

现在,我如何创建一个有效的 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 上不允许有礼貌???)。

最佳答案

您可能知道 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))

关于ruby-on-rails - 具有不同名称的 FactoryGirl 协会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40585384/

相关文章:

ruby-on-rails - 用于 haml 页面的 Ruby/Rails 绑定(bind) css

json - rails API : Cannot whitelist JSON field attribute

ruby - Factory Girl - HABTM 的可变数量的关联对象

ruby-on-rails - 在我的单元测试中,fixture 和 factory 有什么区别?

ruby-on-rails - 当我已经在模型中创建关联时,如何测试具有与 FactoryGirl 的 has_one 关联的模型

ruby-on-rails - rails : Cucumber not cleaning DB

ruby-on-rails - 如何使用 OR 组合两个范围

ruby-on-rails - 如何在 Rails 集成测试中设置 session 变量

ruby-on-rails - 工厂女孩将论点传递给多对多协会

ruby-on-rails-3 - Factory Girl vs. User.create —— 有什么区别?