Rails FactoryGirl inside app in development env

天大地大妈咪最大 提交于 2019-12-10 15:54:00

问题


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

where order is name of factory.

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.

Any help would be appreciated.

EDIT:

p FactoryGirl.factories

returns (after page reload)

#<FactoryGirl::Registry:0x007ff2c9dd29d0 @name="Factory", @items={}>

回答1:


You'll need to call FactoryGirl.find_definitions to load factory girl in development.

require 'factory_girl'
FactoryGirl.find_definitions

Should do the trick.




回答2:


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.

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

to:

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

Note: before instead of after callback and custom FactoryGirl.definition_file_paths definition before find_definitions is executed.

Each time I try to use after hook I get Devise error on first call.



来源:https://stackoverflow.com/questions/36965377/rails-factorygirl-inside-app-in-development-env

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!