-
-
Notifications
You must be signed in to change notification settings - Fork 10
with routes macro
with-routes!
(found in stub-http.core
) is a macro that is useful if you don't need to reuse the "server" instance returned by start!. You can pass both bindings and routes to the macro. The macro expose three bindings to the body of the macro: uri
, port
and server
. In its simplest form it can be used by only specifying a route:
(with-routes!
{"/something" {:status 200 :content-type "text/plan" :body "hello" }}
(is (= "hello" (:body (client/get (str uri "/something"))))))
This will start the stub server on a free port (available via port
). The server is started by the macro and is reached from the uri
(as seen in the example).
Another useful feature of with-routes!
is the ability to declare bindings. This makes the code more compact and may avoid an additional let
statement. For example let's say you're serializing a map to a JSON string that you want to return as the response body. One way would be to do like this:
(let [body (json/generate-string {:hello "world"})]
(with-routes!
{"/something" {:status 200 :content-type "text/plan" :body body }}
(is (= "world" (->> (client/get (str uri "/something")) :body :hello)))))
but since with-routes!
also allows you to declare bindings you can do like this:
(with-routes! [body (json/generate-string {:hello "world"})]
{"/something" {:status 200 :content-type "text/plan" :body body }}
(is (= "world" (->> (client/get (str uri "/something")) :body :hello))))
which is less verbose.