The Crystal Programming Language Forum

Testing compile time errors

I have some checks in my projects that will throw compile time errors if you do not have a required method defined, or adding an annotation to an instance method vs class method.

Is there a way to test these compile time error get thrown as expected; similar to expect_raises or the assert_error method in the stdlib?

1 Like

This is essentially

Similar, would be more interested in making sure the correct compile time error is thrown than just a true/false if it compiles or not tho.

Just to complete this topic. This is what i ended up doing:

def assert_error(path : String, message : String) : Nil
  buffer =
  result ="crystal", ["run", "--no-color", "--no-codegen", "spec/" + path], error: buffer)
  result.success?.should be_false
  buffer.to_s.should contain message

Where i created separate files for each assertion, like:

require "../../../routing_spec_helper"

class CompileController < Athena::Routing::Controller
  @[Athena::Routing::Get(path: "int8/")]
  def no_return_type

Then used it

    describe "without a return type" do
      it "should not compile" do
        assert_error "routing/compiler/actions/", "Route action return type must be set for 'CompileController.no_return_type'"

EDIT: I created GitHub - athena-framework/spec: Common/helpful Spec compliant testing utilities that includes this among other additional testing utilities.