【问题标题】:Testing custom exception with a single expect?用一个期望测试自定义异常?
【发布时间】:2019-04-06 02:44:33
【问题描述】:

我有一个要测试的函数在输入时引发异常,但该异常还包含比普通消息更多的信息,我也想测试它。所以我做了这样的事情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 cop 发生冲突:

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

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

【问题讨论】:

    标签: ruby rspec rubocop


    【解决方案1】:

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

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

    或者,如果您只想针对您的特定规范禁用它,您可以通过添加这样的 cmets 来实现,注意您可以通过使用 cmets 中的规则名称来禁用任何 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 2017-10-31
      • 2012-01-24
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多