2012-03-22 12 views
6

Başla/kurtarma bloğu olan bir yöntem var. Kurtarma bloğunu RSpec2 kullanarak nasıl test edebilirim?RSpec'i kullanma Kurtarma istisnası bloğunun sonuçlarını nasıl test edebilirim

class Capturer 

    def capture 
    begin 
     status = ExternalService.call 
     return true if status == "200" 
     return false 
    rescue Exception => e 
     Logger.log_exception(e) 
     return false 
    end 
    end 

end 

describe "#capture" do 
    context "an exception is thrown" do 
    it "should log the exception and return false" do 
     c = Capturer.new 
     success = c.capture 
     ## Assert that Logger receives log_exception 
     ## Assert that success == false 
    end 
    end 
end 
+1

FYI, [Neden Ruby'de istisna kurtarma için kötü bir stile neden oluyor?] (Https://stackoverflow.com/q/10048173/211563). –

cevap

8

Kullanım should_receive ve should be_false:

context "an exception is thrown" do 
    before do 
    ExternalService.stub(:call) { raise Exception } 
    end 

    it "should log the exception and return false" do 
    c = Capturer.new 
    Logger.should_receive(:log_exception) 
    c.capture.should be_false 
    end 
end 

Ayrıca Exception den kurtarmak, ama bir şey daha spesifik gerektiğini unutmayın. Exception, her şeyi kapsar, bu kesinlikle istediğiniz gibi değildir. En çok, varsayılan olan StandardError'dan kurtarmanız gerekir.

+0

Evet, ancak bu istisnayı yükseltmiyor. – Nick

+0

Sorunuz bu bölümü gerçekten sormuyor, ancak sorumu yine de ek bir notla güncelledim. –

+0

Özellikle soruyor ** Kurtarma bloğunu RSpec2'yi kullanarak nasıl test edebilirim? ** – Nick

İlgili konular