Spec-Driven Tests

Checking arguments is not the only clojure.spec-based facility you can use to improve the reliability of your code. You also take advantage of clojure.spec—and specifically fdef—to drive test.check generative tests. Think about it: in spec’ing the arguments of a function you are also providing much of the information required to generate those arguments.

If we have this simple marketing blurb–generating function and an fdef to go with it, we can run the function with 1,000 randomly generated books:

 (​defn​ book-blurb [book]
  (str ​"The best selling book "​ (:title book) ​" by "​ (:author book)))
 
 (s/fdef book-blurb :args (s/cat :book ::book))

All we need is the check function:

 (require '[clojure.spec.test.alpha :as stest]) ...

Get Getting Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.