Conveniences for testing plugs.

This module can be used in your test cases, like this:

use ExUnit.Case, async: true
use Plug.Test

Using this module will:

  • import all the functions from this module
  • import all the functions from the Plug.Conn module

By default, Plug tests checks for invalid header keys, e.g. header keys which include uppercase letters, and raises a Plug.Conn.InvalidHeaderError when it finds one. To disable it, set :validate_header_keys_during_test to false on the app config.

config :plug, :validate_header_keys_during_test, true



conn(method, path, params_or_body \\ nil)

Creates a test connection

delete_req_cookie(conn, key)

Deletes a request cookie

init_test_session(conn, session)

Initializes the session with the given contents

put_req_cookie(conn, key, value)

Puts a request cookie

recycle_cookies(new_conn, old_conn)

Moves cookies from a connection into a new connection for subsequent requests


Returns the sent response


conn(method, path, params_or_body \\ nil)

conn(String.Chars.t, binary, params) :: Plug.Conn.t

Creates a test connection.

The request method and path are required arguments. method may be any value that implements to_string/1 and it will properly converted and normalized (e.g., :get or "post").

The params_or_body field must be one of:

  • nil - meaning there is no body;
  • a binary - containing a request body. For such cases, :headers must be given as option with a content-type;
  • a map or list - containing the parameters which will automatically set the content-type to multipart. The map or list may contain other lists or maps and all entries will be normalized to string keys;


conn(:get, "/foo", "bar=10")
conn(:post, "/")
conn("patch", "/", "") |> put_req_header("content-type", "application/json")

delete_req_cookie(conn, key)

delete_req_cookie(Plug.Conn.t, binary) :: Plug.Conn.t

Deletes a request cookie.

init_test_session(conn, session)

init_test_session(Plug.Conn.t, %{optional(String.t | atom) => any}) :: Plug.Conn.t

Initializes the session with the given contents.

If the session has already been initialized, the new contents will be merged with the previous ones.

put_req_cookie(conn, key, value)

put_req_cookie(Plug.Conn.t, binary, binary) :: Plug.Conn.t

Puts a request cookie.

recycle_cookies(new_conn, old_conn)

recycle_cookies(Plug.Conn.t, Plug.Conn.t) :: Plug.Conn.t

Moves cookies from a connection into a new connection for subsequent requests.

This function copies the cookie information in old_conn into new_conn, emulating multiple requests done by clients where cookies are always passed forward, and returns the new version of new_conn.


Returns the sent response.

This function is useful when the code being invoked crashes and there is a need to verify a particular response was sent even with the crash. It returns a tuple with {status, headers, body}.

© 2013 Plataformatec
Licensed under the Apache License, Version 2.0.