在Rspec中测试抽象类(Testing abstract classes in Rspec)

编程入门 行业动态 更新时间:2024-10-28 17:28:46
在Rspec中测试抽象类(Testing abstract classes in Rspec)

在我的Ruby库中,我有一些旨在通过继承来使用的类。 因此我在spec文件中做的第一件事是定义一个定制的Foo类:

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

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

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

当我定义像这样的多个类时,特别讨厌清理:

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

这更难以正确地用after :all或after :each定义after :each块。

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

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.

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

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

最满意答案

一种可能是使用匿名类 。

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

这样就没有必要做清理了。

One possibility is to use anonymous classes.

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

This way there is no need to do clean up.

更多推荐

本文发布于:2023-07-20 02:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1192040.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:测试   抽象类   Rspec   classes   abstract

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!