[mocha-developer] mocking singletons

James Mead jamesmead44 at gmail.com
Tue Aug 21 03:38:10 EDT 2007

On 21/08/07, Justin Perkins <justin at spiceworks.com> wrote:
> How can I safely mock a singleton without the mocked method living on
> outside the scope of the test method?

This is one of the things Mocha takes care of for you in the context of a
test method.

I've run into this problem with mocking methods on globals (gasp!) in
> the past by doing something like
> def mock_my_global
>    original = $my_global
>    $my_global.expects(:foo).returns('bar')
>    yield
>    $my_global = original
> end
> Is there something similar I can do for a singleton? Right now I have
> this:
> def mock_my_singleton
>    m = mock("my singleton")
>    m.expects(:foo).returns('bar')
>    MySingleton.expects(:instance).returns(m)
>    yield
> end

Do something like the following...

def test_me
  m = mock("my singleton")
  # Mocha modifies the MySingleton#instance method at this point.
  # From now until the end of the test it will return the mock.
  # At the end of the test it will be reverted to its original

You don't need to explicitly revert the method to its original
implementation - Mocha does it for you.

list mods: I sent a previous message to the list but my membership
> was pending so my message is too. This message is more concise than
> my previous one so please do not approve it :)

No problems. Thanks for letting me know.


More information about the mocha-developer mailing list