繁体   English   中英

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

[英]rspec: Testing a module that is included in other classes

我有两个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 s C的任何类的行为。但是,然后,我对A和B的测试将仅测试C中不存在的行为。如果A和B的实现发生变化,怎么办?不再使用C? 这种感觉很有趣,因为我对A的行为的描述分为两个测试文件。

  • 我只能针对A和B的行为编写测试。 但是,那时他们将有很多冗余测试。

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

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

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

includes C::InstanceMethods

(includes用于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

这里采用的例子。 是另一个讨论站点,其中包含有关共享示例的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM