我的Appointment
模型有一个FactoryGirl工厂。例如:
require 'faker'
FactoryGirl.define do
factory :appointment do |f|
f.name { 'Pending Appointment' }
end
end
Appoinment
模型有很多AppointmentAccess
个实例。它在Appointment
模型的ActiveRecord回调中创建它们。 AppointmentAccess
是一个直通模式,将Appointment
与User
相关联。
我向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逻辑需要它)?
答案 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
回调将会运行。