Mocha Quickstart

I really must get round to writing some better documentation for Mocha, but in the meantime here’s a quickstart guide1.

Mocha adds a couple of new methods to all objects and classes – expects which sets up auto-verified expectations and stubs which stubs the method allowing any number of calls.

Both the expects and stubs methods actually return an expectation object. Relevant methods on an expectation are: at_least, at_least_once, never, raises, returns, times, with, yields which are hopefully fairly self-explanatory. If not there are some clues here

Mocking a class method

product =
assert_equal product, Product.find(1)

Mocking an instance method on a real object

product =

Stubbing instance methods on real object

prices = [stub(:pence => 1000), stub(:pence => 2000)]
product =
assert_equal [1000, 2000], product.prices.collect {|p| p.pence}

Stubbing an instance method on all instances of a class

product =
assert_equal 'stubbed_name',

Traditional mocking

object = mock()
object.expects(:expected_method).with(:p1, :p2).returns(:result)
assert_equal :result, object.expected_method(:p1, :p2)


object = stub(:method1 => :result1, :method2 => :result2)
assert_equal :result1, object.method1
assert_equal :result2, object.method2

1 I wrote these examples without checking them, so there may be some typos.