在 Rspec 中测试抽象类 [英] Testing abstract classes in Rspec

查看:38
本文介绍了在 Rspec 中测试抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Ruby 库中,我有一些旨在通过继承使用的类.因此,我在规范文件中做的第一件事就是定义一个自定义的 Foo 类:

In my Ruby library I have some classes that are intended to be used through inheritance. Therefore the first thing I do in my spec file is defining a custom Foo class:

module MyGem
  describe MyClass do
    class FooMyClass < MyClass
      ...
    end
  end
end

问题是定义的类会泄漏到其他测试,必须小心使用唯一名称或使用 after :all 块删除类.

The problem is that the defined class will leak to other tests and must be careful using unique names or removing the class with an after :all block.

考虑到 Rspec 已经提供的所有魔法,这感觉有点手动.有没有更好的方法来定义抽象类的规范?大多数情况下,我想要一种简单的方法来清理所有时间声明的命名空间.

This feels a little bit manual considering all the magic already given by Rspec. Is there a better way to define specs for abstract classes? Mostly I want an easy way to clean the namespace of all temporal declarations.

当我像这样定义多个类时,清理起来特别烦人:

It is specially annoying to clean up when I define multiple classes like this:

module MyGem
  describe MyClass do
     ... 
  end

  class FooMyClass < MyClass
    ...
  end
  describe FooMyClass do
    ...
  end
end

使用 after :allafter :each 块更难正确取消定义.

This is even harder to properly un-define with after :all or after :each blocks.

推荐答案

一种可能性是使用 匿名类.

  let(:fooMyClass) do
    Class.new(MyClass) do
      # ...
    end
  end

这样就不需要清理了.

这篇关于在 Rspec 中测试抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆