如何减少 RSpec 错误测试的重复?

问题描述 投票:0回答:1

问候和感谢任何人调整。

我有一个可能会产生错误的方法,我有一些特殊的逻辑可以在错误发生时和另一个异常被重新引发之前运行。

例子:

def some_cool_method
 error_prone_logic

 rescue StandardError => e
   logging_methods
   
   error_handling

   raise SpecificException.new
end

规格设置:

我正在为

error_prone_logic
中使用的实体之一制作一个存根,并让它抛出这样的异常:

    before do
      allow(some_entity_double).to receive(:work).and_raise(StandardError, 'RIP')
    end

我的问题是,当我想测试发生错误后运行的逻辑并且我想分离规范时,我生成的代码必须始终测试异常:

    it 'raises explicit error' do
      expect { subject }.to raise_error(SpecificException)
    end

    it 'logs the error' do
      expect(logger).to receive(:error)

      expect { subject }.to raise_error(SpecificException)
    end

    it 'does error handling' do
      expect(ErrorHandler).to receive(:handle)

      expect { subject }.to raise_error(SpecificException)
    end

如果

expect { subject }.to raise_error(SpecificException)
在每个案例的末尾都缺少 - 测试套件无法运行。

所以我的问题是:

有没有办法设置它,以便我只有一个

expect { subject }.to raise_error(SpecificException)
的规范,其余的只断言他们需要断言的东西?

ruby-on-rails testing rspec refactoring
1个回答
0
投票

将错误提升封装到方法中是什么?

def some_cool_method
 error_prone_logic

rescue StandardError
  logging_methods
   
  error_handling

  raise_error
end

在这种情况下,你可以在任何地方模拟它,除了错误提升测试

before
  allow(some_cool_entity).to receive(:raise_error)
end

it 'raises explicit error' do
  allow(some_cool_entity).to receive(:raise_error).and_call_original

  expect { subject }.to raise_error(SpecificException)
end

it 'logs the error' do
  expect(logger).to receive(:error)
end

it 'does error handling' do
  expect(ErrorHandler).to receive(:handle)
end
© www.soinside.com 2019 - 2024. All rights reserved.