2010-01-14 46 views
12

我有這樣的代碼塊:嘲諷在rspec的錯誤/異常(不只是它的類型)

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 

我想測試一下這是怎麼回事在if e.response_code.to_i == 503部分。我可以模擬do_some_stuff拋出正確類型的異常:

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

,但我怎麼嘲笑錯誤對象本身,返回503,當它接收到「RESPONSE_CODE」?

回答

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