【问题标题】:autoload specific module during testing in Rails在 Rails 测试期间自动加载特定模块
【发布时间】:2016-02-10 04:09:47
【问题描述】:

我注意到我的控制器测试开始变得太大,所以我将一些存根方法移到了一个单独的模块中。

我把它放在 test/lib/my_module.rb 中

module MyModule
  def mymethod
  end
end

所以我在 test/controllers/my_controller.rb 中的控制器测试现在看起来是这样的:

class MyControllerTest < ActionController::TestCase
  include MyModule
  def test_something
  end
end

然后我尝试仅在测试期间使 rails 自动加载路径“test/lib”。 为此,我在 config/environments/test.rb 中添加了以下几行

config.autoload_paths += ["#{config.root}/test/lib"]
config.eager_load_paths += ["#{config.root}/test/lib"]

但是当我使用“RAILS_ENV=test bundle exec rake test”运行我的测试时,它会抛出:

rake aborted!
NameError: uninitialized constant MyControllerTest::MyModule

如果我在 config/application.rb 中放入相同的两行,一切正常。但我不想加载这个模块 f.ex。正在生产中。

那么为什么会发生,我该如何解决呢? Rails 保留测试特定代码的最佳实践是什么?

【问题讨论】:

    标签: ruby-on-rails test-environments


    【解决方案1】:

    我将助手放在test/support/*.rb 下并包含它:

    test/test_helper.rb:

    # some code here
    
    Dir[Rails.root.join('test', 'support', '*.rb')].each { |f| require f }
    
    class ActiveSupport::TestCase
      include Warden::Test::Helpers
      include Auth # <- here is a helper for login\logout users in the test env
      # some code here
    

    使用测试规范共享模块是正常的做法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      • 2011-01-08
      • 2012-12-23
      • 2017-06-13
      • 2019-07-30
      • 2018-08-26
      • 1970-01-01
      相关资源
      最近更新 更多