2012-07-05 115 views
17

我想要做的是在命令行上运行ruby sayhello.rb,然后接收Hello from Rspec用RSpec测试输出到命令行

我已经得到了这一点:

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

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

现在我想要写在rspec的测试,以检查命令行输出实际上是“从RSpec的你好” ,而不是“我喜欢的Unix “

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

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 

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

回答

24

这是一个很好的方法来做到这一点。从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" 
+2

建立在这一: DEF expect_stdout(字符串,&块); output = capture_stdout(&block); output.should包含字符串; 结束 – 2013-11-27 13:47:34

2

quietly命令可能是你想要什么(熟成的ActiveSupport,看到文档的api.rubyonrails.org)。下面的RSpec代码片段展示了如何确保stderr上没有输出,同时静默stdout。

quietly do      # silence everything 
    commands.each do |c| 
    content = capture(:stderr) { # capture anything sent to :stderr 
     MyGem::Cli.start(c) 
    } 
    expect(content).to be_empty, "#{c.inspect} had output on stderr: #{content}" 
    end 
end 
-5
it "should say 'Hello from Rspec' when run" do   
    output = `ruby sayhello.rb` 
    output.should == 'Hello from RSpec' 
end