views:

188

answers:

5

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

A: 

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.

Chris Arnold
RSpec has "before" and "after" blocks. http://rspec.info/documentation/before_and_after.html
TK
But the constructor won't get called twice because of the Singleton Pattern.
brainfck
A: 

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?

Graham Lee
The constructor does not need to get called more than once but I want to keep my specs clear - so I am testing only one part of the constructor in each spec.
brainfck
A: 

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.

TK
+1  A: 

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
Nicolai Reuschling
A: 

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.

Wayne Conrad