-
Notifications
You must be signed in to change notification settings - Fork 99
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to use Addict in controller tests? #84
Labels
Comments
Qqwy
changed the title
No documentation on how to use in tests
How to use Addict in controller tests?
May 22, 2016
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: "[email protected]",
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. |
tomfbiz
pushed a commit
to tomfbiz/addict
that referenced
this issue
May 24, 2017
For applications that use addict, it is often useful to be able to create tests without having a session. With this change, if a tester set :current_user in the assigns, the plug does nothing, and the test proceeds as if the :current_user is logged in. Addresses (at least in part)issue trenpixster#84
As posted in a comment here by @trenpixster you can use this in your test:
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
The text was updated successfully, but these errors were encountered: