How to stub out global logging function in rspec examples

主宰稳场 提交于 2019-12-11 09:01:25

问题


I am working with some code which logs to a global static logging class, e.g.:

GlobalLog.debug("Some message")

However in my tests, I don't want to include the real log, because it introduces a lot of unwanted dependencies. So I want to mock it out:

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

Unfortunately, because doubles are cleared out after each example, this isn't allowed:

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

If I change the before(:all) to before(:each), the code works, but I get a warning:

warning: already initialized constant GlobalLog

This is clogging up my test output, so I'd like to avoid the warning. Is there a clean solution?


回答1:


Define GlobalLog once in your spec_helper.rb.

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

You could throw it in spec/support if you want to be cleaner about it.




回答2:


Why won't you stub original GlobalLog object method?

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


来源:https://stackoverflow.com/questions/19175823/how-to-stub-out-global-logging-function-in-rspec-examples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!