2011-02-09 16 views
10

मैं कुछ छोटे रूबी कार्यक्रम लिखते समय टीडीडी सीखने पर काम कर रहा हूं। मेरे पास निम्न श्रेणी है:रुपयेपेक काम नहीं कर रहा है, या उठा नहीं उठा रहा है?

class MyDirectory 
    def check(dir_name) 
    unless File.directory?(dir_name) then 
     raise RuntimeError, "#{dir_name} is not a directory" 
    end 
    end 
end 

और मैं इसे इस आरएसपीसी परीक्षण के साथ परीक्षण करने की कोशिश कर रहा हूं।

describe MyDirectory do 
    it "should error if doesn't exist" do 
    one = MyDirectory.new 
    one.check("donee").should raise_exception(RuntimeError, "donee is not a directory") 
    end 
end 

यह कभी काम नहीं करता है, और मुझे समझ में नहीं आता कि आरएसपीसी आउटपुट से क्या गलत है।

Failures: 

    1) MyDirectory should error if doesn't exist 
    Failure/Error: one.check("donee").should raise_error(RuntimeError, "donee is not a directory") 
    RuntimeError: 
     donee is not a directory 
    # ./lib/directory.rb:4:in `check' 
    # ./spec/directory_spec.rb:9:in `block (2 levels) in <top (required)>' 

मुझे आशा है कि यह कुछ आसान है जो मुझे याद आ रही है, लेकिन मैं इसे देख नहीं रहा हूं।

उत्तर

33

यदि आप अपवाद की जांच कर रहे हैं, तो आपको इसे लैम्बडा के साथ अपने परीक्षण से अलग करना होगा या अपवाद बबल होगा।

lambda {one.check("donee")}.should raise_error(RuntimeError, "donee is not a directory") 

संपादित करें: के बाद से लोगों को अभी भी इस जवाब का उपयोग करें, यहाँ क्या Rspec 3 में क्या करना है:

expect{one.check("donee")}.to raise_error(RuntimeError, "donee is not a directory") 

लैम्ब्डा अब आवश्यक नहीं है, क्योंकि उम्मीद वाक्य रचना एक वैकल्पिक ब्लॉक लेता है।

+0

यह पूरी तरह से काम करता है, धन्यवाद! – gdziengel

+2

मैंने 'उम्मीद {...} के बजाय' उम्मीद (...)। 'का उपयोग किया' और 'इस उत्तर में अंततः मुझे गलती खोजने में मदद मिली! –

+0

ध्यान रखें कि यदि आप ब्लॉक का उपयोग करने के बजाय ब्रांड्स का उपयोग करते हैं तो अपवाद बबल हो सकता है। Https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers देखें ब्लॉक सिंटैक्स का उपयोग अपवादों की अपेक्षा के लिए किया जाना चाहिए। –

संबंधित मुद्दे