2013-02-15 80 views
1

當我在做單元測試的,我不相信非常多的代碼,我會經常使用此模式:如何批量單元測試Ruby中的對象集合?

  1. 想起來了許多(也許是幾十個)的期望我有輸出我函數(我認爲這些是關於代碼如何工作的「理論」)。
  2. 旋轉數以千計的物體。
  3. 通過我編寫的幾十個斷言運行每個對象,反映了我對代碼工作方式的期望。

在Ruby的Test ::股(到我新),我一直在做這樣的事情:

class TestFooBarrer < Test::Unit::TestCase 
    def setup 
    @lots_of_objects_to_be_tested = FooBarrer.bar_lots_of_foos 
    end 

    def assert_foo_has_been_barred(foo) 
    assert_kind_of Bar, foo 
    end 

    def assert_foo_has_baz_method(foo) 
    assert_respond_to foo, :baz 
    end 

    #Many more assertions along those lines go here. 

    def test_all_theories 
    @lots_of_objects_to_be_tested.each do |foo| 
     assert_foo_has_been_barred(foo) 
     assert_foo_has_baz_method(foo) 
     # etc. 
     # 
    end 
    end 
end 

這顯然變得有點笨拙,當理論的數我測試是在幾十個,並涉及什麼看起來像我很多不必要的重複。我更願意做這樣的事情:

class FooTheories 
    def self.assert_all_theories(foo) 
    # ??? 
    end 

    def assert_foo_has_been_barred(foo) 
    assert_kind_of Bar, foo 
    end 

    def assert_foo_has_baz_method(foo) 
    assert_respond_to foo, :baz 
    end 

    #Many more assertions along those lines go here. 
end 


class TestFooBarrer < Test::Unit::TestCase 
    def setup 
    @lots_of_objects_to_be_tested = FooBarrer.bar_lots_of_foos 
    end 

    def test_all_theories 
    @lots_of_objects_to_be_tested.each do |foo| 
     FooTheories.assert_all_theories(foo) 
    end 
    end 
end 

基本上,我正在尋找一種方式來寫一堆斷言在一個地方,然後一遍又一遍給他們打電話的對象量大。

在Ruby中有類似的東西嗎?我不特別與Test :: Unit綁定。任何測試框架都很好。

+0

哦,請不要使用「理論」,甚至在報價:( – 2013-02-15 18:18:52

+0

「假設」會多給點,但很難鍵入:) – 2013-02-15 18:20:10

回答

1

我會做的是在飛行中生成測試。在test_helper添加一個方法:

def test(obj, &block) 
    define_method("test_#{ obj.to_s }", &block) 
end 

然後你就可以讓你的測試套件像下面

class TestObjects < Test::Unit::TestCase 

    @objects_to_test = [...] 

    @objects_to_test.each do |obj| 
    test obj do 

     assert obj.is_a?(Foo), 'not a foo' 

     # all assertions here 

    end 
    end 

end 

然後,如果失敗的話,你會得到知道哪些對象失敗,因爲名稱的測試是對象的字符串表示。防爆消息:

1) Failure: 
test_#<Bar:0x000001009ee930>(TestObjects): 
not a foo 
+0

工作就像一個魅力,謝謝!我認爲有一些元編程解決方案。 – 2013-02-15 21:10:39