最终在RSpec中抛出异常的测试方法

时间:2017-12-05 21:03:39

标签: ruby-on-rails ruby rspec exception-handling

我有一个方法如下:

 if response.fetch('ok')
    response.fetch(response_key) { [] }
  elsif response.fetch('error') == 'token_revoked'
    ErrorReporter.increment('access_revoked', source: { account_id: account_id }, sporadic: true)
    fail(RemoteService::AccessRevoked, 'Our access to your account was revoked, please re-authorize.')
  else
    ErrorReporter.increment(
      'bad_request',
      source: {
        account_id: account_id
        error: response.fetch('error')
      },
      sporadic: true
    )
    fail(RemoteService::InvalidRequest, 'Something went wrong communicating with the remote service, please try again')
  end

当请求返回时出现token_revoked错误,我试图测试该方案。我想确保测试指定在这种情况下,我们将错误报告给我们的ErrorReporting服务。

所以,我的规范看起来像这样:

it 'records the failure with our error reporting service' do
  expect(ErrorReporter).to receive(:increment).with(
    'bad_request',
     source: {
       account_id:  1
     },
     sporadic: true
   )

   available_channels.fetch
end

但是,此规范始终失败,因为在调用ErrorReporter之后,代码会立即调用fail,这会使我的规范失败。有没有人知道如何在处理我知道代码现在要抛出的不可避免的异常时验证对我的错误记者的调用?

2 个答案:

答案 0 :(得分:1)

您可以在代码中引发expect errors。为了使RSpec捕获异常,您需要使用如下块:

it 'records the failure with our error reporting service' do
  expect(ErrorReporter).to receive(:increment).with(
    'bad_request',
    source: {
      account_id:  1
    },
    sporadic: true
  )

  expect { available_channels.fetch }
    .to raise_error RemoteService::InvalidRequest
end

答案 1 :(得分:-1)

该异常导致您的示例失败,因为它未获救。要修复它,可以将方法调用包装在begin ... rescue块中:

it 'records the failure with our error reporting service' do
  expect(ErrorReporter).to receive(:increment).with(
    'bad_request',
     source: {
       account_id:  1
     },
     sporadic: true
   )

   begin
     available_channels.fetch
   rescue => RemoteService::InvalidRequest
     # would cause the example to fail
   end
end