Search code examples
ruby-on-railsrubyrspec

Find all lines that are printing to stdout in Ruby


Google is not helping me out. I have a large Rails project that is riddled with print statements or something of that sort. Something is printing and I can't find out what. I have looked at the specs and I can't find anything that should be printing output.

Is there a flag I can pass to rspec or ruby that will show what line number printed to console?

Or perhaps a grep command EG grep -Rl 'p "' to try and hunt down all these print statements?

My rspec output looks like this:

""
..*.****.......*****.........**.""
...""
.""
.""
.""
.""
.""
.""
.""
.""
.""
.""
.""
.""
.""
.""
.""
.""
.""
.""
...**.......""

Solution

  • $stdout and $stderr are variables! Somewhere early in your test config (spec_helper, probably)

    class MyIO < IO
      def puts(*)
        debugger
        super
      end
    end
    
    $stdout = $stderr = MyIO.new
    

    MyIO may need to have a more concrete superclass - like StringIO or File.

    You'll probably just need to run that once to find the culprit. If you find it's getting called too often with stuff you are OK seeing, maybe tweak the debugger line to be something complicated debugger unless caller_is_whitelisted

    def caller_is_whitelisted
      return true if caller[2 (give or take)].matches(/some_file_that_may_print/)
      ...
      false
    end
    

    This is all really rough code and super gross - but you have a gross problem and it's temporary.