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
The Singleton pattern is a useful pattern in Android development, and Java development at large. The Singleton pattern is defined as follows: In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object.
Unless, that is, you (1) make the singleton implement an interface, and (2) inject the singleton to your class using that interface. For example, singletons are typically instantiated directly like this: public class MyClass { private MySingleton __s = MySingleton. getInstance() ; ... }
Singleton classes do not allow for Test Driven Development (TDD) The laws of TDD. Unit testing depends on tests being independent of one another, so the tests can be run in any order and the program can be set to a known state before the execution of every unit test.
It's hard to test code that uses singletons.You can't control the creation of the singleton object because often it is created in a static initializer or static method. As a result, you also can't mock out the behavior of that Singleton instance.
Singleton classes essentially do this
def self.instance
@instance ||= new
end
private_class_method :new
So you can bypass the memoization altogether by calling the private method new using send
let(:instance) { GlobalClass.send(:new) }
A nice benefit of this way is that no global state is modified as a result of your tests running.
Probably a better way, from this answer:
let(:instance) { Class.new(GlobalClass).instance }
This creates an anonymous class which inherits from GlobalClass
, which all class-level instance variables are stored in. This is then thrown away after each test, leaving GlobalClass
untouched.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With