Mocha Quickstart
Posted by James Mead Fri, 01 Sep 2006 14:07:00 GMT
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
product = Product.new
Product.expects(:find).with(1).returns(product)
assert_equal product, Product.find(1) product = Product.new
product.expects(:save).returns(true)
assert product.save prices = [stub(:pence => 1000), stub(:pence => 2000)]
product = Product.new
product.stubs(:prices).returns(prices)
assert_equal [1000, 2000], product.prices.collect {|p| p.pence} Product.any_instance.stubs(:name).returns('stubbed_name')
product = Product.new
assert_equal 'stubbed_name', product.name 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.method21 I wrote these examples without checking them, so there may be some typos.

Hi,
First of all, let me say, Mocha looks awesome and I’m really looking forward to using it (I’m a TDD newb you might say). However, when I tried to start using it on a Rails app, I encountered an error. It was something along the lines of “User object doesn’t have expects method”. I know I required it above the test case and also tried including it in the test_helper file (I installed it as a gem). Do you have any idea what I could be doing wrong?
Have you required ‘stubba’ as well as ‘mocha’?
The latest svn HEAD does away with the distinction between ‘mocha’ & ‘stubba’, but the latest gem (mocha-0.3.2) is a bit out-of-date and you need to require both.
You need ‘stubba’ if you need to do something like this…
or…
Please use the mailing list for any other queries – thanks.
Thanks James. I’ll use the mailing list next time.