start! function

Johan Haleby edited this page Mar 27, 2016 · 4 revisions

start! (found in stub-http.core) is a function that is useful if you don't want to use the with-routes! macro, for example if you want to reuse the same server instance in multiple tests. start! also allows you to define additional settings (such as a predefined port) which the with-routes! macro doesn't. Usage example:

(let [server (start!  {"/something" {:status 200 :content-type "text/plan" :body "hello" }})
      uri (:uri server)]
      (try
        (is (= "hello" (:body (client/get (str uri "/something")))))
        (finally 
            (.close server)))

This will start the stub server on a free port and return the "server" record/instance. Note that if you use the start! function like this you need to stop it manually.

The server schema is defined like this:

{:uri <string> 
 :port <int> 
 :nano-server <instance of fi.iki.elonen.NanoHTTPD> 
 :routes {:request-spec-fn  <function that takes a request (map) that returns true/false whether this spec matches the request>
          :request-spec     <the request specification map>
          :response-spec-fn <function that takes a request (map) and return the response-spec>
          :response-spec    <the response specification map>
          :recordings       <vector of recordings>}}

with-open support

The server record implements Closable which means that you can use the with-open macro in Clojure to automatically having it closed. The previous example could thus be written as:

(with-open [server (start!  {"/something" {:status 200 :content-type "text/plan" :body "hello" }})]
           (is (= "hello" (:body (client/get (str uri "/something"))))))

which is less verbose.

Settings

The start! functions also allows you to define additional settings. Currently it allows you to specify an explicit port like this:

(start! {:port 8087} {"/something" {:status 200 :content-type "text/plan" :body "hello" }})
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.