1

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?

1 Answer 1

6

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

expect {check_num(0)}.to raise_error
1
  • expect{ } vs expect( ) - took me a while to spot the difference
    – Matt
    May 11, 2021 at 20:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.