1

From this Simple authentication tutorial

I am looking to test routes of the app inside the :login_required pipeline (which simply checks if the client has called Guardian.Plug.sign_in(conn, user))

As the user_path show action needs to have been piped through the :login_required pipeline, I would have thought that to test this route I would simply need to write the following:

Auth.login_by_email_and_pass(conn, user.email, @password)

and then pipe the conn that comes out of that into:

get conn, user_path(conn, :show, user.id)

and check that I get a 200 status code.

But I can't get past the Auth.login_by_email_and_pass(conn, email, password) line and get the error:

session not fetched, call fetch_session/2

Where should I fetch the session?

I have tried bypass_through(conn, [:browser, :with_session])

I would have thought that the :browser pipeline invokes fetch_session which would have solved this issue.

I have also tried as calling fetch_session before and after, but still get the same error

Sam Houston
  • 3,413
  • 2
  • 30
  • 46
  • 1
    Try calling `init_test_session/2`, like this: `conn = conn |> init_test_session(%{}) |> Auth.login_by_email_and_pass(user.email, @password)`. – Dogbert Jul 16 '17 at 19:03
  • @Dogbert Thank you, spot on, if you post an answer, I'll accept it – Sam Houston Jul 16 '17 at 20:22

1 Answers1

2

You can use Plug.Test.init_test_session/2 to initialize the session. Since you don't need to put any data, you can pass an empty map as the second argument.

conn = conn
  |> init_test_session(%{})
  |> Auth.login_by_email_and_pass(user.email, @password)
Dogbert
  • 212,659
  • 41
  • 396
  • 397