using mocha, is there a way to stub with many parameters?
Asked Answered
G

1

11

Let's assume that i have this class

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

I can stub whole bar method using:

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

However if I only want to stub when param1 of bar method is true, I couldn't find a way to do:

I also looked at with, and has_entry, and it seems it only applies to a single parameter.

I was expecting some function like this.

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

Thanks

................................................... EDITED THE FOLLOWING .............................................

Thanks, nash

Not familiar with rspec, so I tried with unit test with any_instance, and it seems work

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
Gendarmerie answered 9/3, 2012 at 17:48 Comment(1)
expects instead of stub also works fine for me. Foo.any_instance.expects(:bar).with { |*args| args[0]=='hee' }.returns('hee')Gendarmerie
H
11

If I got you right it can be something like:

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
Handclap answered 9/3, 2012 at 19:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.