Viktor
Viktor

Reputation: 4346

RSpec failure on raise_error

I have a simple function.

def check_num(num)
  if num.is_a?(Integer) && num > 0
    #...
  else
    raise 'NOT VALID'
  end
end

And trying to test it with RSpec with following test:

require 'find'

describe 'check_num' do

  describe 'errors' do

    it 'raises an error if parameter is 0' do
      expect(check_num(0)).to raise_error(RuntimeError)
    end

    it 'raises an error if parameter is less than 0' do
      expect(check_num(-1)).to raise_error(RuntimeError)
    end

    it 'raises an error if parameter is not a number' do
      expect(check_num('Heya, Am a string')).to raise_error(RuntimeError)
    end

  end

end

And this is what I'm getting with my test:

/home/duke/.rvm/rubies/ruby-2.2.3/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /home/duke/.rvm/gems/ruby-2.2.3/bin/rspec /home/duke/RubymineProjects/rspec_tutor/prime_numbers/spec/find_spec.rb --require teamcity/spec/runner/formatter/teamcity/formatter --format Spec::Runner::Formatter::TeamcityFormatter
Testing started at 15:04 ...

RuntimeError: NOT VALID
./lib/find.rb:37:in `check_num'
./spec/find_spec.rb:8:in `block (3 levels) in <top (required)>'
-e:1:in `load'
-e:1:in `<main>'

RuntimeError: NOT VALID
./lib/find.rb:37:in `check_num'
./spec/find_spec.rb:12:in `block (3 levels) in <top (required)>'
-e:1:in `load'
-e:1:in `<main>'

ArgumentError: comparison of String with 0 failed
./lib/find.rb:28:in `>'
./lib/find.rb:28:in `check_num'
./spec/find_spec.rb:16:in `block (3 levels) in <top (required)>'
-e:1:in `load'
-e:1:in `<main>'

3 examples, 3 failures, 0 passed

Finished in 0.004547262 seconds

Process finished with exit code 1

Why am I getting an error while raise_error is what exactly I'm testing? How should I test errors raising then?

Upvotes: 1

Views: 614

Answers (1)

Babar Al-Amin
Babar Al-Amin

Reputation: 3984

You'll have to move the raising error method in a block, like this:

expect {check_num(0)}.to raise_error

Upvotes: 6

Related Questions