How to Ignore Ruby Puts in RSpec Tests

While writing some RSpec tests today, I ran into an annoying little problem.

One of the functions I was testing was logging output to my console as I ran the tests.

Being a little OCD, all I want to see while running tests are my green dots representing my tests are passing, or the occasional red F indicating I need to look into something. I don’t want to see a boatload of other rouge info. The solution, surprisingly, took me more than a few seconds to find after Googling, so I figured I’d post this quick fix to help any others searching for a fast way to ignore console output from ruby “put” functions during RSpec tests.

If you want to provide a fast way to ignore puts in any test, add this code to the spec_helper. If it’s a one-off fix, just add it to the spec you’re in.

def ignore_puts
before do

What this is doing is just stubbing out the stdout write method, which, in layman’s terms, is overriding it to do absolutely nothing. The only caveat to note here, is that if you’re using pry to debug your tests (a practice I highly recommend), the debugging console won’t give you any contextual output. So implementing the ignore_puts is something you may want to wait to add if you think you will need to do some heavy debugging in your tests.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: