[mocha-developer] mocking singletons

Justin Perkins justin at spiceworks.com
Mon Aug 20 21:26:50 EDT 2007


How can I safely mock a singleton without the mocked method living on  
outside the scope of the 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

Thanks for your help.

-justin

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 :)




More information about the mocha-developer mailing list