Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Ruby:如何针对异常进行测试_Ruby On Rails_Ruby - Fatal编程技术网

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

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

我是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('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存根请求吗?非常感谢您的帮助,我在异常级别遇到了不同的错误“但未引发任何问题”,所以现在您需要找出代码未能通过此测试的原因;)我感觉代码有问题,我需要做进一步的调试:)。非常感谢。我非常感谢您的帮助,我在异常级别遇到了不同的错误“但未引发任何问题”,所以现在您需要找出代码未能通过此测试的原因;)我感觉代码有问题,我需要做进一步的调试:)。非常感谢。