如何编写在多个集成测试中使用的集成测试助手?我尝试了以下错误。我正在考虑制作一个基类并对其进行扩展,但我不明白“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
测试助手.rb
ENV["RAILS_ENV"] ||= "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
ActiveRecord::Migration.check_pending!
最佳答案
name_helper_test.rb 文件不用于通用代码,这些文件用于您的助手的测试用例。
根据 Rails Testing Guide以 _test.rb 结尾的文件用于测试用例,您应该在该文件中编写测试,因为 rake 任务从 _test.rb 检测到它是用于测试的文件 ID。因此,如果您想添加一些通用代码,test_helper.rb 就在您身边。您甚至可以为辅助方法定义自己的文件,有关常见测试代码的更多指南请阅读 A Guide for Writing Maintainable Rails Tests .
注意:上述答案的评论中的问题是您在类外的test_helper.rb 中编写代码,并且由于使用了require。所有方法都可以在其他文件中找到,因为它们都需要 test_helper.rb。
关于ruby-on-rails - 如何为 Rails 中的集成测试编写帮助程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20778032/