2017-04-25 97 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 

希望它可以幫助