2010-01-14 4 views
12

J'ai un bloc de code comme ceci:se moquant une erreur/exception rspec (et pas seulement son type)

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 

Je veux tester ce qui se passe dans cette section if e.response_code.to_i == 503. Je peux se moquer do_some_stuff de jeter le type d'exception:

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

mais comment puis-je moquer l'objet d'erreur lui-même pour revenir 503 lorsqu'il reçoit « RESPONSE_CODE »?

Répondre

21
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