如何在Ruby中重置单个对象?我知道在真正的代码中我们永远不想这样做但是单元测试呢?
这是我在RSpec测试中尝试做的事情 -
describe MySingleton, "#not_initialised" do
it "raises an exception" do
expect {MySingleton.get_something}.to raise_error(RuntimeError)
end
end
Run Code Online (Sandbox Code Playgroud)
它失败是因为我之前的一个测试初始化了单例对象.我试过从这个链接开始关注Ian White的建议,它基本上是猴子补丁Singleton来提供reset_instance方法,但我得到一个未定义的方法'reset_instance'异常.
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
Run Code Online (Sandbox Code Playgroud)
在Ruby中最常用的方法是什么?
我正在使用RSpec并且想要多次测试Singleton类的构造函数.
我怎样才能做到这一点?
最好的祝福