如何忽略在rspec

时间:2016-08-04 14:09:42

标签: ruby rspec

我正在使用Commander编写一个ruby gem,它使用erb模板和$terminal.color来表示某些输出。在RSpec中编写测试时(使用CLI Test)我希望能够将一个选项传递给我的命令以防止着色,以便我的测试可以匹配简单的字符串,而不必在字符串比较中包含格式。

目前我正在使用:

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

但是,让我们说“Colorized”这个词是粗体,这个测试会失败,因为它被其他角色包围所以我必须像这样写我的测试

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")

我想避免以这种方式分解测试 - 有没有办法可以在我的测试中通过execute_script调用中的选项,或者配置RSpec来删除测试的格式?

RSpec看到的示例字符串

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

我希望能够对抗

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

2 个答案:

答案 0 :(得分:2)

尝试使用以下RegExp从字符串中删除ANSI转义符号:/\e\[(\d+)m/

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

RegExp来自ansi gem https://github.com/rubyworks/ansi

https://github.com/rubyworks/ansi/blob/17002348d45ce9298a1a4017dc43d3cf65151bd4/lib/ansi/code.rb#L44

https://github.com/rubyworks/ansi/blob/17002348d45ce9298a1a4017dc43d3cf65151bd4/lib/ansi/code.rb#L193-L208

我不确定这个正则表达式是否对这项工作最正确。我在这个答案中找到了另一个:How can I remove the ANSI escape sequences from a string in python

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

答案是指相应的标准,所以这个可能更完整。

答案 1 :(得分:0)

使用@ SunnyMagadan的正则表达式/\e\[\d+m/成功定位着色。我不是必须在所有测试中都包含它,而是扩展了CliTest Execution类并添加了一个stripped_stdout方法,该方法只使用正则表达式去除已经由类定义的stdout。

我将此代码添加到/ spec / support中的文件并将其导入我的spec_helper.rb

module CliTest
  class Execution
    # Strips out ansi colorization leaving unformatted text
    def stripped_stdout
      @stdout.gsub(/\e\[\d+m/, '')
    end
  end
end

这允许我在我的测试中使用以下内容

expect(last_execution.stripped_stdout).to include("Expected Colorized Output")

这是我满意的解决方案。这不会干扰任何其他功能,并允许我在/我想要的时候继续使用last_execution.stdout。

相关问题