Rabbott Rabbott - 2 months ago 10
Ruby Question

How can I ignore command line colors for commands run within rspec

I'm writing a ruby gem using Commander which uses erb templates and

for some of the output. When writing tests in RSpec (using CLI Test) I'd like to be able to pass an option to my commands to prevent the colorization so that my tests can match simple strings instead of having to include formatting in my string comparisons.

Currently I'm using:

execute_script('mycommand arg1')
expect(last_execution.stdout).to include("Expected Colorized Output")

But let's say the word "Colorized" is bolded, this test will fail because its surrounded by other characters so I have to write my test like this

execute_script('mycommand arg1')
expect(last_execution.stdout).to include("Expected")
expect(last_execution.stdout).to include("Colorized")
expect(last_execution.stdout).to include("Output")

I'd like to avoid having to break up the test in this way -- is there a way I can either pass an option within my
call in my tests, or configure RSpec to remove formatting for tests?

Sample string that RSpec sees

# successfully is bolded here
Command ran \e[1m\e[32msuccessfully\e[0m

Which I would like to be able to run against

expect(last_execution.stdout).to include("Command ran successfully")


Try to remove ANSI escape symbols from the string with the following RegExp: /\e\[(\d+)m/

"Command ran \e[1m\e[32msuccessfully\e[0m".gsub(/\e\[(\d+)m/, "")
 => "Command ran successfully"

RegExp was taken from ansi gem https://github.com/rubyworks/ansi



I am not sure if this regexp is the most correct for this job. I found another in this answer: How can I remove the ANSI escape sequences from a string in python

/(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]/

Answer refers to the corresponding standards so maybe this one is more complete.