module Spec

Overview

Crystal's built-in testing library.

A basic spec looks something like this:

require "spec"

describe "Array" do
  describe "#size" do
    it "correctly reports the number of elements in the Array" do
      [1, 2, 3].size.should eq 3
    end
  end

  describe "#empty?" do
    it "is empty when no elements are in the array" do
      ([] of Int32).empty?.should be_true
    end

    it "is not empty if there are elements in the array" do
      [1].empty?.should be_false
    end
  end

  # lots more specs

end

Test files are structured by use of the describe or context methods. Typically a top level describe defines the outer unit (such as a class) that is to be tested by the spec. Further describe calls can be nested within the outer unit to specify smaller units under test (such as individual methods). describe can also be used to set up a certain context - think empty Array versus Array with elements. The context method behaves just like the describe method and may be used instead, to emphasize context to the reader.

Within a describe block, concrete test cases are defined with it . A descriptive string is supplied to it describing what the test case tests specifically.

Specs then use the should method to verify that the expected value is returned. See the example above for details.

By convention, specs live in the spec directory of a project. You can compile and run the specs of a project by running:

crystal spec

You can also compile and run individual spec files by providing their path:

crystal spec spec/my/test/file_spec.cr

In addition, you may run individual specs by providing a line number:

crystal spec spec/my/test/file_spec.cr:14

Defined in:

spec/dsl.cr
spec/context.cr
spec/expectations.cr
spec/formatter.cr
spec/junit_formatter.cr
spec/source.cr
spec.cr

Class Method Summary

Class Method Detail

def self.add_formatter(formatter) #

View source
def self.after_each(&block) #

Instructs the spec runner to execute the given block after each spec, regardless of where this method is invoked.


View source
def self.before_each(&block) #

Instructs the spec runner to execute the given block before each spec, regardless of where this method is invoked.


View source
def self.override_default_formatter(formatter) #

View source