Stub out Puts or Print with RSpec

By Morten Møller Riis

August 26 2011 11:00 CET

In one project I have some Ruby agents that outputs status to STDOUT. When running the RSpec suite this becomes a bit annoying since it will mess up the spec progress output.

So, the quick and dirty way to get rid of STDOUT output via either #puts or #print is to stub the methods on the objects.

Keep in mind that if you use the object several times you must include the stub in the before method so it is not overridden.

something_spec.rb

                require File.dirname(__FILE__) + '/../spec_helper'
                require 'rspec/mocks/standalone'
                
                describe "Something" do
                  before do
                    Something.stub!(:print)
                    Something.stub!(:puts)
                  end
                  
                  it "should do something" do
                    Something.whatever
                  end
                end
             

Any print/puts in Something#whatever should now be suppressed.

If you are getting an undefined method `stub!` you probably forgot to include require 'rspec/mocks/standalone'.