【问题标题】:Assert conn was redirected in phoenix断言 conn 在 phoenix 中被重定向
【发布时间】:2017-04-25 21:22:55
【问题描述】:

请我编写一个测试来检查用户是否已登录并尝试访问某些 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

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

【问题讨论】:

  • 请添加 ex_unit 输出
  • RuntimeError 预期重定向,状态为 302,得到:200
  • 这表明问题出在您的控制器上。请发布SessionController.createUserController.create 的控制器代码
  • @MikeBuhot,我已使用相关代码对我的问题进行了更改
  • 该代码看起来也不错。测试如何建立conn.assigns.current_user

标签: elixir phoenix-framework


【解决方案1】:

其实正确的实现需要处理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

【讨论】:

  • 这显然是一个更好更准确的解决方案
【解决方案2】:

尝试删除最后一个 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

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-07
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2018-04-11
    • 1970-01-01
    相关资源
    最近更新 更多