断言conn在凤凰中被重定向

时间:2017-04-25 21:22:55

标签: elixir phoenix-framework

请写一个测试,如果用户已登录并尝试访问某些网址,则会检查用户是否已重定向到特定网址

#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

实施后测试仍然失败。请问我错过了什么?

2 个答案:

答案 0 :(得分:1)

实际上,正确的实现需要处理else的情况。插头总是排除要重新调整的conn。

#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

答案 1 :(得分:0)

尝试删除最后一个conn。测试了您的代码,最终返回状态200

#auth.ex
def authenticated_user(conn,_opts) do
if conn.assigns.current_user do
conn #<-- 302 returned here
|> redirect(to: Helpers.user_path(conn,:dashboard))
|> halt()
end
#conn <-- Remove this line, "" returned here
end

希望有所帮助