Please im writing a test that would check that a user is redirected to a particular URL if they are logged in and try to visit certain URLs
#auth.ex
def authenticated_user(conn,_opts) do
if conn.assigns.current_user do
conn
|> redirect(to: Helpers.user_path(conn,:dashboard))
|> halt()
end
conn
end
# router.ex
pipe_through [:browser, :authenticated_user]
get "/signup", UserController, :new
get "/signin", SessionController, :new
#_test.ex
setup %{conn: conn} = config do
if email = config[:login_as ] do
user = insert_user(%{email: "demo"})
conn = assign(build_conn(),:current_user, user)
{:ok, conn: conn, user: user}
else
:ok
end
end
@tag login_as: "test user "
test "redirect already logged user when /signin or /signup is visited ", %{conn: conn} do
Enum.each([
get(conn, session_path(conn, :new)),
get(conn, user_path(conn, new)),
], fn conn ->
assert redirected_to(conn,302) == "/dashboard"
end)
end
The test still fails after implementation. Please what am I missing?
Actually, the correct implementation needs to handle the else case. A plug always excepts a conn to be retuned.
#auth.ex
def authenticated_user(conn,_opts) do
# Don't use the `.` below. It will fail if the map does not have the key.
if conn.assigns[:current_user] do
conn
|> redirect(to: Helpers.user_path(conn,:dashboard))
|> halt() # stops the remaining plugs from being run.
else
# just returning conn will allow the requested page to be rendered
conn
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With