我正在尝试在开发模式下在我的应用程序中使用FactoryGirl gem(用于邮件测试more)和rails_email_preview gem。
它有效,但仅在初始页面加载时有效,重新加载/刷新页面后,我收到以下错误:
Factory not registered: order
其中
order
是工厂名称。
这是我的代码(它是我的 Rails 引擎的虚拟应用程序):
spec/dummy/app/mailer_previews/mymodule/order_mailer_preview.rb
Dir[Mymodule::Core::Engine.root.join('spec', 'factories', '*')].each do |f|
require_dependency f
end
module Mymodule
class OrderMailerPreview
def confirmation_email
o = FactoryGirl.create(:order)
OrderMailer.confirmation_email(o)
end
end
end
当然我的工厂在测试环境下是没有任何问题的。
如有任何帮助,我们将不胜感激。
编辑:
p FactoryGirl.factories
返回(页面重新加载后)
#<FactoryGirl::Registry:0x007ff2c9dd29d0 @name="Factory", @items={}>
您需要致电
FactoryGirl.find_definitions
来加载开发中的工厂女孩。
require 'factory_girl'
FactoryGirl.find_definitions
应该可以解决问题。
事实证明我的问题与 Devise gem 有关。 我的初始化程序中有代码,由于设计问题(如here所述),每次重新加载时都会清除工厂。 此代码仅在存在一些工厂时运行,因此不会在第一个请求时运行。
解决方案是更改我的 config/initializers/devise.rb 文件:
ActionDispatch::Callbacks.after do
# Reload the factories
return unless (Rails.env.development? || Rails.env.test?)
unless FactoryGirl.factories.blank? # first init will load factories, this should only run on subsequent reloads
FactoryGirl.factories.clear
FactoryGirl.find_definitions
end
end
至:
ActionDispatch::Callbacks.before do
# Reload the factories
return unless (Rails.env.development? || Rails.env.test?)
FactoryGirl.definition_file_paths = [Mymodule::Core::Engine.root.join('spec', 'factories')]
# first init will load factories, this should only run on subsequent reloads
unless FactoryGirl.factories.blank?
FactoryGirl.factories.clear
FactoryGirl.sequences.clear
FactoryGirl.find_definitions
end
end
注意:
before
代替after
回调和执行FactoryGirl.definition_file_paths
之前自定义find_definitions
定义。
每次我尝试使用
after
钩子时,我都会在第一次调用时遇到 Devise 错误。