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

时间:2013-12-26 00:55:25

标签: ruby-on-rails ruby-on-rails-4 integration-testing

如何编写在多个集成测试中使用的集成测试助手?我尝试了以下错误。我正在考虑创建一个基类并扩展它,但我不明白'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 `<top (required)>'
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 #<PostIntegrationTest:0x3da81d0>
    test/integration/post_integration_test.rb:20:in `block in <class:PostIntegrationTest>'

代码,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 `<class:PostIntegrationTest>'
C:/Users/Chloe/workspace/SeenIt/test/integration/post_integration_test.rb:5:in `<top (required)>'
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!

2 个答案:

答案 0 :(得分:5)

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

根据 _test.rb 结尾的Rails Testing Guide文件是针对测试用例的,您应该在该文件中编写测试,因为rake任务从 _test.rb检测到这是测试的文件ID。因此,如果您想添加一些常用代码, test_helper.rb 就适合您。您甚至可以为助手方法定义自己的文件,以获取有关常见测试代码A Guide for Writing Maintainable Rails Tests的进一步指南。

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

答案 1 :(得分:3)

选择一个:

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