【问题标题】:RSpec failure on raise_errorraise_error 上的 RSpec 失败
【发布时间】:2016-03-01 12:10:36
【问题描述】:

我有一个简单的函数。

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 是我正在测试的内容时出现错误? 那么我应该如何测试引发的错误呢?

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    您必须将引发错误的方法移动到一个块中,如下所示:

    expect {check_num(0)}.to raise_error
    

    【讨论】:

    • expect{ } vs expect() - 我花了一段时间才发现差异
    猜你喜欢
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多