Skip to content

Clojure Specificationsλ︎

Clojure specifications banner

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.

What is Clojure spec - an illustrated guide

Purpose of Clojure specλ︎

A summary highlighting the common purposes that Clojure Spec is used for

Purpose Description
Living documentation Use spec to include specifications in Function documentation (fdef)
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 (fdef)
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)

Example codeλ︎

practicalli/leveraging-spec

practicalli/leveraging-spec - basic examples of using spec, following the Practicalli Spec broadcasts

Understanding the basics of Clojure Specλ︎

Trying 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.

Referencesλ︎

spec guide - clojure.org Introducing clojure.spec clojure.spec - rational and overview

spec.alpha API reference

How do you use clojure.spec - Sean Corfield

Specifications for clojure.core

Leveraging clojure.spec - Stuart Halloway spec.test - Stuart Halloway

Clojure Spec: Expressing Data Constraints without Types