2017-02-14 70 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 }