If I run "rake test", the output will be in color.
This is due to the fact that in the autotest mode the "terminal" in which your test procedure runs is not tty
, but when launched directly.
First, how it works, color codes are defined in escape sequences which, if you wrote them down, would look like \E[48mPRINT ME IN RED\E[0m
( details ).
Your terminal understands these escape sequences (usually), replacing them with colors, improving the appearance of the output.
Using the environment variables defined by the terminal emulator and looking at it, it enters, and the output streams (i.e. $stdin
, $stdout
and $stderr
) process (s) (s), can determine the color support and it is connected to the terminal ( tty
) or to a file or other process, etc.
When one process starts another process, your process, and not the terminal, is the owner, so your test
output does not talk to the terminal, which understands the color escape sequences, it talks to the autotest, and this is not so.
The same behavior will happen by running tests, but redirecting the output to a file, escape codes and sequences will be meaningless.
The relationship is as follows:
# rake test Terminal Application \- Bash \- rake
There are several ways to fake support, so autotest works in color, one of the methods described here will turn out to be the most reliable without checking it yourself.
Another way is simply to short-circuit the “color support check” using this method
The #tty?
method #tty?
in streams is not only useful for the above, but also consider the case when you run Ruby-debug or some other “interactive” command, when the control process is not tty, there is no way that ruby-debug can ask the user if he is connected to another application, which may not understand the prompts, therefore, when streaming output to a file or executing one process inside another, intelligent software always checks first to see if the parent process can be confused by calling and typing or sending non-standard output.
If you want to do extra reading, take a look at $stdin.tty?
from the Ruby documentation, it explains the difference between inbound and outbound process flows, which are considered ttys, and the effect that is related to how this is done.