Ruby:如果引发了正确的错误,如何返回布尔值?

时间:2014-01-30 21:13:17

标签: ruby testing

我有兴趣比较是否为我的代码引发了正确的错误。 如果引发了正确的错误,则返回true,否则返回false。

有办法解决吗?或者我需要编写异常处理吗?

例如,

some_method(arg) == TypeError # => true

3 个答案:

答案 0 :(得分:3)

  

当引发异常但尚未处理时(在救援中,确保,at_exit和END阻止),全局variable $! will contain the current exception和$ @包含当前异常的回溯。

执行以下操作(使用内联rescue方式):

2.0.0-p0 :001 > [1, 2, 3].first("two")
TypeError: no implicit conversion of String into Integer
    from (irb):1:in 'first'
    from (irb):1
    from /home/kirti/.rvm/rubies/ruby-2.0.0-p0/bin/irb:16:in '<main>'
2.0.0-p0 :002 > [1, 2, 3].first("two") rescue $!.class == TypeError
 => true 
2.0.0-p0 :003 > [1, 2, 3]['a'] rescue $!.class == TypeError
 => true 
2.0.0-p0 :004 > [1, 2, 3]['a']
TypeError: no implicit conversion of String into Integer
    from (irb):4:in '[]'
    from (irb):4
    from /home/kirti/.rvm/rubies/ruby-2.0.0-p0/bin/irb:16:in '<main>'
2.0.0-p0 :005 > 1/0 rescue $!.class == TypeError
 => false 
2.0.0-p0 :006 > 

TypeError

  

遇到不符合预期类型的​​对象时触发。

[1, 2, 3].first("two")
  

引发异常:    TypeError:没有将String隐式转换为整数

在您的情况下,您可以写如下:

some_method(arg) rescue $!.class == TypeError

答案 1 :(得分:2)

错误处理似乎很简单:

begin
  some_method(arg)
  false
rescue TypeError
  true
end

答案 2 :(得分:0)

如果您使用rspec进行测试,则可以执行以下操作:

expect { some_method(arg) }.to raise_error(TypeError)

-> { some_method(arg) }.should raise_error(TypeError)