如何在引发错误之前检查一些东西

时间:2017-04-20 07:35:38

标签: ruby rspec3

我有以下红宝石代码

class Gateway
...
 def post
  begin 
  ...
  raise ClientError if state == :open
  rescue ClientError => e
   Log.add("error")
   raise
  end
 end
end

在RSpec上,如何在ClientError被提出Log.add时检查?

我尝试了不同的东西,但我总是得到错误。

由于

2 个答案:

答案 0 :(得分:4)

您可以执行以下操作(初始化步骤可能需要略有不同,具体取决于您需要将state设置为:open):

describe 'Gateway#post' do
  let(:gateway) { Gateway.new(state: :open) }

  before { allow(Log).to receive(:add) }

  it 'raises an excpetion' do
    expect { gateway.post }.to raise_error(ClientError)
    expect(Log).to have_received(:add).with('error')
  end
end

答案 1 :(得分:3)

这样的事情应该有效:

describe '#post' do
  context 'with state :open' do
    let(:gateway) { Gateway.new(state: :open) }

    it 'logs the error' do
      expect(Log).to receive(:add).with('error')
      gateway.post rescue nil
    end

    it 're-raises the error' do
      expect { gateway.post }.to raise_error(ClientError)
    end
  end
end

在第一个示例中,rescue nil确保您的规范没有因为引发的错误而失败(它会无声地挽救它)。第二个示例检查是否正在重新引发错误。

相关问题