Clojure Spec is a library for defining specifications around data and functions to test for correctness.
A spec defines the expected shape of specific values in Clojure and specs are intended to be used across multiple projects. Specifications for more complex values are composed of specific value specifications, providing a flexible way to define what key parts of the system should look like.
Clojure specs are used to generate comprehensive test data, identifying more scenarios and edge cases with less code.
Spec is included in Clojure version 1.9 onward and can be used by requiring the
clojure.spec.alpha in the REPL or in namespaces of a Clojure project.
Purpose of Clojure specλ︎
A summary highlighting the common purposes that Clojure Spec is used for
|Living documentation||Use spec to include specifications in Function documentation (
|Data Validation||Ensure the data entering and leaving the system or its key functions are of the correct form|
|Test Data Generation||Provide extensive test data coverage with minimal code maintenance|
|Generative testing of functions||Test functions using their spec defined contract (
|Generative scenario testing||Specific correct usage paths for known states|
|Development time checking||Instrument functions to ensure correctness|
|Derive code from specifications||Specify a system of record for data structures, internal and external to the system.|
Example use casesλ︎
- API requests (schema is often used here, but so can spec)
- Checking data pulled from / pushed to message systems (e.g. Kafka, TIBCO)
- Data specifications (eg. Vega-lite)
Understanding the basics of Clojure Specλ︎
Follow the examples in these two excellent videos
Why is the spec library called alpha?λ︎
The library is called
clojure.spec.alpha as the design of spec is still evolving and there may be some changes to the design in later versions. Clojure aims for backwards compatibility, so new versions typically do not break existing use of libraries.
There are some important changes being developed for spec version 2 and a few things may change, however, the large majority of Spec will remain the same and is safe to use.