How to write down the rspec to test rescue block.?
Asked Answered
B

2

5

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..?

Buckskins answered 8/1, 2014 at 15:13 Comment(0)
U
12

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.

Urial answered 8/1, 2014 at 15:40 Comment(2)
Thanks Carletti. This is very helpful for me to test rescue block.Buckskins
It doesn't work when I'm trying to expect method to raise error when it's already rescued by the method.Amaryllidaceous
Z
2

you can stub with return error

for example you have class with method like this :

class Email
  def self.send_email
    # send email
  rescue
    'Error sent email'
  end
end

so rspec for raising error is

context 'when error occures' do
  it 'should return error message' do
    allow(Email).to receive(:send_email) { err }
    expect(Email.send_email).to eq 'Error sent email brand'
  end
end
Zakarias answered 21/12, 2020 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.