watch this  

the official mrchucho blog

Unit Testing Ruby Singletons

Posted 2006 Oct 31

I found an interesting post via reddit about how the Singleton pattern is incompatible with Unit Testing. I’ve certainly encountered difficulties unit testing a Singleton that maintains any sort of state. I posted the following as a comment, but my code didn’t format properly, so here it is:

I’ve encountered this problem recently using Ruby. Thankfully, with Ruby I can create a singleton of my Singleton class for use in my unit tests. In this test-specific singleton I can add “reset” or “clear” method to reset the state. Assuming I have a singleton called “OnlyOne”:
def test_singleton
  class << OnlyOne.instance
    def reset
      # reset state
    end
  end

  OnlyOne.instance.modify_state
  OnlyOne.instance.reset  
end

Responses to "Unit Testing Ruby Singletons"

No responses yet.

Comments are now closed.
atom rss