Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby popen3 and ANSI colour

I am attempting to get watchr running tests automatically as files change, and got most of what I need working except for the fact that all ANSI colours from RSpec are being disregarded. The offending code is as follows:

stdin, stdout, stderr = Open3.popen3(cmd)
stdout.each_line do |line|
  last_output = line
  puts line
end

When cmd is equal to something like rspec spec/**/*.rb then the above code runs RSpec fine except that all output is in monochrome. I've looked at using Kernel.system instead, however system does not return the output which I need to determine if a test failed / succeeded. How can I get the output form a script that is executed from within Ruby including the ANSI color and output this to the console?

like image 852
Matthew O'Riordan Avatar asked Apr 03 '11 00:04

Matthew O'Riordan


2 Answers

I would guess that rspec is examining the stream to which it is writing output to see if it is a tty (ie the console) or not, and if it's not, disabling colour. Many commands do this - GNU ls and grep, for example. Since the stream from the child process to your script is not a tty, colour will be disabled.

Hopefully, rspec has a flag which will force colour to be used, regardless of the stream type. If it doesn't, you will have to resort to some truly weird stty shenanigans.

like image 188
Tom Anderson Avatar answered Nov 24 '22 19:11

Tom Anderson


Chances are good that the rspec tool is checking to see if it is running interactively on a terminal or being run automatically from a script before deciding to use color output or not.

The documentation says you can force color with --color command line option.

Try: rspec --color spec/**/*.rb.

like image 28
sarnold Avatar answered Nov 24 '22 19:11

sarnold