如何在rspec示例中存根全局日志记录function

我正在使用一些记录到全局静态日志记录类的代码,例如:

GlobalLog.debug("Some message") 

但是在我的测试中,我不想包含真正的日志,因为它引入了许多不需要的依赖项。 所以我想嘲笑它:

 describe "some function" do before(:all) do log = double('log') GlobalLog = log log.stub(:debug) end ... end 

不幸的是,因为在每个示例之后清除了双精度数,所以不允许这样做:

https://www.relishapp.com/rspec/rspec-mocks/docs/scope

如果我将before(:all)更改为before(:each) ,代码可以正常工作,但是我收到警告:

 warning: already initialized constant GlobalLog 

这会堵塞我的测试输出,所以我想避免警告。 有清洁的解决方案吗?

spec_helper.rb定义GlobalLog一次。

 class GlobalLog class << self [:info, :debug, :warn, :error].each do |method| define_method(method) {|*|} end end end 

如果你想要更清洁,你可以把它扔进spec/support

为什么不存根原始的GlobalLog对象方法?

 before(:each) GlobalLog.stub(:debug) end