【问题标题】:RSpec: Expecting method to raise an error failsRSpec:期望引发错误的方法失败
【发布时间】:2015-04-27 00:54:09
【问题描述】:

我正在尝试测试在某些条件下是否正确引发了错误。在本规范中,引发了错误,但测试仍然失败。我做错了什么?

require 'spec_helper'

describe USBTeensyRenderer do 
  context 'when the correct USB port name is not present' do
    it 'raises an error on instantiation' do
      expect(renderer = USBTeensyRenderer.new).to raise_error(USBInitError)
    end
  end
end

以及'bundle exec rspec'的终端输出:

Failures:

  1) USBTeensyRenderer when the correct USB port name is not present raises an error on instantiation
     Failure/Error: expect(renderer = USBTeensyRenderer.new).to raise_error(USBInitError)
     USBInitError:
       USB output couldn't be initialized
     # ./lib/ivan/view/renderers/usb_teensy_renderer.rb:9:in `rescue in initialize'
     # ./lib/ivan/view/renderers/usb_teensy_renderer.rb:6:in `initialize'
     # ./spec/models/usb_teensy_renderer_spec.rb:10:in `new'
     # ./spec/models/usb_teensy_renderer_spec.rb:10:in `block (3 levels) in <top (required)>'

Finished in 0.00351 seconds (files took 0.11638 seconds to load)
8 examples, 1 failure

Failed examples:

rspec ./spec/models/usb_teensy_renderer_spec.rb:9 # USBTeensyRenderer when the correct USB port name is not present raises an error on instantiation

这是在类中引发错误的方式:

def initialize
  begin
    @sp = SerialPort.new("/dev/tty.usbmodem54121", 9600, 8, 1)
  rescue
    raise USBInitError, "USB output couldn't be initialized"
  end
  @sp.get_modem_params()
end

【问题讨论】:

标签: ruby rspec


【解决方案1】:

我相信在这种情况下,expect 应该会阻止:

expect { renderer = USBTeensyRenderer.new }.to raise_error(USBInitError)

这个帖子对 expect() 与 expect {}

有很好的解释

Rspec: expect vs expect with block - what's the difference?

【讨论】:

  • 没错,当然——因为在块中定义它会让期望方法在需要时而不是之前调用它。谢谢!
猜你喜欢
  • 2014-05-13
  • 2019-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多