gpt4 book ai didi

ruby - 用一个期望测试自定义异常?

转载 作者:行者123 更新时间:2023-12-05 02:12:43 33 4
gpt4 key购买 nike

我有一个我想测试的函数在输入时引发异常,但该异常还包含一些比普通消息更多的信息,我也想测试它。所以我做了这样的事情as seen in the rspec documentation :

it 'raises the correct exception' do
expect { my_call }.to raise_error do |error|
expect(error.some_field).to eq('some data')
end
end

这很好用,但是它与 RSpec/MultipleExpectations 冲突:

RSpec/MultipleExpectations: Example has too many expectations [2/1]

据我所知,如果没有超过一个期望值,就不可能像这样以 block 形式使用 raise_error,那么是什么原因呢?有没有办法以某种方式将引发的异常保存在示例之外,以便我可以正常规范它,而无需在规范中做一些涉及 rescue 的可怕事情?或者我应该使用自定义 raise_custom_error 匹配器?

最佳答案

Rubocop 默认情况下,我认为会启用您看到的警告,其中表示每个 it block 中只有一个 expect。您可以通过添加以下内容在 rubocop.yml 中禁用此功能:

# Disables "Too many expectations."
RSpec/MultipleExpectations:
Enabled: false

或者如果你只想为你的特定规范禁用它,你可以通过添加这样的注释来实现,注意你可以通过在注释中使用规则名称来禁用任何 rubocop 规则:

# rubocop:disable RSpec/MultipleExpectations
it 'raises the correct exception' do
expect { my_call }.to raise_error do |error|
expect(error.some_field).to eq('some data')
end
end
# rubocop:enable RSpec/MultipleExpectations

it 'does something else' do
expect(true).to be true
end

更多 rubocop 语法选项 see this answer

关于ruby - 用一个期望测试自定义异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55545389/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com