     raw: false
 db = connection.database('cozy')
 
+# helpers
 
-# TEST SECTION #################################################################
+cleanRequest = ->
+    delete @body
+    delete @response
 
+parseBody = (response, body) ->
+    if typeof body is "object" then body else JSON.parse body
+
+# Clear DB, create a new one, then init data for tests.
 before (done) ->
-    # Prepare database for tests
     db.destroy ->
         console.log 'DB destroyed'
         db.create ->
             console.log 'DB recreated'
-            db.save '321', {"value":"val"} # insert id 321 : Existence
+            db.save '321', {"value":"val"}, ->
+                done()
 
-    # start app
+# Start application before starting tests.
+before (done) ->
     app.listen(8888)
     done()
 
+# Stop application after finishing tests.
 after (done) ->
     app.close()
     done()


describe "Find", ->
    describe "Find a Document that does not exist in database", ->
        before ->
            delete @body
            delete @response

        it "When I send a request to get Document with id 123", (done) ->
            client.get "data/123/", (error, response, body) =>

            @response.statusCode.should.equal(404)

    describe "Find a Document that does exist in database", ->
        before cleanRequest

        it "When I send a request to get Document with id 321", (done) ->
            client.get 'data/321/', (error, response, body) =>
                response.statusCode.should.equal(200)
                @body = parseBody response, body
                done()

        it "Then { _id: '321', value: 'val'} should be returned", ->
            @body.should.deep.equal {"_id": '321', "value":"val"}

describe "Create", ->
    describe "Try to Create a Document with id 321", ->
        before cleanRequest

        it "When I send a request to create a document with id 321", (done) ->
            client.post 'data/321/', {"value":"created value"}, \
                        (error, response, body) =>
                @response = response
                done()

