Archive for the ‘Testing’ Category

Mock testing with mocha

Wednesday, September 12th, 2007

Mocha is a library designed to let you mock objects in your test environment. It’s very useful for testing around external dependencies

Inside one of my controllers I am calling a SOAP Service:

message_result = SOAPService.send_message(message)

This leaves me with a problem in my functional test - external dependencies are not conduive to self-contained test. Enter Mocha to the rescue!

Mocha lets me create a stub for a method on any instance of my object. This means that I can intercept the calls in my test, without needing to touch the code inside my controller.

SOAPService.any_instance.stubs(:send_message).returns( MessageResult.new )
get :respond
assert_match(/1<\/status>/, @response.body)

The get :respond call above would normally invoke a SOAP call, but using any_instance.stubs(:send_message).returns( MessageResult.new ) means that the SOAPService.send_message method now will return a new MessageResult. My controller doesn’t care and now my functional test is tight and focussed, and tests the controller logic without the external dependency being a factor.

Did you find this Ruby on Rails article useful? Why not recommend Toby at Working With Rails?

Facebook Apps are very hard to debug

Tuesday, September 4th, 2007