Testing what a Ruby process writes to STDOUT.
Ruby’s relationship with STDOUT
Ruby has two built-in values that represent the system’s standard output stream:
- The constant
STDOUT
- The global variable
$stdout
The Ruby documentation, describes STDOUT
as the standard output, and $stdout
and the current standard output. If you want to change the stream that this Ruby process sends its output to, you can change the value of $stdout
Hello StringIO
Given an RSpec test pack, I should be able to use an output matcher, but I couldn’t get this to reliably work across tests for my system. However, the standard library includes an IO-like object for strings, StringIO
, which must be explicitly required.
This means I can write my tests like this:
require 'stringio'
RSpec.describe DVLA::Engineering do
output = StringIO.new
$stdout = output
puts 'Hello from the DVLA'
expect(output.string).to match(/DVLA/)
end