I have an rspec where I am testing if an exception thrown from method1 is rescued and raised again in method2 (method2 calls method1). But the RSpec seems to fail. I have debugged through the code and can see the exception being raised.
it 'should check for exceptions raised' do
allow(TestClass).to receive(:method1) do
raise ::Test::CustomException.new(1, 'test.csv.gz', StandardError.new('test exception'))
end
expect(#test_class.method2).to raise_error(Test::CustomException)
end
method2
tester["key_list"].each do |key|
begin
TestClass.method1(key, self.id) do |row|
#do something
end
rescue Test::CustomException => exception
raise ::Test::CustomException.new(self.id, key, exception)
end
end
method1
begin
#do something
rescue => exc
raise ::Test::CustomException.new(id, key, exc)
end
end
CustomException as the name says is a custom defined exception that takes in 3 parameters
Error:
Failures:
should check for exceptions raised
Failure/Error: expect(#test_class.method2).to raise_error
Test::CustomException:
true
test_class.rb:146:in `rescue in block method'
Related
Is there a way to rspec test if an error was raised and rescued? If I have a rescue, my rspec test does not see the raised error, only results in the rescue?
module MyApp
def some_method(msg)
raise StandardError.new(msg)
end
def second_method(msg)
begin
count = 0
some_method(msg)
rescue StandardError=> e
puts e
count = 1
end
end
end
RSpec.describe Myapp do
describe "#some_method" do
it "should raise error" do
expect {
some_method("this is an error")
}.to raise_error(StandardError) {|e|
expect(e.message).to eql "this is an error"
}
end
end
# this fails, as the error is not raised
describe "#second_method" do
it should raise error and rescue do
expect {
a = second_method("this is an error and rescue")
}.to raise_error(StandardError) {|e|
expect(e.message).to eql "this is an error and rescue"
expect(a) = 1
}
end
end
end
You generally don't want to raise or rescue StandardError directly because it's pretty uninformative, and won't catch errors outside of the StandardError hierarchy. Instead, you generally want to test that a specific exception was raised, or that a specific error class or error message was raised.
If you know the custom or built-in exception class that you want, or the specific error message, then test for that explicitly. For example:
it 'should raise an ArgumentError exception' do
expect { MyApp.new.foo }.to raise_error(ArgumentError)
end
it 'should raise MyCustomError' do
expect { MyApp.new.foo }.to raise_error(MyCustomError)
end
it 'should raise StandardError with a custom message' do
msg = 'this is a custom error and rescue'
expect { MyApp.new.foo }.to raise_error(msg)
end
If you don't know (or care about) the specific exception or message that should be raised, but you expect some exception to interrupt the execution flow, then you should use a bare raise_error matcher. For example:
it "should raise an exception" do
expect { MyApp.new.foo }.to raise_error
end
I need to catch a NameError in a special case. But I don't want to catch all SubClasses of NameError. Is there a way to achieve this?
# This shall be catched
begin
String::NotExistend.new
rescue NameError
puts 'Will do something with this error'
end
# This shall not be catched
begin
# Will raise a NoMethodError but I don't want this Error to be catched
String.myattribute = 'value'
rescue NameError
puts 'Should never be called'
end
You can also do it in a more traditional way
begin
# your code goes here
rescue NoMethodError
raise
rescue NameError
puts 'Will do something with this error'
end
You can re-raise exception if its class is different than a given:
begin
# your code goes here
rescue NameError => exception
# note that `exception.kind_of?` will not work as expected here
raise unless exception.class.eql?(NameError)
# handle `NameError` exception here
end
You can also check the exception message and decide what to do.
Here is an example using the code you provided.
# This shall be catched
begin
String::NotExistend.new
rescue NameError => e
if e.message['String::NotExistend']
puts 'Will do something with this error'
else
raise
end
end
# This shall not be catched
begin
# Will raise a NoMethodError but I don't want this Error to be catched
String.myattribute = 'value'
rescue NameError => e
if e.message['String::NotExistend']
puts 'Should never be called'
else
raise
end
end
begin
raise "explosion"
rescue
p $!
raise "Are you mad"
p $!
end
# #<RuntimeError: explosion>
# RuntimeError: Are you mad
# from (irb):5:in `rescue in irb_binding'
# from (irb):1
# from /usr/bin/irb:12:in `<main>'
$! always holds only the current exception object reference.
But is there any way to get a reference to the original exception object (here it is "explosion"), after another exception has been raised? <~~~ Here is my question.
Myself tried and reached to the answer,hope now it is more clearer to all who was in Smokey situation with my queries.
Are you saying you want to have reference to the original exception when you rescue the second exception? If so, then you need to capture the original exception in a variable during the rescue. This is done by doing:
rescue StandardError => e
where StandardError can be any type of exception or omitted (in which case StandardError is the default).
For example, the code:
begin
raise "original exception"
rescue StandardError => e
puts "Original Exception:"
puts $!
puts e
begin
raise "second exception"
rescue
puts "Second Exception:"
puts $!
puts e
end
end
Gives the output:
Original Exception:
original exception
original exception
Second Exception:
second exception
original exception
As you can see e has stored the original exception for use after the second exception.
class MyError < StandardError
attr_reader :original
def initialize(msg, original=$!)
super(msg)
#original = original;
end
end
begin
begin
raise "explosion"
rescue => error
raise MyError, "Are you mad"
end
rescue => error
puts "Current failure: #{error.inspect}"
puts "Original failure: #{error.original.inspect}"
end
OUTPUT
Current failure: #<MyError: Are you mad>
Original failure: #<RuntimeError: explosion>
=> nil
I have a method that calls two other methods:
def first_method
second_method
# Don´t call this method when something went wrong before
third_method
end
The second_method calls other methods:
def second_method
fourth_method
fifth_method
end
Let´s say the fifth_method has a begin/rescue statement:
def fifth_method
begin
# do_something
rescue Error => e
#
end
end
Now I want to avoid third_method to be called when fifth_method throws an error. How would I/you solve this most elegantly in Ruby.
It seems to me so obvious but anyway
def first_method
begin
second_method
rescue
return
end
third_method
end
This construction (without explicit type of exception) will catch StandartError exception.
To avoid intersection with another exceptions you can create your own exception class:
class MyError < StandardError; end
and then use it
begin
second_method
rescue MyError => e
return
end
Note that you should not inherit exception from Exception because this type of exceptions are from environment level, where the exceptions of StandardError are meant to deal with application level errors.
I think the simplest way is removing error catching from fifth_method and move it to the first_method
def first_method
begin
second_method
third_method
rescue Error => e
end
end
def fifth_method
# do_something
end
If you don't want to use exceptions, you can just return a status:
def fifth_method
# do_something
true
rescue Error => e
false
end
def first_method
if second_method
third_method
end
end
I'm looking for something like this:
raise Exception rescue nil
But the shortest way I've found is this:
begin
raise Exception
rescue Exception
end
This is provided by ActiveSupport:
suppress(Exception) do
# dangerous code here
end
http://api.rubyonrails.org/classes/Kernel.html#method-i-suppress
def ignore_exception
begin
yield
rescue Exception
end
end
Now write you code as
ignore_exception { puts "Ignoring Exception"; raise Exception; puts "This is Ignored" }
Just wrap the left-hand side in parenthesis:
(raise RuntimeError, "foo") rescue 'yahoo'
Note that the rescue will only happen if the exception is a StandardError or a subclass thereof. See http://ruby.runpaint.org/exceptions for more info.