在Rspec中测试STDOUT输出

use*_*710 42 ruby rspec rspec2

我正在尝试为此声明构建一个规范.'puts'很容易

print "'#{@file}' doesn't exist: Create Empty File (y/n)?"
Run Code Online (Sandbox Code Playgroud)

Pat*_*ity 82

RSpec 3.0+

RSpec 3.0 为此添加了一个新的output匹配器:

expect { my_method }.to output("my message").to_stdout
expect { my_method }.to output("my error").to_stderr
Run Code Online (Sandbox Code Playgroud)

MINITEST

Minitest也有一些叫做capture_io:

out, err = capture_io do
  my_method
end

assert_equals "my message", out
assert_equals "my error", err
Run Code Online (Sandbox Code Playgroud)

RSpec <3.0(及其他)

对于RSpec <3.0和其他框架,您可以使用以下帮助程序.这将允许您捕获分别发送到stdout和stderr的任何内容:

require 'stringio'

def capture_stdout(&blk)
  old = $stdout
  $stdout = fake = StringIO.new
  blk.call
  fake.string
ensure
  $stdout = old
end

def capture_stderr(&blk)
  old = $stderr
  $stderr = fake = StringIO.new
  blk.call
  fake.string
ensure
  $stderr = old
end
Run Code Online (Sandbox Code Playgroud)

现在,当你有一个方法应该打印到控制台的东西

def my_method
  # ...
  print "my message"
end
Run Code Online (Sandbox Code Playgroud)

你可以这样编写一个规范:

it 'should print "my message"' do
  printed = capture_stdout do
    my_method # do your actual method call
  end

  printed.should eq("my message")
end
Run Code Online (Sandbox Code Playgroud)