Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mocking an error/exception in rspec (not just its type)

I have a block of code like this:

def some_method
  begin
    do_some_stuff
  rescue WWW::Mechanize::ResponseCodeError => e
    if e.response_code.to_i == 503
      handle_the_situation
    end
  end
end

I want to test what's going on in that if e.response_code.to_i == 503 section. I can mock do_some_stuff to throw the right type of exception:

whatever.should_receive(:do_some_stuff).and_raise(WWW::Mechanize::ResponseCodeError)

but how do I mock the error object itself to return 503 when it receives "response_code"?

like image 963
hoff2 Avatar asked Jan 14 '10 21:01

hoff2


People also ask

How do I mock a method in RSpec?

Mocking with RSpec is done with the rspec-mocks gem. If you have rspec as a dependency in your Gemfile , you already have rspec-mocks available.

How does a mock work RSpec?

Generally speaking, a mock is a replica or imitation of something. RSpec mocks, in the same sense, are an imitation of return values or method implementations. The ability to carry out this kind of imitation makes it possible to set expectations that specific messages are received by an object.

What is a double in Ruby?

So to really boil it down, a double is not meant to be used on the main character, but rather on one of the supporting roles, so the code of the test can focus on the main character.


1 Answers

require 'mechanize'

class Foo

  def some_method
    begin
      do_some_stuff
    rescue WWW::Mechanize::ResponseCodeError => e
      if e.response_code.to_i == 503
        handle_the_situation
      end
    end
  end

end

describe "Foo" do

  it "should handle a 503 response" do
    page = stub(:code=>503)
    foo = Foo.new
    foo.should_receive(:do_some_stuff).with(no_args)\
    .and_raise(WWW::Mechanize::ResponseCodeError.new(page))
    foo.should_receive(:handle_the_situation).with(no_args)
    foo.some_method
  end

end
like image 129
Wayne Conrad Avatar answered Oct 16 '22 05:10

Wayne Conrad