John F. Miller
John F. Miller

Reputation: 27217

check for (the absence of) `puts` in RSpec

I am using rspec for my test in a ruby project, and I want to spec that my program should not output anything when the -q option is used. I tried:

Kernel.should_not_receive :puts

That did not result in a failed test when there was output to the console.

How do I verify the absents of text output?

Upvotes: 10

Views: 3364

Answers (2)

Mike Bethany
Mike Bethany

Reputation:

The accepted answer above is incorrect. It "works" because it doesn't receive a :write message but it might have received a :puts message.

The correct line should read:

$stdout.should_not_receive(:puts)

Also you need to make sure you put the line before the code that will write to STDIO. For instance:

it "should print a copyright message" do
  $stdout.should_receive(:puts).with(/copyright/i)
  app = ApplicationController.new(%w[project_name])
end


it "should not print an error message" do
  $stdout.should_not_receive(:puts).with(/error/i)
  app = ApplicationController.new(%w[project_name])
end

That's an actual working RSpec from a project

Upvotes: 4

Sutto
Sutto

Reputation: 1044

puts uses $stdout internally. Due to the way it works, the easiest way to check is to simply use: $stdout.should_not_receive(:write)

Which checks nothing is written to stdout as expected. Kernel.puts (as above) would only result in a failed test when it is explictely called as such (e.g. Kernel.puts "Some text"), where as most cases it's call in the scope of the current object.

Upvotes: 15

Related Questions