Testing POST route with anti-forgery and ring-mock

Viewed 1149

I want to write a test for a simple POST request using ring.mock - something like this:

(testing "id post route"
    (let [response (app (mock/request :post "/" {:id "Foo"}))]
      (is (= 302 (:status response)))))

However, since I use the wrap-csrf middleware I get a 403 status response since I don't provide an anti-forgery token.

Is there a way to write POST tests with ring.mock without disabling the wrap-csrf middleware?

3 Answers

We can disable the csrf in tests using (assoc site-defaults :security false). The complete code is something like this:

; Create a copy of testing app in utilities.testing
; by wrapping handler with testing middlewares

(ns utilities.testing
    (:require [your-web-app.handler :refer [path-handler]]
              [ring.middleware.defaults :refer [wrap-defaults site-defaults]]))

; Disabling CSRF for testing
(def app
    (-> path-handler
        (wrap-defaults (assoc site-defaults :security false))))

Now you can use this app in tests

(ns users.views-test
    (:require [utilities.testing :refer [app]]
              ;...
              ))

;...
(testing "id post route"
    (let [response (app (mock/request :post "/" {:id "Foo"}))]
      (is (= 302 (:status response)))))

Related