Ruby:如何针对异常进行测试

时间:2017-02-14 22:08:23

标签: ruby-on-rails ruby

我是Ruby的新手,我想用allow编写一个针对logger预测的规范。请帮忙,谢谢。

当前规范

    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 => {})

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

尝试:

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