2014-07-22 61 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是另一个讨论网站,其中有一些关于共享示例的更多信息。

相关问题