[mocha-developer] Mocking objects to test Rails Controllers

Rob Sanheim rsanheim at gmail.com
Wed May 28 11:29:41 EDT 2008


On Wed, May 28, 2008 at 11:12 AM, Rick Moynihan <rick at calicojack.co.uk> wrote:
> Hi all,
>
> I'm currently considering the use of Mocha to aid in writing my Rails
> unit/functional tests.
>
> I currently have a Rails model which mixes in a series of methods to allow
> it to talk to an external service.  The code is roughly of this form:
>
> class Person < ActiveRecord::Base
>
>   include SMSNotifier
>
>   def send_notification(message)
>      send_sms(number,message)
>      # more code/interactions...
>   end
> end
>
> Assuming I want to test that a call to send_notification calls send_sms on
> the SMSNotifier module, what is the best way to use Mocha to do this?
> Obviously I don't want my tests calls to send_notification to actually do
> any SMS sending :-)
>
> I'm assuming Mocha can monkey-patch it's own method/expectations over the
> SMSNotifier module.  In Java, I'd use dependency injection, but I'm trying
> to find the Ruby way here.
>
> Also I've seen that Rails has a folder called test/mocks, can anyone provide
> any examples or links as to the use of this in Rails/Mocha?
>
> Thanks in advance for your assistance,

With mocha, this is very simple.  Say goodbye to DI, and forget the
builtin rails/mocks as well.

def test_sends_sms_with_number
  person = Person.new(:number => "5551234567")
  person.expects(:send_sms).with("5551234567", "test msg")
  person.send_notification("test msg")
end

That test will ensure your sms method gets called, and it also removes
its implementation so no actual web service calls are made.

- Rob

http://robsanheim.com
http://thinkrelevance.com


More information about the mocha-developer mailing list