Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing abstract classes in Rspec

Tags:

ruby

rspec

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.

like image 685
SystematicFrank Avatar asked Dec 09 '22 04:12

SystematicFrank


2 Answers

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.

like image 180
hjing Avatar answered Dec 24 '22 10:12

hjing


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

Creating constants in a test is always going to be painful, this is a useful workaround I've used.

like image 23
Jim Deville Avatar answered Dec 24 '22 10:12

Jim Deville