Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Why won't you stub original GlobalLog object method?

before(:each)
  GlobalLog.stub(:debug)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top