elixir - Assert conn 在 phoenix 中被重定向

标签 elixir phoenix-framework

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

相关文章:

elixir - 如何在将 Ecto 变更集插入 repo 之前修改它?

elixir - 在 Phoenix 中使用模板不同布局的正确方法

phoenix-framework - ecto.repo检查id是否存在于数据库,Phoenix框架中

cookies - Phoenix 框架 : set "expires" attribute for response cookies

ssl - Phoenix 找不到 SSL key ,即使它存在于该位置

elixir - 人性化的绳子修剪

elixir-lang 在列表中查找非重复元素

elixir - 基于 Ecto 关联查询

elixir - 返回 map 还是转换为 map ?字数统计 Elixir

javascript - Phoenix 框架如何在js中模拟套接字