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

Chl*_*loe 2 integration-testing ruby-on-rails ruby-on-rails-4

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

LS

$ ls test/integration
integration_helper_test.rb  post_integration_test.rb  user_flows_test.rb
Run Code Online (Sandbox Code Playgroud)

代码,integration_helper_test.rb

class IntegrationHelperTest < ActionDispatch::IntegrationTest

  def login(user)
    ...
Run Code Online (Sandbox Code Playgroud)

代码,post_integration_test.rb

require 'test_helper'
require 'integration_helper_test'
# require 'integration/integration_helper_test'

class PostIntegrationTest < ActionDispatch::IntegrationTest
  # include IntegrationHelperTest
Run Code Online (Sandbox Code Playgroud)

错误

$ rake
rake aborted!
cannot load such file -- integration_helper_test
C:/Users/Chloe/workspace/SeenIt/test/integration/post_integration_test.rb:2:in `<top (required)>'
Tasks: TOP => test:run => test:integration
Run Code Online (Sandbox Code Playgroud)

代码,post_integration_test.rb

require 'test_helper'
# require 'integration_helper_test'
require 'integration/integration_helper_test'

class PostIntegrationTest < ActionDispatch::IntegrationTest
Run Code Online (Sandbox Code Playgroud)

错误

  1) Error:
PostIntegrationTest#test_should_create_post:
NoMethodError: undefined method `login' for #<PostIntegrationTest:0x3da81d0>
    test/integration/post_integration_test.rb:20:in `block in <class:PostIntegrationTest>'
Run Code Online (Sandbox Code Playgroud)

代码,post_integration_test.rb

require 'test_helper'
# require 'integration_helper_test'
#require 'integration/integration_helper_test'

class PostIntegrationTest < ActionDispatch::IntegrationTest
  include IntegrationHelperTest
Run Code Online (Sandbox Code Playgroud)

错误

$ 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 `<class:PostIntegrationTest>'
C:/Users/Chloe/workspace/SeenIt/test/integration/post_integration_test.rb:5:in `<top (required)>'
Tasks: TOP => test:run => test:integration
Run Code Online (Sandbox Code Playgroud)

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!
Run Code Online (Sandbox Code Playgroud)

Mal*_*zad 5

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

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

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