如何在Rails中为集成测试编写帮助程序?

如何编写在多个集成测试中使用的集成测试助手? 我尝试了以下错误。 我正在考虑创建一个基类并扩展它,但我不明白’test_helper’是如何工作的! 我不能将帮助器方法放在test_helper中,因为它们使用特殊的集成助手,如post_with_redirect

LS

 $ ls test/integration integration_helper_test.rb post_integration_test.rb user_flows_test.rb 

代码,integration_helper_test.rb

 class IntegrationHelperTest < ActionDispatch::IntegrationTest def login(user) ... 

代码,post_integration_test.rb

 require 'test_helper' require 'integration_helper_test' # require 'integration/integration_helper_test' class PostIntegrationTest < ActionDispatch::IntegrationTest # include IntegrationHelperTest 

错误

 $ rake rake aborted! cannot load such file -- integration_helper_test C:/Users/Chloe/workspace/SeenIt/test/integration/post_integration_test.rb:2:in `' Tasks: TOP => test:run => test:integration 

代码,post_integration_test.rb

 require 'test_helper' # require 'integration_helper_test' require 'integration/integration_helper_test' class PostIntegrationTest < ActionDispatch::IntegrationTest 

错误

  1) Error: PostIntegrationTest#test_should_create_post: NoMethodError: undefined method `login' for # test/integration/post_integration_test.rb:20:in `block in ' 

代码,post_integration_test.rb

 require 'test_helper' # require 'integration_helper_test' #require 'integration/integration_helper_test' class PostIntegrationTest < ActionDispatch::IntegrationTest include IntegrationHelperTest 

错误

 $ rake rake aborted! wrong argument type Class (expected Module) C:/Users/Chloe/workspace/SeenIt/test/integration/post_integration_test.rb:6:in `include' C:/Users/Chloe/workspace/SeenIt/test/integration/post_integration_test.rb:6:in `' C:/Users/Chloe/workspace/SeenIt/test/integration/post_integration_test.rb:5:in `' Tasks: TOP => test:run => test:integration 

test_helper.rb中

 ENV["RAILS_ENV"] ||= "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActiveSupport::TestCase ActiveRecord::Migration.check_pending! 

选一个:

 module IntegrationHelperTest # ... end require 'test_helper' require 'integration/integration_helper_test' class PostIntegrationTest < ActionDispatch::IntegrationTest include IntegrationHelperTest # ... end 

要么

 class IntegrationHelperTest < ActionDispatch::IntegrationTest # ... end require 'test_helper' require 'integration/integration_helper_test' class PostIntegrationTest < IntegrationHelperTest # .. end 

name_helper_test.rb文件不适用于公共代码,这些文件适用于助手的测试用例。

根据Rails测试指南文件,以_test.rb结尾是针对测试用例的,您应该在该文件中编写测试,因为rake任务从_test.rb检测到测试的文件ID。 因此,如果您想添加一些常用代码,请为您提供test_helper.rb 。 您甚至可以为助手方法定义自己的文件,有关常见测试代码的更多指南,请参阅“编写可维护的Rails测试指南” 。

注意:上述答案的注释中的问题是您在类之外的test_helper.rb中编写代码,并且由于使用了require,所有方法都可以在其他文件中使用,因为它们都需要test_helper.rb