我正在测试将一些消息(带有 puts、p 警告等)放在控制台上的类。我只是想知道在 RSpec 测试期间是否有任何抑制此输出的能力?
最佳答案
我通过将 $stout
重定向到文本文件来抑制类中的 puts
输出。这样,如果我出于任何原因需要查看输出,它就在那里,但不会混淆我的测试结果。
#spec_helper.rb
RSpec.configure do |config|
config.before(:all, &:silence_output)
config.after(:all, &:enable_output)
end
public
# Redirects stderr and stout to /dev/null.txt
def silence_output
# Store the original stderr and stdout in order to restore them later
@original_stderr = $stderr
@original_stdout = $stdout
# Redirect stderr and stdout
$stderr = File.new(File.join(File.dirname(__FILE__), 'dev', 'null.txt'), 'w')
$stdout = File.new(File.join(File.dirname(__FILE__), 'dev', 'null.txt'), 'w')
end
# Replace stderr and stdout so anything else is output correctly
def enable_output
$stderr = @original_stderr
$stdout = @original_stdout
@original_stderr = nil
@original_stdout = nil
end
编辑:
针对@MyronMarston 的评论,将方法作为 block 直接插入before
和after
可能会更聪明。
#spec_helper.rb
RSpec.configure do |config|
original_stderr = $stderr
original_stdout = $stdout
config.before(:all) do
# Redirect stderr and stdout
$stderr = File.new(File.join(File.dirname(__FILE__), 'dev', 'null.txt'), 'w')
$stdout = File.new(File.join(File.dirname(__FILE__), 'dev', 'null.txt'), 'w')
end
config.after(:all) do
$stderr = original_stderr
$stdout = original_stdout
end
end
它看起来更干净一些,并且让方法远离 main
。
另外请注意,如果您使用的是 Ruby 2.0,则可以使用 __dir__
而不是 File.dirname(__FILE__)
。
EDIT2
还应该提到的是,您可以使用 File::NULL
转发到真正的操作系统 /dev/null
,因为它是在 Ruby v 1.9.3 中引入的. (jruby 1.7)
然后代码片段将如下所示:
#spec_helper.rb
RSpec.configure do |config|
original_stderr = $stderr
original_stdout = $stdout
config.before(:all) do
# Redirect stderr and stdout
$stderr = File.open(File::NULL, "w")
$stdout = File.open(File::NULL, "w")
end
config.after(:all) do
$stderr = original_stderr
$stdout = original_stdout
end
end
关于ruby - 在 RSpec 测试期间抑制控制台输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15430551/