【发布时间】:2018-06-07 10:11:56
【问题描述】:
我正在使用 Rails 5.2 并进行一些测试。我正在尝试使用ActionController::TestCase 进行单元测试,发现@controller.class.skip_before_action :verify_user 在进入下一个测试单元方法之前不会自动重置控制器。
现在,由于每次运行时 rails 测试都是随机的,因此某些单元有时会失败,有时不会失败。我认为它期待 HTTP 401,但我得到了 200。导致控制器忽略 before_action :verify_user。
我可以在每个单元的末尾设置@controller.class.before_action :verify_user(它可以工作!)但它不应该是测试 sys 以在每次运行之前重置上下文的代表吗?
提供我的代码片段:
class ApiSiteMetricsTest < ActionController::TestCase
tests Api::SiteMetricsController
def test_1_index
@controller.class.skip_before_action :verify_user,raise: false
get "index", params:{
"format"=>"json",
"site_metric_value"=>{
"site_metric_id"=>2403,
"date_acquired"=>"2018-03-14T01:44:00+05:30",
"site_id"=>3840,
"lab_device_details"=>"",
"comment"=>"",
"sender_affiliation"=>"",
"float_value"=>""
}
}
assert_response :success
File.open("#{Rails.root}/del.html", "wb") { |f| f.write(@response.body) }
#Do I have to do this o every test?
#@controller.class.before_action :verify_user
end
...
【问题讨论】:
-
你没有一些配置可以在每次测试后启用上下文重置吗?使用 rspec 可以在 spec_helper.rb 中使用
config.use_transactional_fixtures = true完成。同样使用 rspec 你有 before(:each) 和 after(:each) 回调将你的 skip 和 before_action 放入,避免手动将其粘贴到每个测试中 -
config.use_transactional_fixtures在这里无关紧要。
标签: ruby-on-rails ruby unit-testing tdd ruby-on-rails-5.2