请我编写一个测试来检查用户是否被重定向到特定的 URL,如果他们登录并尝试访问某些 URL
#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
实现后测试仍然失败。请问我错过了什么?
最佳答案
实际上,正确的实现需要处理 else 情况。插头总是不包括要重新调整的连接。
#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
关于elixir - Assert conn 在 phoenix 中被重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43621222/