问题
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