DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Test Singletons
Method 1: Two classes. The first implements the functionality. The second gets the protection, i.e. it is the Singleton.
require 'singleton' class WorkingFoo # all the functionality end class SingleFoo < WorkingFoo implements Singleton end
In production use the second class, SigleFoo. For testing use the first class, WorkingFoo. Literature: Russ Olso, Design Paterns in Ruby, 2007 Method 2: If you don't own the code or if you fear missuse of the baseclass you can use metaprogramming. Ian White poposes a #reset_instance method
require 'singleton'
class <<Singleton
def included_with_reset(klass)
included_without_reset(klass)
class <<klass
def reset_instance
Singleton.send :__init__, self
self
end
end
end
alias_method :included_without_reset, :included
alias_method :included, :included_with_reset
end
More Info: http://blog.ardes.com/2006/12/11/testing-singletons-with-ruby





