ruby 使用单个expect测试自定义异常?

pinkon5k  于 4个月前  发布在  Ruby
关注(0)|答案(2)|浏览(41)

我有一个函数,我想测试在输入上引发异常,但是这个异常也携带了一些信息,而不仅仅是一个普通的消息,我也想测试它。所以我做了一些类似于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 cop相冲突:

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


从我所知道的,不可能在没有多个expect的情况下以块的形式使用raise_error,那么有什么办法呢?有没有某种方法可以在示例之外保存异常,这样我就可以正常地规范它,而不会在规范中做一些可怕的涉及rescue的事情?或者我应该使用自定义的raise_custom_error匹配器?

8wtpewkr

8wtpewkr1#

Rubocop默认情况下,我认为会启用您看到的警告,即每个it块中只有一个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

zi8p0yeb

zi8p0yeb2#

你可以随时禁用RSpec/MultipleExpectations cop,但是如何以一种让rubocop(和rubocop-rspec)满意的方式重写它呢?类似这样的东西应该可以工作:

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

字符串
如果我们想对错误类做更多的检查,我们可以使用“可组合参数匹配器”,也就是像这样添加.and

it 'raises the correct exception' do
    expect { my_call }.to raise_error(
      an_instance_of(RuntimeError)
      .and(having_attributes(some_field: 'some data'))
    )
  end


在rubocop-rspec repo中讨论了类似的问题

相关问题