Peter Marklund

Peter Marklund's Home


Ruby Testing: Avoid Stubbing Non-Existent Methods with Mocha

Mocks and stubs can be fragile and come back and bite you when they can get out of sync with your code. One way this can happen is that a method is renamed or you misspell the method name. To avoid this issue you can configure Mocha to disallow stubbing and mocking of non-existent methods. I've come up with two new methods for the cases where you are working with messages implemented with method_missing:

It is interesting to note that this extension of Mocha is possible because of its flexible and clever design. Mocha was recently updated to version 0.9.9. I am grateful to James Mead (Floehopper) for providing this excellent testing library.

2 comment(s)


Peter Marklund said 2010-11-03 15:24:

Thanks for the comment James! Using respond_to? sounds like a good idea to me except of course for the case where the respond_to? contract is not properly implemented. Therefore, you probably need to be able to relax any respond_to? constraint that Mocha adds.

floehopper said 2010-11-03 10:05:

Neat. It feels like Mocha ought to be able to use the "method_missing"/"respond_to?" contract to determine whether an object will respond to a particular method. I wonder whether the current default behaviour of the ":stubbing_non_existent_method configuration" option should work this way. I do remember a lot of problems getting that functionality working sensibly and can't remember why it doesn't currently check the "respond_to?" method. I'll have a think... Cheers, James.