Search code examples
crystal-lang

How do I spec instance methods on an abstract class in Crystal?


Let's say I have an abstract class which has a non-abstract instance method for children to inherit:

# - abstract.cr
abstract class Abstract
  def foo
    2
  end
end

How do I write a spec for this?

# - abstract_spec.cr

it "returns 2 from #foo" do
  Abstract.instance.foo.should eq 2 #???
end

Solution

  • There might be a better way to this (hence my posting the question, I'd love to get feedback from the community), but one way I can think to do this is to have a class inherit from the parent in the test. That way you are abstractly focusing on "any" implementation of the class.

    # - abstract_spec.cr
    class AbstractTest < Abstract
    end
    
    it "returns 2 from #foo" do
      AbstractTest.new.foo.should eq 2
    end