Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write down the rspec to test rescue block.?

I have method like this

def className  
  def method_name
    some code  
  rescue  
    some code and error message  
  end  
end

So, How to write down the rspec to test rescue block..?

like image 521
Dheer Avatar asked Dec 16 '22 02:12

Dheer


1 Answers

If you want to rescue, it means you expect some code to raise some kind of exception.

You can use RSpec stubs to fake the implementation and force an error. Assuming the execution block contains a method that may raise

def method_name
  other_method_that_may_raise
rescue => e
  "ERROR: #{e.message}"
end

hook the stub to that method in your specs

it " ... " do
  subject.stub(:other_method_that_may_raise) { raise "boom" }
  expect { subject.method_name }.to_not raise_error
end

You can also check the rescue handler by testing the result

it " ... " do
  subject.stub(:other_method_that_may_raise) { raise "boom" }
  expect(subject.method_name).to eq("ERROR: boom")
end

Needless to say, you should raise an error that it's likely to be raised by the real implementation instead of a generic error

{ raise FooError, "boom" }

and rescue only that Error, assuming this is relevant.


As a side note, in Ruby you define a class with:

class ClassName

not

def className

as in your example.

like image 200
Simone Carletti Avatar answered Dec 30 '22 07:12

Simone Carletti