[mocha-developer] mocking missing methods

Dan North dan at tastapod.com
Tue Mar 6 05:42:57 EST 2007

Hi folks.

So I'm using mocha on a ruby project, and I really like it. One thing 
I've noticed is that it can be a bit "surprising" when I'm mocking 
methods that don't exist on an object, and I think there's an easyish fix.

At the moment, you use sheep = mock() to create a mock sheep. What I'd 
like to do is something like sheep = mock(Sheep), so the mock is typed. 
It's still duck-typed because the Sheep class is open, so I can set 
expectations on it like this:


and then use the sheep somewhere. But here's the cool bit.

When I invoke an expected method on the mock sheep (i.e. a method that 
matches an expectation), if the sheep is typed, it checks to see whether 
the type responds to the method (or if it implements method_missing). If 
neither of these is the case, it blows up like a regular sheep with a 
NoMethodError, rather than doing the expectation stuff.

The reason for deferring the failure until the method is invoked rather 
than failing fast like JMock does when the expectation is defined, is in 
case the method gets defined, or the Sheep class gets extended, between 
the mock being defined and the method being invoked.

Again, you would only get this behaviour if you created a typed mock, 
using sheep = mock(Sheep) rather than sheep = mock().

What do you think?


ps. James: so that's where you got to!

More information about the mocha-developer mailing list