2014-07-22 64 views
0

我有兩個具有共同行爲的類A和B.比方說,我把常用的東西,一個模塊,每個類include S IN:rspec:測試包含在其他類中的模塊

class A 
    include C 

    def do_something 
    module_do_something(1) 
    end 
end 

class B 
    include C 

    def do_something 
    module_do_something(2) 
    end 
end 

module C 
    def module_do_something(num) 
    print num 
    end 
end 

(首先,這是一個合理的方式來構造類/模塊從Java的背景,我會作出C 2一個抽象類,A和B都是繼承而來的,但我讀過Ruby並沒有抽象類的概念。)

什麼是編寫測試的好方法?

  • 我可以寫測試爲C,指定其行爲的任何類include小號。然而,然後我的A和B測試只能測試不是C.如果A的行爲和B的實現改變,以便他們不再使用C?這種感覺很有趣,因爲我對A行爲的描述被分成兩個測試文件。

  • 我只能寫A和B的行爲測試。但是他們會有很多冗餘測試。

回答

0

是的,這看起來像一個合理的方式來在Ruby中構建您的代碼。通常,在模塊中混合時,您可以定義模塊的方法是類還是實例方法。在你上面的例子,這可能看起來像

module C 
    module InstanceMethods 
    def module_do_something(num) 
     print num 
    end 
    end 
end 

然後在你的其他類,你會指定

includes C::InstanceMethods 

(包括用於InstanceMethods,延伸,用於ClassMethods)

你可以使用共享示例在rspec中創建測試。

share_examples_for "C" do 
    it "should print a num" do 
    # ... 
    end 
end 

describe "A" do 
    it_should_behave_like "C" 

    it "should do something" do 
    # ... 
    end 
end 

describe "B" do 
    it_should_behave_like "C" 

    it "should do something" do 
    # ... 
    end 
end 

here採用的示例。 here是另一個討論網站,其中有一些關於共享示例的更多信息。

相關問題