相关疑难解决方法(0)

重置Ruby中的单例实例

如何在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中最常用的方法是什么?

ruby singleton rspec rspec2

20
推荐指数
3
解决办法
8481
查看次数

如何测试Singleton类?

我正在使用RSpec并且想要多次测试Singleton类的构造函数.

我怎样才能做到这一点?

最好的祝福

ruby testing singleton rspec

11
推荐指数
3
解决办法
4873
查看次数

标签 统计

rspec ×2

ruby ×2

singleton ×2

rspec2 ×1

testing ×1