RSpec:期望引发错误的方法失败

时间:2015-04-26 16:38:32

标签: ruby rspec

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

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

1 个答案:

答案 0 :(得分:14)

我认为在这种情况下应该采取阻止措施:

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

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

有很好的解释

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