[mocha-developer] mocking missing methods

James Mead jamesmead44 at gmail.com
Wed Mar 7 05:14:48 EST 2007


On 06/03/07, Dan North <dan at tastapod.com> wrote:
>
> 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?
>
> Cheers,
> Dan
>
> ps. James: so that's where you got to!
>

Hi Dan,

Good to hear from you.

Something very close to this idea has been on the to-do list for a long
time, but I don't think we had thought of deferring the check to respond_to?
until the actual moment the method on the mock is called. Good idea. Of
course you'd be very welcome to send us a patch!

My understanding of Ruby is that if you implement method_missing on a class,
you should really implement respond_to? so that it reflects the methods that
method_missing can handle. Is that your understanding? I know that not all
Ruby libraries do this (notably ActiveRecord, at least when I last looked
some months ago).

Are you using Ruby in anger on a project?

-- 
James.
http://blog.floehopper.org


More information about the mocha-developer mailing list