2012-07-05 113 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