使用 RSpec 测试命令行输出 [英] Test output to command line with RSpec

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

问题描述

我想做的是在命令行上运行ruby sayhello.rb,然后从Rspec接收Hello.

I want to do is run ruby sayhello.rb on the command line, then receive Hello from Rspec.

我有这个:

class Hello
  def speak
    puts 'Hello from RSpec'
  end
end

hi = Hello.new #brings my object into existence
hi.speak

现在我想在 rspec 中编写一个测试来检查命令行输出实际上是Hello from RSpec"而不是我喜欢 Unix"

Now I want to write a test in rspec to check that the command line output is in fact "Hello from RSpec" and not "I like Unix"

不工作.我目前在 sayhello_spec.rb 文件中有这个

NOT WORKING. I currently have this in my sayhello_spec.rb file

require_relative 'sayhello.rb' #points to file so I can 'see' it

describe "sayhello.rb" do
  it "should say 'Hello from Rspec' when ran" do        
    STDOUT.should_receive(:puts).with('Hello from RSpec')    
  end
end

有人能指出我正确的方向吗?

Can someone point me in the right direction please?

推荐答案

这是一个很好的方法.复制自 hirb test_helper 源:

Here's a pretty good way to do this. Copied from the hirb test_helper source:

def capture_stdout(&block)
  original_stdout = $stdout
  $stdout = fake = StringIO.new
  begin
    yield
  ensure
    $stdout = original_stdout
  end
  fake.string
end

像这样使用:

output = capture_stdout { Hello.new.speak }
output.should == "Hello from RSpec\n"

这篇关于使用 RSpec 测试命令行输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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