Testing abstract classes in rspec

In my Ruby library, I have several classes that are designed to be used through inheritance. So the first thing I do in my spec file is to define a custom class Foo:

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

The problem is that a certain class will leak into other tests and must be careful using unique names or deleting a class with a block after :all.

It feels a little tame, given all the magic already given by Rspec. Is there a better way to define specifications for abstract classes? Basically I want an easy way to clear the namespace of all temporary declarations.

Cleaning is especially annoying when I define several classes as follows:

module MyGem
  describe MyClass do
     ... 
  end

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

after :all after :each.

+4
3

.

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

, .

+7
describe MyClass do
  let(:klass) { Class.new(MyClass) }
  it "works without assigning a constant name" do
    obj = klass.new
    expect(obj).to be_kind_of(MyClass)
  end
end

, , .

+3

Following @hjing answer, you can also use stub_const

before do
  stub_const('MyClass', fooMyClass)
end

which makes MyClassavailable as a constant in your specifications. This is useful if the behavior of a class depends on its name (as is sometimes the case with fantastic metaprogramming).

0
source

All Articles