Test output to command line with RSpec
rspec, ruby, testing
Solution
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
Use like this:
output = capture_stdout { Hello.new.speak }
output.should == "Hello from RSpec\n"
Problem
I want to do is run `ruby sayhello.rb` on the command line, then receive `Hello from Rspec`. I've got that with this: ``` class Hello def speak puts 'Hello from RSpec' end end hi = Hello.new #brings my object into existence hi.speak ``` 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" 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?