为什么我不能在 to_raise 匹配器中捕获 Capybara::ElementNotFound?

Why can't I catch Capybara::ElementNotFound in the to_raise matcher?

pry#<> expect(find("#recipients")).to raise_error(Capybara::ElementNotFound)
Capybara::ElementNotFound: Unable to find visible css "#recipients"

我知道测试某些元素是否 "not" 很难并且可能容易出错,但我相信我的用例是一个很好的用例。

我正在尝试制作一个 #dont_find 匹配器...

您的问题是您试图将 find('#recipients') 直接传递给 expect,但这不起作用,因为 find 引发异常,因此 expect甚至从未被调用。你应该传递一个块,像这样:

expect { find('#recipients') }.to raise_error(Capybara::ElementNotFound)