2012-02-21 50 views
6

的Rails 3.2.1應用程序,使用MINITEST和自動測試護欄寶石。如何使用測試/單元MiniTest在自動測試中獲得彩色輸出?

如果我運行「耙測試」的輸出是彩色的。但是如果我運行自動測試,輸出不是彩色的。

如何使用自動測試時,我得到的彩色輸出?

這裏是我的test_helper.rb中:

ENV["RAILS_ENV"] = "test" 
require File.expand_path('../../config/environment', __FILE__) 
require 'rails/test_help' 
require 'turn/autorun' 

Turn.config do |c| 
# use one of output formats: 
# :outline - turn's original case/test outline mode [default] 
# :progress - indicates progress with progress bar 
# :dotted - test/unit's traditional dot-progress mode 
# :pretty - new pretty reporter 
# :marshal - dump output as YAML (normal run mode only) 
# :cue  - interactive testing 
c.format = :pretty 
# turn on invoke/execute tracing, enable full backtrace 
c.trace = true 
# use humanized test names (works only with :outline format) 
c.natural = true 
end 

class ActiveSupport::TestCase 
    # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order. 
    # 
    # Note: You'll currently still have to declare fixtures explicitly in integration tests 
    # -- they do not yet inherit this setting 
    fixtures :all 

    # Add more helper methods to be used by all tests here... 
end 

回答

7

如果我運行 「耙測試」 的輸出是彩色的。

這是因爲在自動測試「終端」您的測試processess在運行不是tty,當你直接運行,它是。

首先它是如何工作的,顏色代碼是在轉義序列中定義的,如果你把它們寫下來看起來像\E[48mPRINT ME IN RED\E[0mdetails)。

您的終端理解這些轉義序列(通常),用顏色替換它們,改善輸出的外觀。

通過使用由終端模擬器中定義的環境變量,看它是它的輸入,和輸出流(即$stdin$stdout,並$stderr)processe(一個或多個)可確定顏色的支持,以及它是否已連接到一個終端(tty)或文件,或其他進程,或等

當一個進程啓動另一個進程,你的過程,而不是終端是主人,所以你test輸出不說話,理解有色逃跑的終端序列,它正在與自動測試進行交談,而不是。

同樣的行爲會發生,運行你的測試,但重定向到一個文件的輸出,轉義碼和序列將是沒有意義的。

的關係是這樣的:

# rake test 
Terminal Application 
\- Bash 
    \- rake   # Rake's $stdout.tty? => true 
        # (Bash is a terminal emulator) 

# autotest 
Terminal Application 
\- Bash 
    \- autotest 
     \- rake  # Rake's $stdout.tty? => false 
         # (Autotest is not a terminal emulator) 

有一些方法來僞造的支持,使自動測試在顏色上運行,documented here似乎是最強大的,而不必測試它自己的一種方式。

另一種方式,是簡單地短路它的「檢查顏色支持」的流using this technique

方法#tty?不是上述只是有用的,但也考慮到一個情況運行Ruby-debug或其他一些「交互式」命令,當控制進程不是tty時,ruby-debug無法提示用戶,如果它連接到另一個可能不理解提示的應用程序,那麼當將輸出流式傳輸到一個文件,或者在另一個進程中運行一個進程,智能軟件總是首先檢查,通過提示輸入或發送非標準輸出來查看父進程是否可能被混淆。

如果您想做一些額外的閱讀,請參閱Ruby文檔中的$stdin.tty?,它解釋了輸入輸出流被認爲是ttys的過程與對事物執行方式的影響之間的區別。

+2

這兩個環節似乎是死:( – alnorth29 2013-09-30 06:39:04

+2

的職位超過12個月大的!對於這兩種技術中提到,無論是在這裏介紹的技術不工作了,但理論上是合理的,你必須在代碼中查找,或者詢問寶石作者是否有強制着色的方法,繞過檢查輸出是否爲tty。 – 2013-09-30 07:06:23

相關問題