Recently while writing specs for a Phoenix application, I came across this scenario, where I needed to pass a jwt token in request-headers for authorization of Users.

I knew of a setup method where you can setup connection headers or variables to be used later in the tests. All worked fine for one or two modules. But it felt wrong. I thought may be I could do this in a module and later use it in others, like Plugs.

Here is the module I created.

  defmodule MyApplication.UserAuthentication do
    use ExUnit.CaseTemplate
    import Plug.Conn, only: [put_req_header: 3]
    alias MyApplication.{User, Repo}
    setup do
      user_params = %{email: "test@example.com", password: "hello123"}
      changeset = User.registration_changeset(%User{}, user_params)
      case Repo.insert(changeset) do
        {:ok, user} ->
          new_conn = Guardian.Plug.api_sign_in(Phoenix.ConnTest.build_conn(), user, :access)
          jwt = Guardian.Plug.current_token(new_conn)
      end
      conn = new_conn
        |> put_req_header("accept", "application/json")
        |> put_req_header("authorization", "Bearer #{jwt}")
      {:ok, conn: conn}
    end
  end

And later used it like:

  defmodule MyApplication.HomeControllerTest do
    use MyApplication.ConnCase
    use MyApplication.UserAuthentication
    ......
  end

And voila, I had proper authorization headers with jwt.