开发环境中的应用程序内的Rails FactoryGirl [英] Rails FactoryGirl inside app in development env
问题描述
我正在尝试在开发模式下的应用程序内部使用FactoryGirl gem(用于邮件测试 rails_email_preview gem.
I'm trying to use FactoryGirl gem inside my App in development mode (it's for mailer tests more) with rails_email_preview gem.
它有效,但仅在初始页面加载时,重新加载/刷新页面后出现以下错误:
It works but only on initial page load, after reloading/refreshing the page I get following error:
Factory not registered: order
其中order
是工厂名称.
这是我的代码(这是我的Rails Engine的虚拟应用程序):
Here is my code (it is a dummy app for my Rails Engine):
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
我的工厂当然可以在测试环境中正常工作.
Of course my factories works without any problem in test environment.
任何帮助将不胜感激.
p FactoryGirl.factories
返回(页面重新加载后)
returns (after page reload)
#<FactoryGirl::Registry:0x007ff2c9dd29d0 @name="Factory", @items={}>
推荐答案
事实证明,我的问题与 Devise gem有关. 我的初始化程序中有代码,由于设计问题,该代码在每次重装时都会清除工厂(描述为
It turns out that my issue was connected with Devise gem. I have code in my initializer which clears factories on each reload because of devise issue (described here). This code runs only when there are some factories, so not on the first request.
解决方案是将我的 config/initializers/devise.rb 文件从以下位置更改:
The solution was to change my config/initializers/devise.rb file from:
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
注意:在执行find_definitions
之前,先使用before
代替after
回调和自定义FactoryGirl.definition_file_paths
定义.
Note: before
instead of after
callback and custom FactoryGirl.definition_file_paths
definition before find_definitions
is executed.
每次尝试使用after
挂钩时,第一次调用时都会出现Devise错误.
Each time I try to use after
hook I get Devise error on first call.
这篇关于开发环境中的应用程序内的Rails FactoryGirl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!