Ruby on rails Ruby:如何针对异常进行测试
我是Ruby新手,我想使用allow编写一个针对logger expection的规范。请帮忙,谢谢 现行规格Ruby on rails Ruby:如何针对异常进行测试,ruby-on-rails,ruby,Ruby On Rails,Ruby,我是Ruby新手,我想使用allow编写一个针对logger expection的规范。请帮忙,谢谢 现行规格 it 'raises exception fetching auditables' do allow(NightLiaison::HttpConnection.open).to receive(:get).and_raise(StandardError) expect { described_class.fetch_auditables }.to raise_error
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 => {})
got#200,:body=>,:headers=>{})
当它尝试打开时,它似乎失败了-如果你也模仿它,它可能会工作。尝试以下方法:
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
看起来当它尝试打开时失败了-如果你也模仿它,它可以工作。尝试以下方法:
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
尝试:
尝试:
由于您在测试中启用了WebMock,所有尝试建立网络连接的操作都会导致您发布的WebMock::NetConnectNotAllowedError
错误,因此我假设NightContainion::HttpConnection.open
已正确模拟,但可能没有正确模拟?您是对的Nightliason::HttpConnection.open未模拟规范。我需要创建webmock存根请求吗?因为您在测试中启用了webmock,所以所有尝试建立网络连接的操作都会导致您发布的webmock::NetConnectNotAllowedError
错误,我假设NightContainion::HttpConnection.open
被正确模拟,但可能不是这样?您的回答是正确的Nightliason::HttpConnection.open在规范中不是mock。我需要创建webmock存根请求吗?非常感谢您的帮助,我在异常级别遇到了不同的错误“但未引发任何问题”,所以现在您需要找出代码未能通过此测试的原因;)我感觉代码有问题,我需要做进一步的调试:)。非常感谢。我非常感谢您的帮助,我在异常级别遇到了不同的错误“但未引发任何问题”,所以现在您需要找出代码未能通过此测试的原因;)我感觉代码有问题,我需要做进一步的调试:)。非常感谢。