[mocha-developer] Scoping expectations and more ...

Gabriel Birke gabriel.birke at gmail.com
Sat Dec 2 09:33:12 EST 2006


Hello!

I'm new to Mocha and through experimentation I found out something
that is not explicitly stated in the documentation: If you need to
mock the same function call with different parameters and results, you
can set the scope of expectations with a begin ... end block.

I also made up an example on how to expect more than one function call
with different parameters and return values.

Someday I will have a blog where I can publish this example, for now I
send it to the mailing list:

# This is the object we will mock
class A
  def m(p)
    return p+1
  end
end

# This is teh object we will test
class B
  def m(p)
    a = A.new
    a.m(p)
  end

  def calltwice(p)
    a = A.new
    a.m(p+1)+a.m(p+2)
  end
end


require 'test/unit'
require 'rubygems'
require 'mocha'
require 'stubba'

class BTest < Test::Unit::TestCase

  # This test demonstrates how you can call a function that calls a mocked
  # object more than one time in the same test
  def test_m_call
    b = B.new
    begin
      A.any_instance.expects(:m).with(5).returns(6)
      assert_equal 6, b.m(5)
    end
    begin
      A.any_instance.expects(:m).with(9).returns(10)
      assert_equal 10, b.m(9)
    end
  end

  # This test demonstrates how to mock objects where the method is called
  # more than one time with different parameters and different results
  def test_twocall
    b = B.new
    params = [6,7]
    results = [7, 8]
    e = A.any_instance.expects(:m)
    e.with {|p| p == params.shift}
    e.returns(lambda {results.shift})
    e.times(2)
    assert_equal 15, b.calltwice(5)
  end

end


More information about the mocha-developer mailing list