Define flexible specifications around data and function definitions to test for correctness and generate comprehensive test data.
Spec is included in Clojure from 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)
- practicalli/leveraging-spec - basic examples of using spec, following the Practicalli Spec broadcasts
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.