Hello all, I am trying to test controllers that require Guardian authentication (that I’m trying to fake).
My first approach was super complex and based on what I found in some other examples, for example:
I gave up because it gives problems one way or another.
Now I’m trying to simplify my approach to how it should really work in my opinion:
When signing the connection directly it still fails because “session not fetched, call fetch_session/2”, basically what I was doing before when getting “/”
I guess this is pretty common when using guardian, does anybody have any code to share? How are you testing controllers protected by guardian?
To solve this in my own case, I use a helper which I defined in conn_case.ex. The trick is to flush your session so subsequent requests contain the correct session data for Guardian to do its thing.
Helper for setting up a `conn` which logs in a user
def guardian_login(user, token \\ :token, opts \\ ) do
|> bypass_through(YourApp.Router, [:browser, :browser_authenticated_session])
|> Guardian.Plug.sign_in(user, token, opts)
|> send_resp(200, "Flush the session")
test "a thing that requires a logged in user" do
user = insert(:user)
conn = guardian_login(user)
conn = get(conn, path_requiring_authorisation(conn, :index))
assert html_response(conn, 200)
If you’re writing multiple tests which require a logged in user, consider building conn in a setup block and pass that down to your tests. In this example, conn which is passed down to the test in the background is not pattern matched on as we’re assigning our own conn from scratch.