ruby - 我可以在 RSpec 中 stub STDERR 吗?

标签 ruby rspec stub

我有一个简单的函数想要测试(可能主要是为了安抚 simplecov)。函数是:

module Utils
  extend self

  def blather(msg)
    msg = "=== " + msg
    STDERR.puts(msg)
    Rails.logger.debug(msg)
  end

end

RSpec documentation for stubbing说:

Messages can be stubbed on any class, including those in Ruby's core library.

但是以下内容:

# file: spec/lib/utils_spec.rb
require 'spec_helper'
describe Utils do
  context "blather" do
    it "should print to STDERR" do
      STDERR.any_instance.should_receive(:puts).with("=== zoo")    
      Utils.blather("zoo")
    end
  end
end

...我得到一个错误

undefined method `any_instance' for #<IO:<STDERR>>

抛开这个测试是否有意义的问题,是否可以对 STDERR(IO 类)进行 stub ?这是因为它是一个类方法而失败吗?或者对于这种测试是否有更明智的策略?

最佳答案

首先,您通常应该使用 $stderr 而不是 STDERR

module Utils
  extend self

  def blather(msg)
    msg = "=== " + msg
    $stderr.puts(msg)
    Rails.logger.debug(msg)
  end

end

要回答您的问题,您可以在 RSpec 中执行以下操作:

describe Utils do
  context "blather" do
    it "should print to stderr" do
      $stderr.should_receive(:puts).with("=== zoo")
      Utils.blather("zoo")
    end
  end
end

您只需通过 $stderr.should_receive stub 该方法。因为 $stderr 是一个普通对象,您可以像普通对象一样在其上 stub 方法,并在其上设置期望。

关于ruby - 我可以在 RSpec 中 stub STDERR 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10108820/

相关文章:

Ruby 持续输出长时间运行的 shell 命令的标准输出

rspec - 如何测试 Mongoid 将生成的查询类型?

ruby-on-rails - rails/Rspec : Having an anonymous controller be of a certain class

unit-testing - 如何将特征对象的 stub 注入(inject) Rust 中的类型并保留对它的引用?

Ruby:定义函数原型(prototype)?

ruby-on-rails - 如何为 ActiveRecord 模型对象找到关联的 Resque 作业?

ruby - 用 Ruby 编写一个简单的网络服务器

ruby-on-rails - 在 Rspec 中创建的记录在新线程中不可用?

java - 通过比较两个查询参数来匹配wiremock请求

python - unittest.mock.patch 一个类实例,并设置方法返回值