Cover by Brian Carper, Christophe Grand, Chas Emerick

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Growing an HTML DSL

As a live example of testing during development, let’s use tests to help us build a library to generate HTML. The result will be a simple-minded version of Hiccup (https://github.com/weavejester/hiccup), a library that produces HTML that mirrors the structure of defined or generated Clojure collections.

Our goal is to be able to write HTML snippets like this:

[:html
 [:head [:title "Propaganda"]]
 [:body [:p "Visit us at "
         [:a {:href "http://clojureprogramming.com"}
          "our website"]
         "."]]]

And compile them into HTML like this:

<html>
  <head><title>Propaganda</title></head>
  <body>
    <p>Visit us at <a href="http://clojurebook.com">our website</a>.</p>
  </body>
</html>

Here, vectors (or really, any sequential collection) represent HTML elements where the first value is the element name, the second is an optional map of its attributes, and remaining values are the contents of the element, which can be either strings or additional vectors representing child elements.

Let’s write some tests to get started. We know that our eventual HTML-generating function is going to be pure; it’s going to accept some input, and produce some result without any external dependency or effect. We’d hate to have to write (is (= expected (ƒ input))) over and over; so, most of our tests will likely use are:

(deftest test-addition
  (are [x y z] (= x (+ y z))
    10 7 3
    20 10 10
    100 89 11))

are is a helper macro in clojure.test that templatizes assertions. For example, the are form above macroexpands into this: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required