如何在引发错误之前使用检查内容
How to use check something before an error is raised
我有以下ruby代码
class Gateway
...
def post
begin
...
raise ClientError if state == :open
rescue ClientError => e
Log.add("error")
raise
end
end
end
在 RSpec 上,如何检查引发 ClientError
时 Log.add
被调用?
我尝试了不同的方法,但总是出现错误。
谢谢
您或许可以这样做(初始化步骤可能需要看起来有点不同,具体取决于您需要如何将 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
像这样的东西应该可以工作:
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
确保您的规范不会因为引发的错误而失败(它会默默地挽救它)。第二个示例检查是否正在重新引发错误。
我有以下ruby代码
class Gateway
...
def post
begin
...
raise ClientError if state == :open
rescue ClientError => e
Log.add("error")
raise
end
end
end
在 RSpec 上,如何检查引发 ClientError
时 Log.add
被调用?
我尝试了不同的方法,但总是出现错误。
谢谢
您或许可以这样做(初始化步骤可能需要看起来有点不同,具体取决于您需要如何将 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
像这样的东西应该可以工作:
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
确保您的规范不会因为引发的错误而失败(它会默默地挽救它)。第二个示例检查是否正在重新引发错误。