2017-04-20 59 views
1

錯誤之前,我有以下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叫?

我嘗試過不同的事情,但我總是得到提出的錯誤。

感謝

+2

您不應該檢查*「檢查當發生'ClientError'' Log.add'被稱爲」*。你應該檢查'state'是否是':open',你會得到記錄的錯誤。 – ndn

回答

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確保您的規範不是fa因爲提出的錯誤(它默默地拯救它)。第二個例子檢查錯誤是否被重新提出。

+0

感謝您的回覆。我錯過了'救援無'。我更喜歡有兩個單獨的規格。 – macsig

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 
+0

感謝您的回覆。 – macsig