由于AR回调中的逻辑,FactoryGirl工厂失败

时间:2016-06-10 17:11:53

标签: ruby-on-rails activerecord factory-bot

我的Appointment模型有一个FactoryGirl工厂。例如:

require 'faker'

FactoryGirl.define do
  factory :appointment do |f|
    f.name { 'Pending Appointment' }
  end
end

Appoinment模型有很多AppointmentAccess个实例。它在Appointment模型的ActiveRecord回调中创建它们。 AppointmentAccess是一个直通模式,将AppointmentUser相关联。

我向Factory添加了一个回调(见下文),但由于在FactoryGirl回调之前运行了AR回调,因此Appointment模型的AR回调中仍然出现错误:

class Appointment < ActiveRecord::Base
  has_many :appointment_accesses
  has_many :users, through: :appointment_accesses

  after_create :example_callback

  protected

  def example_callback
    owner = self.appointment_accesses.find_by(owner: 1)

    owner.name
  end
end

由于模型的回调在FactoryGirl回调之前运行,因此设置为1的AppointmentAccess尚未存在,因此会抛出错误。这是我的FactoryGirl工厂的回调(与上面相同,带回调):

owner

如何确保在require 'faker' FactoryGirl.define do factory :appointment do |f| f.name { 'Pending Appointment' } after(:create) do |appointment| FactoryGirl.create(:appointment_access, appointment: appointment) end end end 模型的回调运行之前,FactoryGirl回调首先运行(因为ActiveRecord逻辑需要它)?

1 个答案:

答案 0 :(得分:0)

尝试使用AppointmentAccess回调初始化新的Appointment记录以及新的before(:create)

require 'faker'

FactoryGirl.define do
  factory :appointment do |f|
    f.name { 'Pending Appointment' }

    before(:create) do |appointment|
      # initializes a new AppointmentAccess and adds it to the collection
      appointment.appointment_accesses << FactoryGirl.build(:appointment_access)
    end
  end
end

实际保存Appointment时,它还会保存已初始化的AppointmentAccess,此时模型中的after_create回调将会运行。