Open Qqwy opened 8 years ago
Here's how I managed to solve it. First I've created my own authenticated plug edition:
defmodule Publisher.Plugs.Authenticated do
import Plug.Conn
def init(options) do
options
end
def call(conn, _) do
conn = fetch_session(conn)
session_current_user = get_session(conn, :current_user)
if !is_nil(session_current_user) || !is_nil(conn.assigns[:current_user]) do
conn |> assign(:current_user, session_current_user)
else
not_logged_in_url = Addict.Configs.not_logged_in_url || "/login"
conn |> Phoenix.Controller.redirect(to: not_logged_in_url) |> halt
end
end
end
Then added a way to set up a user when I need it into ConnCase:
def user do
user_attrs =%{
name: "Basil Pupkin",
email: "basil@mailinator.com",
encrypted_password: "whatever"
}
user = Repo.get_by(Publisher.User, user_attrs)
if is_nil(user) do
struct(Publisher.User, user_attrs)
|> Repo.insert!
else
user
end
end
def logged_in(conn) do
conn
|> assign(:current_user, user)
end
And here's how it looks in the controller tests:
test "GET /", %{conn: conn} do
conn = conn |> logged_in |> get("/")
assert html_response(conn, 200) =~ "Welcome to Glo Publisher platform!"
end
Seems to look pretty slick. Hope it helps somebody to get it done a tad faster than I did.
The pre-made controller tests that Phoenix generates will break when you add authentication using Addict.
How can I log in the
conn
before doing these tests?I believe that this is very valuable information to put in the Readme.