Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec: Expecting method to raise an error fails

Tags:

ruby

rspec

I'm trying to test that an error is raised correctly under certain conditions. In this spec, the error is raised, but the test still fails. What am I doing wrong?

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

And the terminal output of '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

Here's how the error is raised in the class:

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
like image 731
Duncan Malashock Avatar asked Apr 26 '15 16:04

Duncan Malashock


1 Answers

I believe expect should take a block in this case:

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

This thread has a pretty good explanation on expect() vs expect {}

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

like image 141
fylooi Avatar answered Sep 25 '22 01:09

fylooi