2010-08-24 56 views
1

我有一些ruby文件(a.rb,b.rb,c.rb),它們定義了非常類似的類。 (他們應該測試相同)生成許多幾乎相同的紅寶石單元測試

我已經編寫了一個單元測試來測試這些子類,並且我已經爲每個類以編程方式生成了上下文(請參閱下文) - 我是否應該用編程方式編寫完整的Test Classes?如果是的話,爲什麼如何?

我使用shoulda單元測試擴展,所以我的文件看起來是這樣的:

a.rb

class ItsA 
    def number 
    1123 
    end 
end 

b.rb

class ItsB 
    def number 
    6784 
    end 
end 

test_letters.rb

require 'rubygems' 
require 'test/unit' 
require 'shoulda' 

class LettersTest < Test::Unit::TestCase 
    Dir.glob('letters/*.rb') do |letter| 
    context "The #{letter} letter file" 
     setup do 
     # Here I require the ruby file and allocate 
     # @theclass to be an instance of the class in the file. 
     # I'm actually testing JavaScript using Harmony, but 
     # putting those details in might complicate my question. 
     end 

     should "return a number" do 
     assert @theclass.number.is_a? Number 
     end 
    end 
    end 

這做這項工作相當不錯,但我應該做一些其他jiggerypokery創造LetterATestLetterBTest等自動代替?如果是這樣,你會如何去做,爲什麼?

+1

您可以將該方法抽象爲一個模塊,測試一次幷包含在類中。 – 2010-08-24 19:02:14

回答

1

這真的取決於你的類是如何相似的,但假設他們幾乎相同,需要一些小測試,你使用早該,你可以這樣做:

class LettersTest < Test::Unit::TestCase 
    context "The letter classes" 
    setup do 
     @instances = # your code to get a list of the instances 
    end 

    should "return a number" do 
     @instances.each do |instance| 
     assert instance.number.is_a?(Number), "#{instance.class}.number should be a number" 
     end 
    end 
    end 
end 

在我們的代碼庫發現大量自動生成的上下文和測試導致測試執行速度非常緩慢,所以我們傾向於採用上述方法來儘量減少上下文/測試的數量。你可能沒有這個問題。

+0

這回答我的兩個問題,聽起來像我需要儘可能減少我的上下文數量!謝謝! – 2010-08-25 08:20:29