Capturing STDOUT and STDERR in Ruby Tests

I'm writing up a new gem called Tinfoil that tests whether web servers support secure headers. Since this is a command-line interface (CLI) for a Unix-based system, I have a hard time testing the CLI in Ruby's built-in Test::Unit framework. The problem is that the CLI outputs directly to STDOUT and STDERR, polluting my test output when I run them. The problem to this was solved by capturing stdout and stderr and redirecting them for a short time while the test runs. I got it from this StackOverflow answer, and I have added another method for capturing stderr.

def capture_stdout(&block)
  original_stdout = $stdout
  $stdout = fake = StringIO.new
  begin
    yield
  ensure
    $stdout = original_stdout
  end
 fake.string
end

def capture_stderr(&block)
  original_stderr = $stderr
  $stderr = fake = StringIO.new
  begin
    yield
  ensure
    $stderr = original_stderr
  end
 fake.string
end

I guess the next thing is to package this up as a gem and then I can easily use it in other tests.

I don't know why I didn't think of this before. It's so simple and elegant. Gotta love Ruby.