首页 > 解决方案 > 用一个期望测试自定义异常?

问题描述

我有一个要测试的函数在输入上引发异常,但该异常还包含更多信息,而不仅仅是一条普通消息,我也想测试它。所以我做了类似的事情,如 rspec 文档中所示

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]

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

标签: rubyrspecrubocop

解决方案


默认情况下,我认为 Rubocop 会启用您看到的警告,即expect每个it块中只有一个。您可以通过添加以下内容在 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 语法选项,请参阅此答案


推荐阅读