2010-03-21 5 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 

편집 : RegularListTest에 조명기 호출을 넣고 모듈에서 제거하면 모든 것이 작동하는 것 같습니다.

+0

아, 조명기는 test_helper.rb의 한 방법이므로 각 테스트 클래스로 이동해야합니다. 나는 아래 나의 대답을 업데이 트했습니다. –

답변

1

나는 실제로 비슷한 문제가있어서 그것을 해결하기 위해 믹스 인을 사용했다.

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

+0

여기에서 귀하의 질문을 이해할 수 있는지 잘 모르겠습니다. 예를 들어 줄 수 있습니까? mixin에서 클래스를 포함하여 메서드를 호출 할 수 있습니다. 위의 경우 mixin은 OtherListTest와 RegularListTest의 list_type 메소드를 호출합니다. 또한 클래스를 포함하면 믹스 인에서 메서드를 호출 할 수 있습니다. –