【问题标题】:Rails Functional test functions works separately, but not together. Using cancan, devise, RoR4Rails 功能测试功能单独工作,但不能一起工作。使用 cancan、devise、RoR4
【发布时间】:2014-05-26 09:23:02
【问题描述】:

我正在使用 RoR4、Cancan(1.5.0) 和 Devise(3.2.2)。 我正在使用 Test:Unit 来测试我的应用程序。 问题是,如果我将请求分开在不同的函数中,它可以工作,但如果在一个函数中我执行两个测试,它似乎评估第一个请求的响应,即使在后续请求之后也是如此: 这有效:

test 'admin cannot delete product that has line_items associated' do
  sign_in @admin_user
  assert_no_difference('Product.count') do 
    delete :destroy, id: @prod_to_all
  end
  assert_redirected_to product_path(@prod_to_all)
end

test 'admin can delete product that has no line_items associated' do
  sign_in @admin_user
  assert_difference('Product.count', -1) do 
      delete :destroy, id: products(:prod_to_all_not_ordered)
  end
  assert_redirected_to products_path
end

如果我把它们放在一起,它会失败:

test 'admin cannot delete product that has line_items associated, but can delete one that has no line_items associated' do
  sign_in @admin_user
  assert_no_difference('Product.count') do 
    delete :destroy, id: @prod_to_all
  end
  assert_redirected_to product_path(@prod_to_all)

  assert_difference('Product.count', -1) do
    delete :destroy, id: products(:prod_to_all_not_ordered)
  end
  assert_redirected_to products_path
end

错误:

"Product.count" didn't change by -1.
  Expected: 5
  Actual: 6

我的问题是我有 3 个角色:public_user、client 和 admin。并且为不同功能中的每个角色测试每个功能是一种痛苦。即使对于简单的控制器,它也会变得比应有的更大,我讨厌这种解决方案。
你们有什么建议?我真的需要接受 rspec 及其上下文,还是我可以摆脱 test:unit 并保持代码干燥?
此外,在我看来,test:unit 有些东西不太好,因为它没有正确评估第二个请求……它是一个错误还是我不理解的结构性更强的东西? 谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rspec devise cancan


    【解决方案1】:

    我实际上更喜欢单独的版本。它更干净。而且我个人喜欢我的测试不要太干。这使它们更加冗长。我更喜欢:Duplication in Tests Is Sometimes good

    Rails 功能测试的目的是在每次测试一个请求的情况下运行。如果要测试多个请求,可以使用集成测试。 如果不查看控制器代码,很难判断错误。可能是您的应用程序在请求期间丢失了登录用户。或者他们共享状态(例如实例变量)。使用 pry 或其他调试器进行调试,或者只是简单的旧 puts 来查看对象的状态。

    【讨论】:

    • 谢谢米兰,我会听从你的建议的。
    猜你喜欢
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    相关资源
    最近更新 更多