2010-03-21 29 views
0

我有許多使用STI的模型,並且我想使用相同的單元測試來測試每個模型。例如,我有:對使用​​STI的模型重複使用單元測試

class RegularList < List 
class OtherList < List 

class ListTest < ActiveSupport::TestCase 
    fixtures :lists 

    def test_word_count 
    list = lists(:regular_list) 
    assert_equal(0, list.count) 
    end 

end 

我該如何去使用OtherList模型的test_word_count測試。測試時間更長,所以我寧願不必爲每個模型重新輸入。謝謝。

編輯:我想按照蘭迪的建議使用混合。這是我,但我得到的錯誤: 「對象是不缺的不斷ListTestMethods(引發ArgumentError)」:

在LIB

/list_test_methods.rb:

module ListTestMethods 
    fixtures :lists 

    def test_word_count 
    ... 
    end 
end 

在regular_list_test.rb:

require File.dirname(__FILE__) + '/../test_helper' 

class RegularListTest < ActiveSupport::TestCase 
    include ListTestMethods 

    protected 
    def list_type 
    return :regular_list 
    end 
end 

編輯:一切似乎工作,如果我把Fixtures調用RegularListTest並從模塊中刪除它。

+0

啊,fixtures是test_helper.rb中的一個方法,所以你必須將它移動到每個測試類。我已在下面更新了我的答案。 – 2010-03-21 22:58:38

回答

1

我實際上有一個類似的問題,並使用mixin來解決它。

module ListTestMethods 

    def test_word_count 
    # the list type method is implemented by the including class 
    list = lists(list_type) 
    assert_equal(0, list.count) 
    end 

end 

class RegularListTest < ActiveSupport::TestCase 
    fixtures :lists 

    include ::ListTestMethods 

    # Put any regular list specific tests here 

    protected 

    def list_type 
    return :regular_list 
    end 
end 

class OtherListTest < ActiveSupport::TestCase 
    fixtures :lists 

    include ::ListTestMethods 

    # Put any other list specific tests here 

    protected 

    def list_type 
    return :other_list 
    end 
end 

這裏有效的是OtherListTest和RegularListTest能夠彼此獨立增長。

您可能也可以使用基類來做到這一點,但由於Ruby不支持抽象基類,因此它並不是一個乾淨的解決方案。

+0

有什麼方法可以使用此設置從測試中的ListTestMethods模塊調用單個方法?我有一些重疊的方法,其他方法不重合,我寧願不製作另一個模塊文件。 – TenJack 2010-03-21 22:27:50

+0

我不確定我在這裏理解你的問題。你能給個例子嗎?從混音中你可以在你的課堂中調用方法。在上面的例子中,mixin在OtherListTest和RegularListTest上調用list_type方法。另外,你的包含類可以調用mixin上的方法。 – 2010-03-21 22:56:39

相關問題