2012-07-05 32 views
17

Tôi muốn làm là chạy ruby sayhello.rb trên dòng lệnh, sau đó nhận Hello from Rspec.Đầu ra kiểm tra đến dòng lệnh với RSpec

Tôi đã có mà với điều này:

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

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

Bây giờ tôi muốn viết một bài kiểm tra trong rspec để kiểm tra xem các đầu ra dòng lệnh là trong thực tế "Hello từ RSpec" và không phải là "Tôi thích Unix "

KHÔNG LÀM VIỆC. Tôi hiện có điều này trong tệp sayhello_spec.rb của mình

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 

Ai đó có thể hướng tôi đi đúng hướng?

Trả lời

24

Đây là một cách khá hay để thực hiện việc này. Sao chép từ 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 

Sử dụng như thế này:

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

Xây dựng về vấn đề này: def expect_stdout (string, & chặn); output = capture_stdout (& block); output.should bao gồm chuỗi; kết thúc –

2

Lệnh quietly có lẽ là những gì bạn muốn (nấu chín vào ActiveSupport, xem tài liệu tại api.rubyonrails.org). Đoạn mã RSpec dưới đây cho thấy làm thế nào để đảm bảo không có đầu ra trên stderr trong khi đồng thời im lặng 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 
Các vấn đề liên quan