Redefinindo uma instância singleton em Ruby
Como faço para redefinir um objeto singleton em Ruby? Eu sei que nunca se quer fazer isso emreal código, mas e quanto aos testes unitários?
Aqui está o que estou tentando fazer em um teste RSpec -
describe MySingleton, "#not_initialised" do
it "raises an exception" do
expect {MySingleton.get_something}.to raise_error(RuntimeError)
end
end
Ele falha porque um dos meus testes anteriores inicializa o objeto singleton. Eu tentei seguir o conselho de Ian White deisto link essencialmente monkey patches Singleton para fornecer um método reset_instance mas recebo uma exceção 'reset_instance' do método indefinido.
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
describe MySingleton, "#not_initialised" do
it "raises an exception" do
MySingleton.reset_instance
expect {MySingleton.get_something}.to raise_error(RuntimeError)
end
end
Qual é a maneira mais idiomática de fazer isso em Ruby?