2012-03-09 22 views
6

मैं का उपयोग कर पूरे बार विधि ठूंठ कर सकते हैं मान लेते हैं मैं इस वर्गमोचा का उपयोग करके, क्या कई मानकों के साथ स्टब करने का कोई तरीका है?

class Foo 
    def bar(param1=nil, param2=nil, param3=nil) 
    :bar1 if param1 
    :bar2 if param2 
    :bar3 if param3 
    end 
end 

है कि दो:

Foo.any_instance.expects(:bar).at_least_once.returns(false) 

लेकिन अगर मैं केवल ठूंठ जब बार विधि के param1 सच है चाहता हूँ, मैं नहीं कर सका ऐसा करने का तरीका ढूंढें:

मैंने भी देखा, और है_इन्री, और ऐसा लगता है कि यह केवल एक पैरामीटर पर लागू होता है।

मुझे इस तरह के कुछ समारोह की उम्मीद थी।

Foo.any_instance.expects(:bar).with('true',:any,:any).returns(:baz1) 
Foo.any_instance.expects(:bar).with(any,'some',:any).returns(:baz2) 

धन्यवाद

...................................... ............. निम्नलिखित संपादित किया .................................. ...........

धन्यवाद, नैश

rspec से परिचित नहीं है, इसलिए मैं any_instance साथ इकाई परीक्षण के साथ की कोशिश की, और यह काम लगता है

require 'test/unit' 
require 'mocha' 

class FooTest < Test::Unit::TestCase 

    def test_bar_stub 
    foo = Foo.new 
    p foo.bar(1) 

    Foo.any_instance.stubs(:bar).with { |*args| args[0]=='hee' }.returns('hee') 
    Foo.any_instance.stubs(:bar).with { |*args| args[1]=='haa' }.returns('haa') 
    Foo.any_instance.stubs(:bar).with { |*args| args[2]!=nil }.returns('heehaa') 

    foo = Foo.new 
    p foo.bar('hee') 
    p foo.bar('sth', 'haa') 
    p foo.bar('sth', 'haa', 'sth') 
    end 

end 
+0

स्टब के बजाय अपेक्षा भी मेरे लिए ठीक काम करता है। Foo.any_instance.expects (: बार) .with {| * args | तर्क [0] == 'हे'}। पीछे हटना ('हे') – allenhwkim

उत्तर

7

यदि मैं आपको सही मिला तो यह कुछ ऐसा हो सकता है:

class Foo 
    def bar(param1=nil, param2=nil, param3=nil) 
    :bar1 if param1 
    :bar2 if param2 
    :bar3 if param3 
    end 
end 

describe Foo do 
    it "returns 0 for all gutter game" do 
    foo = Foo.new 
    foo.stub(:bar).with { |*args| args[0] }.and_return(:bar1) 
    foo.stub(:bar).with { |*args| args[1] }.and_return(:bar2) 
    foo.stub(:bar).with { |*args| args[2] }.and_return(:bar3) 
    foo.bar(true).should == :bar1 
    foo.bar('blah', true).should == :bar2 
    foo.bar('blah', 'blah', true).should == :bar3 
    end 
end 
संबंधित मुद्दे

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