在raise_error上RSpec失败

时间:2016-03-01 12:10:37

标签: ruby rspec

我有一个简单的功能。

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

尝试使用RSpec进行测试并进行以下测试:

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

这就是我在测试中得到的结果:

/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

为什么我在raise_error进行测试时遇到错误?{I} 我应该如何测试错误呢?

1 个答案:

答案 0 :(得分:2)

您必须在块中移动引发错误方法,如下所示:

expect {check_num(0)}.to raise_error
相关问题