gpt4 book ai didi

elixir - Assert conn 在 phoenix 中被重定向

转载 作者:行者123 更新时间:2023-12-04 17:52:25 24 4
gpt4 key购买 nike

请我编写一个测试来检查用户是否被重定向到特定的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com