我想使用customised failure messages当 testing if an error was raised or not访问带有 capybara 的页面时。
我的代码:
expect(visit '/page/path').to_not raise_error(ActionView::Template::Error), "my custom error message"
我还尝试使用 lambda 语法 (lambda { "my custom error message"}
),但没有成功。
问题似乎是错误本身优先于我的自定义错误消息显示。我对错误消息不感兴趣 - 如果出现错误消息,我知道问题是什么,并且自定义错误消息会提供解决方案(涉及 VCR 的故事很长)。
现在我有一个粗略的begin/rescue
,如下所示:
begin
expect(visit '/page/path').to_not raise_error(ActionView::Template::Error)
rescue ActionView::Template::Error => error
expect(1).to eq(0), "my custom error message"
end
但是,正如您所看到的,我必须编写一个假的、总是失败的测试,expect(1).to eq(0)
,这看起来很愚蠢。
有什么方法可以强制从内联自定义错误消息中显示我的消息吗?
最佳答案
首先,您需要将要执行的 block 传递给 Expect 方法,以便 raise_error
匹配器捕获 block 中引发的错误。也许令人惊讶的是,以下内容因此失败:
describe 'Foo' do
it 'raises an error' do
expect(fail "wat").to raise_error(RuntimeError)
end
end
但是如果我们按如下方式重写该期望,它就会通过:
expect{fail "wat"}.to raise_error(RuntimeError)
正如 Rob 提到的,如果您想指定不引发错误,您需要按如下方式编写您的期望:
expect{fail "wat"}.to_not raise_error
并使用该格式您可以指定自定义错误消息:
expect{fail "wat"}.to_not raise_error, "custom error message"
您的第二个代码块似乎有效的原因是您的访问'/page/path'
引发了异常,然后您的异常处理程序捕获了它。它相当于以下内容:
begin
visit '/page/path'
rescue ActionView::Template::Error => error
expect(1).to eq(0), "my custom error message"
end
关于ruby-on-rails - Rspec:raise_error 测试的自定义失败消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25498316/