Ruby: How do I return a boolean value if the correct error is raised?
ruby, testing
Solution
When an exception has been raised but not yet handled (in rescue, ensure, at_exit and END blocks) the global variable $! will contain the current exception and $@ contains the current exception’s backtrace.
Do as below (using inline `rescue` way):
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`
Raised when encountering an object that is not of the expected type.
[1, 2, 3].first("two")
raises the exception: TypeError: no implicit conversion of String into Integer
In your case you could write as below :
some_method(arg) rescue $!.class == TypeError
Problem
I'm interested in comparing if the correct errors are raised for my code. If the correct error is raised then it returns true, otherwise false. Is there a way to go about it? Or would I need to write exception handling? For example, ``` some_method(arg) == TypeError # => true ```