为什么在 RSpec 中负特定异常期望已被弃用?

3

看起来我可以为.to指定异常类,但不能为.not_to指定异常类?这是什么原因呢?

 Failure/Error: expect{ smth }.not_to raise_exception SomeExceptionClass
 ArgumentError:
   `expect { }.not_to raise_error(SpecificErrorClass)` is not valid, use `expect { }.not_to raise_error` (with no args) instead
3个回答

2
为了进一步解释Nakilon的答案:
这是他们做出的设计决定。他们认为这不是一个好的测试规范,因为如果你期望某个错误没有被引发,那么当测试通过时会出现以下情况:
- 没有引发错误 - 引发了其他错误
这至少是不精确的。很可能你的代码只想要其中一个结果。
无论如何,这似乎是他们的理由--我不想说它是否公平。

https://github.com/rspec/rspec-expectations/issues/231 的讨论总结得非常好。谢谢。 - Tyler Rick

0

看起来他们意识到没有理由弃用异常类参数,所以它目前可以正常工作:https://www.relishapp.com/rspec/rspec-expectations/v/3-5/docs/built-in-matchers/raise-error-matcher

例如,在Selenium中,在检查某些条件是否为真后:

Selenium::WebDriver::Wait.new(
  message: message,
  timeout: timeout,
).until do
  f() == x
end

现在,通过否定超时异常,也很容易等待它在接下来的几秒钟内不变为假:

  begin
    Selenium::WebDriver::Wait.new(
      timeout: timeout,
    ).until do
      f() != x
    end
    raise message
  rescue Selenium::WebDriver::Error::TimeOutError
  end

0

来自变更日志:

使得expect { }.to_not raise_error(SomeSpecificClass, message)expect { }.to_not raise_error(SomeSpecificClass)expect { }.to_not raise_error(message)无效,因为它们容易隐藏失败。相反,使用expect { }.to_not raise_error(不带参数)。 (Sam Phippen)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接