Rails功能测试 - 在assert_raises中嵌套断言?

时间:2014-07-01 20:52:04

标签: ruby-on-rails ruby-on-rails-3 tdd

我的功能测试如下:

test "vendors can't create notes for products they don't own" do
  login vendor
  params = { format: 'json', note: { content: "shouldn't exist" }, vendor_id: other_product.vendor.id }

  assert_raises(CanCan::AccessDenied) do
    assert_no_difference "Note.count" do
      post :create, params
    end
  end
end

运行时,此测试通过,但输出只显示1个断言:

1 tests, 1 assertions, 0 failures, 1 errors, 0 skips

这些嵌套的assert_no_difference断言是否会被运行,因为引发了AccessDenied异常?

如果我将它们作为两个单独的断言运行,如下所示:

assert_raises(CanCan::AccessDenied) do
  post :create, params
end

assert_no_difference "Note.count" do
  post :create, params
end

...使用CanCan::AccessDenied: You are not authorized to access this page.测试错误因此,第一个示例中的嵌套断言是否实际运行?我知道这有点多余,但它只是几行额外的代码,并提供一些额外的安心(但只有它实际上做任何事情)。

1 个答案:

答案 0 :(得分:1)

否,您注意到,您的assert_no_difference断言没有运行。引发异常完全摆脱了障碍。

解决方案是反转断言的嵌套顺序,如下所示:

assert_no_difference "Note.count" do
  assert_raises(CanCan::AccessDenied) do
    post :create, params
  end
end

assert_raises调用捕获异常,从而允许执行继续,因此外部块完成并执行了Note.count检查。