6

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?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Matthew O'Riordan
  • 7,981
  • 4
  • 45
  • 59

3 Answers3

6

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.

Tom Anderson
  • 46,189
  • 17
  • 92
  • 133
  • 1
    Thanks Tom, you directed me in the right direction and I got it working by running rspec as follows: 'rspec --tty --drb --colour [path]' where obviously [path] is the path to the test(s) you are to run. Thanks again, that is great. – Matthew O'Riordan Apr 03 '11 at 17:18
  • It was the `--tty` argument that did it for me. – Steve Wilford Jan 14 '17 at 10:07
5

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.

sarnold
  • 102,305
  • 22
  • 181
  • 238
  • 1
    Sorry, I should have specified that the command that is being run by watchr is 'rspec --drb --colour --format nested [file_name_of_test]' so colour is being forced. – Matthew O'Riordan Apr 03 '11 at 17:16
1

It's possible to run commands in a pseudo terminal via the PTY module in order to preserve a user facing terminal-like behaviour. Credits go to the creator of the tty-command gem (see this issue) who implemented this behaviour in his gem:

require 'tty-command'
cmd = TTY::Command.new(pty: true)
cmd.run('rspec', 'spec/**/*.rb')

Keep in mind that using a pseudo terminal may have unwanted side effects, such as certain git commands using a pager which will essentially cause commands to hang. So introducing the functionality might be a breaking change.

thisismydesign
  • 21,553
  • 9
  • 123
  • 126