2017-04-25 76 views
1

请我写一个测试,将检查用户被重定向到一个特定的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 

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

+0

请状态302添加ex_unit输出 –

+0

RuntimeError预计重定向,得到:200 – user1232968

+0

这表明,问题是在您的控制器。请发布'SessionController.create'和'UserController.create'的控制器代码 –

回答

1

其实,正确的实现需要处理的其他案件。一个插头总是除了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

谢谢史蒂夫! – user1232968

+1

这显然是一个更好和准确的解决方案 – dev

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 

希望它可以帮助