Hi,
I am using RSpec and want to test the constructor of a Singleton class more than one time.
How can I do this?
Best regards
Hi,
I am using RSpec and want to test the constructor of a Singleton class more than one time.
How can I do this?
Best regards
Does RSpec allow you do perform pre-test actions? Is so, you could add another method to you static class that cleared anything done during the constructor. Then just call that prior to each and every test.
Refactor it into a class that can be constructed multiple times. This has the side-effect (some would say benefit) of removing the Singleton nature from the class.
Look at it another way: you've found a need to call the constructor more than once. Why should the class only construct one instance? What benefit is Singleton providing?
You can simply make a new it
and block for each spec. Break down your spec to a testable unit. Use "before" and "after" to set up and clears up anything you did.
before(:each)
and after(:each)
are executed for every it
block.
Hi,
have a look at http://blog.ardes.com/2006/12/11/testing-singletons-with-ruby:
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
People use singletons because "global variables are bad, m'kay?" A singleton is a global variable, sequestered in a name space, and with lazy instantiation. Consider whether a true global variable might simplify things, especially if you don't need lazy instantiation.