Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

ruby - Testing STDOUT output in Rspec

I am trying to build a spec for this statement. It is easy with 'puts'

print "'#{@file}' doesn't exist: Create Empty File (y/n)?"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

RSpec 3.0+

RSpec 3.0 added a new output matcher for this purpose:

expect { my_method }.to output("my message").to_stdout
expect { my_method }.to output("my error").to_stderr

Minitest

Minitest also has something called capture_io:

out, err = capture_io do
  my_method
end

assert_equals "my message", out
assert_equals "my error", err

RSpec < 3.0 (and others)

For RSpec < 3.0 and other frameworks, you can use the following helper. This will allow you to capture whatever is sent to stdout and stderr, respectively:

require 'stringio'

def capture_stdout(&blk)
  old = $stdout
  $stdout = fake = StringIO.new
  blk.call
  fake.string
ensure
  $stdout = old
end

def capture_stderr(&blk)
  old = $stderr
  $stderr = fake = StringIO.new
  blk.call
  fake.string
ensure
  $stderr = old
end

Now, when you have a method that should print something to the console

def my_method
  # ...
  print "my message"
end

you can write a spec like this:

it 'should print "my message"' do
  printed = capture_stdout do
    my_method # do your actual method call
  end

  printed.should eq("my message")
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...