Skip to main content
 首页 » 编程设计

ruby-on-rails中Rails 功能测试中在assert_raises 中嵌套断言

2025年01月19日13pander-it

我进行了如下功能测试:

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 

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

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

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

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

请您参考如下方法:

不,正如您所注意到的,您的 assert_no_difference 断言未运行。引发异常完全打破了阻塞。

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

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

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