2011-03-30 55 views
1

當你自己的測試套件執行完成後,會有一些結果。 我想保留在txt文件或HTML, thoes信息,但我不知道如何保存那些輸出的消息, 如果有人知道,請與我分享,在此先感謝 下面的代碼是我的實驗,但它不起作用。如何通過ruby將測試結果重定向到txt文件?

require File.join(File.dirname(__FILE__), 'person') 
require "test/unit" 

filename = "logfile.txt" 
$logfile = File.new(filename,"a") 
open(logfile,'a') { |f| f << $stdout} 

class PersonTest < Test::Unit::TestCase 

    FIRST_NAME, LAST_NAME, AGE = 'Nathaniel', 'Taldtretbott', 25 

    def setup 
    @person = Person.new(FIRST_NAME, LAST_NAME, AGE) 
    end 

    def test_first_name 
    assert_equal "asv", @person.first_name,"try to compare" 
    end 

    def test_last_name 
    assert_equal "Taldtretbott", @person.last_name 
    end 

    def test_full_name 
    assert_equal FIRST_NAME + ' ' + LAST_NAME, @person.full_name 
    end 
end 
+0

使用大括號圖標({})來修改您的代碼。 – 2011-03-30 15:10:53

回答

0

嘗試:

$stdout = $logfile 

代替:

open(logfile,'a') { |f| f << $stdout} 

這意味着要重定向標準輸出到文件中。

+0

不行,夥計。非常感謝所有相同的 – user680200 2011-03-31 14:09:52

1

爲什麼不

ruby testfile.rb > text_output.txt 
+0

非常感謝。有沒有其他的方式來重定向輸出信息? – user680200 2011-03-31 14:07:31

1

我有一些時間來嘗試解決一些測試。我設法把它的工作是這樣的:

require 'test/unit' 

STDOUT = $stdout = File.open("stdout.txt", "a+") 
STDERR = $stderr = File.open("stderr.txt", "a+") 

class AreasTest < Test::Unit::TestCase 
    def test_ok 
    puts "#{Time.now} Hello " 
    a = 10 
    assert_equal(a, 10) 
    end 


    def test_fail 
    a = 9 
    assert_equal(a, 10) 
    end 
end 

它給出了一個警告,原因STDOUT和STDERR已經初始化,但只是重定向$ stdout和標準錯誤$不起作用(僅適用於正常的看跌期權)。

我希望它有幫助。

相關問題