Pav*_* K. 3 ruby-on-rails test-environments
我注意到我的控制器测试开始变得太大,所以我将一些存根方法移动到一个单独的模块中.
我把它放在test/lib/my_module.rb中
module MyModule
def mymethod
end
end
Run Code Online (Sandbox Code Playgroud)
所以我在test/controllers/my_controller.rb中的控制器测试现在看起来像这样:
class MyControllerTest < ActionController::TestCase
include MyModule
def test_something
end
end
Run Code Online (Sandbox Code Playgroud)
然后我尝试在测试期间制作rails autoload path"test/lib".为此,我在config/environments/test.rb中添加了以下行
config.autoload_paths += ["#{config.root}/test/lib"]
config.eager_load_paths += ["#{config.root}/test/lib"]
Run Code Online (Sandbox Code Playgroud)
但是当我使用"RAILS_ENV = test bundle exec rake test"运行我的测试时,它会抛出:
rake aborted!
NameError: uninitialized constant MyControllerTest::MyModule
Run Code Online (Sandbox Code Playgroud)
如果我在config/application.rb中放入相同的两行,一切都运行良好.但我不想加载这个模块f.ex. 在生产中.
那为什么会发生,我该如何解决呢?什么是Rails保持测试专用代码的最佳实践?
我把助手放在下面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
Run Code Online (Sandbox Code Playgroud)
具有测试规范的共享模块的常规做法.
| 归档时间: |
|
| 查看次数: |
891 次 |
| 最近记录: |