rspec:测试包含在其他类中的模块

时间:2014-07-22 00:28:45

标签: ruby rspec

我有两个具有共同行为的A和B类。假设我把常见的东西放在每个类include s:

的模块中
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成为A和B都继承的抽象类。但是,我读过Ruby没有真的有一个抽象类的概念。)

为此编写测试的好方法是什么?

  • 我可以为C编写测试,为include C的任何类指定其行为。但是,我对A和B的测试只会测试不在C中的行为。如果A和B的实现发生变化而不再使用C,该怎么办?这种感觉很有趣,因为我对A行为的描述分为两个测试文件。

  • 我只能为A和B的行为编写测试。但是他们会进行大量的冗余测试。

1 个答案:

答案 0 :(得分:0)

是的,这看起来像是在Ruby中构建代码的合理方法。通常,在混合模块时,您将定义模块的方法是类还是实例方法。在上面的示例中,这可能看起来像

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

然后在其他课程中,您将指定

includes C::InstanceMethods

(包括用于InstanceMethods,extends用于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是另一个讨论网站,其中包含有关共享示例的更多信息。

相关问题