我有一个简单的函数想要测试(可能主要是为了安抚 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/