如何在 rspec 示例中删除全局日志记录功能 [英] How to stub out global logging function in rspec examples

查看:35
本文介绍了如何在 rspec 示例中删除全局日志记录功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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/文档/范围

如果我将 before(:all) 更改为 before(:each),代码有效,但我收到警告:

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?

推荐答案

spec_helper.rb 中定义一次 GlobalLog.

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

如果你想更清楚,你可以把它放在 spec/support 中.

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

这篇关于如何在 rspec 示例中删除全局日志记录功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆