RSpec | Ruby

Assert STDOUT output

We want to assert output to STDOUT:

it 'should work' do
  expect { puts 'Aayla Secura' }.to output(/secura/i).to_stdout
end

With some class method that outputs to STDOUT:

describe PlainTextFormatter do
  it 'should output report title' do
    report = Report.new(PlainTextFormatter.new)

    expect do
      report.output
    end.to output(/===== Nostromo Report =====/).to_stdout
  end

  it 'should should output report body content' do
    report = Report.new(PlainTextFormatter.new)

    lines_to_match = [
      'This is Ripley, last survivor of the Nostromo.',
      'Signing off.'
    ].join("\n")

    expect { report.output }.to output(/#{lines_to_match}/).to_stdout
  end
end

References