4

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

我把它放在 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 保留测试特定代码的最佳实践是什么?

4

1 回答 1

9

我将助手放在下面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

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

于 2015-11-09T13:51:15.183 回答