2017-02-14 113 views
0

我是Ruby的新手,我想寫一個規範反對logger expection使用allow。請幫忙,謝謝。Ruby:如何測試異常

電流規格

it 'raises exception fetching auditables' do 
    allow(NightLiaison::HttpConnection.open).to receive(:get).and_raise(StandardError) 
    expect { described_class.fetch_auditables }.to raise_error('Fetching auditables raised an exception') 
end 

方法:

def self.fetch_auditables 
    HttpConnection.open.get AppConfig.api.nightliaison.fetch_auditables 
    rescue => e 
     LOGGER.error('Fetching auditables raised an exception', exception: e) 
     Faraday::Response.new 
     end 

錯誤消息:

got #<WebMock::NetConnectNotAllowedError: Real HTTP connections are disabled. Unregistered request: GET h... => 200, :body => "", :headers => {}) 
+0

因爲您已啓用WebMock在測試中*所有*嘗試進行網絡連接會導致'WebMock :: NetConnectNotAllowedError'從你貼什麼,我會假設'NightLiaison :: HttpConnection.open'被適當地模擬,但也許不是? – GSP

+0

你是對的Nightliason :: HttpConnection.open不是在模擬規範。我需要創建一個webmock存根請求嗎? – Skipoura

回答

1

看起來當它試圖open喜歡失敗 - 如果你莫也可以,它可以工作。嘗試是這樣的:

it 'raises exception fetching auditables' do 
    open_mock = double 
    allow(open_mock).to receive(:get).and_raise(StandardError) 
    allow(NightLiaison::HttpConnection).to receive(:open).and_return(open_mock) 
    expect { described_class.fetch_auditables }.to raise_error('Fetching auditables raised an exception') 
end 
+0

我很感謝幫助,我在異常級別得到了不同的錯誤「但沒有提出任何問題」 – Skipoura

+0

因此,現在您需要弄清楚爲什麼您的代碼無法通過此測試; –

+1

我有感覺代碼問題,我需要進一步調試:)。謝謝! – Skipoura

1

嘗試:

allow(NightLiaison::HttpConnection).to receive_message_chain(:open, :get) { raise StandardError }