我有一个工厂,当它的符号为:notification_event
时工作正常,但是当我将其名称更改为player_notification_event
时它会失败并显示错误
未初始化的常量PlayerNotificationEvent。
另外,我的其他工厂:property_notification_event
也失败了,并出现了错误
未初始化的常量PropertyNotificationEvent。
factory :player_notification_event do
notification_eventable_type 'Player'
association :notification_eventable, factory: :player
unread_count 1
last_notif_unread_count 0
last_email_message_count 0
last_email_time 5.hours.ago
last_notif_time 3.hours.ago
end
factory :property_notification_event do
notification_eventable_type 'Property'
association :notification_eventable, factory: :property
unread_count 1
last_notif_unread_count 0
last_email_message_count 0
last_email_time 5.hours.ago
last_notif_time 3.hours.ago
end
let(:player_notification_event) { create :player_notification_event }
let(:property_notification_event) { create :property_notification_event }
it 'sends email to player' do
player = player_notification_event.notification_eventable
allow(UnreadMessagesMailer).to receive_message_chain(:player_email, :deliver_now!)
described_class.perform
expect(UnreadMessagesMailer).to have_received(:player_email)
end
it 'sends email to property' do
property = property_notification_event.notification_eventable
allow(UnreadMessagesMailer).to receive_message_chain(:property_email, :deliver_now!)
described_class.perform
expect(UnreadMessagesMailer).to have_received(:property_email)
end
let(:player_notification_event) { create :notification_event }
it 'sends email to player' do
player = player_notification_event.notification_eventable
allow(UnreadMessagesMailer).to receive_message_chain(:player_email, :deliver_now!)
described_class.perform
expect(UnreadMessagesMailer).to have_received(:player_email)
end
factory :notification_event do
notification_eventable_type 'Player'
association :notification_eventable, factory: :player
unread_count 1
last_notif_unread_count 0
last_email_message_count 0
last_email_time 5.hours.ago
last_notif_time 3.hours.ago
end
答案 0 :(得分:2)
您可以在此处使用继承,而不是复制整个工厂。
[...]最好为每个类定义一个基本工厂, 创建它所需的属性。然后,创建更具体的 从此基本父级继承的工厂。工厂定义是 仍然是代码,因此请使其保持干燥。 maps.FrozenMap
factory :notification_event do
unread_count 1
last_notif_unread_count 0
last_email_message_count 0
last_email_time 5.hours.ago
last_notif_time 3.hours.ago
factory :player_notification_event do
notification_eventable_type 'Player'
association :notification_eventable, factory: :player
end
factory :property_notification_event do
notification_eventable_type 'Property'
association :notification_eventable, factory: :property
end
end
由于模型类是从父类factory :notification_event
派生的,因此您无需手动指定它。
答案 1 :(得分:1)
factory_bot
的默认值是查找与factory
中的第一个参数同名的类,如果您未显式传递class
(请检查{{3} }。试试这个:
factory :player_notification_event, class: NotificationEvent do ...