在 Rspec 中测试 STDOUT 输出 [英] Testing STDOUT output in Rspec

查看:41
本文介绍了在 Rspec 中测试 STDOUT 输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to build a spec for this statement. It is easy with 'puts'

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

推荐答案

RSpec 3.0+

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

RSpec 3.0+

RSpec 3.0 added a new output matcher for this purpose:

expect { my_method }.to output("my message").to_stdout
expect { my_method }.to output("my error").to_stderr

迷你测试

Minitest 还有一个叫做 capture_io:

out, err = capture_io do
  my_method
end

assert_equals "my message", out
assert_equals "my error", err

RSpec <3.0(和其他)

对于 RSpec <3.0等框架,可以使用下面的helper.这将允许您分别捕获发送到 stdout 和 stderr 的任何内容:

RSpec < 3.0 (and others)

For RSpec < 3.0 and other frameworks, you can use the following helper. This will allow you to capture whatever is sent to stdout and stderr, respectively:

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

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

Now, when you have a method that should print something to the console

def my_method
  # ...
  print "my message"
end

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

you can write a spec like this:

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

  printed.should eq("my message")
end

这篇关于在 Rspec 中测试 STDOUT 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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