【问题标题】:RSpec. How to color the piped or redirected output?规范。如何为管道或重定向的输出着色?
【发布时间】:2011-02-03 07:11:02
【问题描述】:

在 2.0 之前的 RSpec 版本中,我可以将颜色输出通过管道传输到 less 或将其重定向到文件。为此,我只需将 RSPEC_COLOR 环境变量设置为 true。但是,在框架的新主版本中,此变量已停止定义输出类型(颜色或单色)。有没有办法在 RSpec 2.0 及更高版本中管道或重定向颜色?

谢谢。

Debian GNU/Linux 5.0.7;

红宝石 1.9.2;

RSpec 2.4.0。

更新


我自己找到了答案。

应该使用tty配置选项来达到效果。

示例如下:

# spec/spec_helper.rb

RSpec.configure do |config|
  config.tty = true
end

【问题讨论】:

    标签: ruby rspec bdd


    【解决方案1】:

    问题中的答案是正确的:

    # spec/spec_helper.rb
    
    RSpec.configure do |config|
      config.tty = true
    end
    

    然后rspec | grep --color="never" something保持着色。

    【讨论】:

      【解决方案2】:

      通过查看sources,似乎color_enabled 配置选项现在位于RSpec 的配置模块中。但是,如果没有输出到 tty,color is disabled

      我的建议是设置 color_enabled = true 并对 RSpec 配置模块进行猴子补丁,这样即使不输出到 tty 也能正常工作:

      module RSpec   
        module Core
          class Configuration
            def color_enabled
              true
            end
          end
        end
      end
      

      不过,这不是最好的方法。这也未经测试,我认为猴子修补 rspec 并不是最简单的事情,因为通常测试是通过专用的命令行工具运行的。

      也许您可以向维护者打开一个错误报告并要求提供force_color_enabled 选项?实施起来可能会非常快...

      祝你好运,编码愉快!

      【讨论】:

      • 感谢您的回答,10 月。我自己解决。请参阅我的回答中的更新部分。
      • 顺便说一句,我在 Github 上打开了一个issue,但我没有得到答案,不得不自己找到解决方案。
      • 这个配置设置效果很好!只是在此处添加稍后相关的issue
      【解决方案3】:

      很简单:

      # spec/spec_helper.rb
      
      RSpec.configure do |config|
        config.color_enabled = true
      end
      

      【讨论】:

      • Sam,问题不在于如何为输出着色,而是如何在将输出重定向到寻呼机或文件时保留颜色标签。看:config.color_enabled = true$ rspec spec/ | less #=> monochromeconfig.tty = true; config.color_enabled = true; $ rspec spec/ | less #=> color.
      猜你喜欢
      • 2011-07-22
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 2014-12-11
      • 2013-12-21
      • 1970-01-01
      • 2018-03-24
      相关资源
      最近更新 更多