[mocha-developer] mocking missing methods

David Chelimsky dchelimsky at gmail.com
Tue Mar 6 08:52:29 EST 2007

On 3/6/07, Dan North <dan at tastapod.com> wrote:
> 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:
> sheep.expects(:chew).with('grass')
> 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?

We've got an open feature request for this in rspec as well, but with
the ability to configure a test run to either report or not report
these errors. The idea being that reporting that Sheep won't respond
to certain messages can be a distraction from the work you're doing on
Shepherd, but then when the task at hand reaches a good breaking
point, you can run your tests w/ some flag that says "please tell me
all the messages that I've mocked that I must now implement".

I'd love to see this feature in mocha because it seems really useful
in a test driven world, and because the day is not far off when rspec
will support using mocha in addition to its own mock framework. The
closer to parity of features we can get, the more likely people will
be interested in using mocha within rspec.


> Cheers,
> Dan
> ps. James: so that's where you got to!
> _______________________________________________
> mocha-developer mailing list
> mocha-developer at rubyforge.org
> http://rubyforge.org/mailman/listinfo/mocha-developer

More information about the mocha-developer mailing list