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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With