Skip to content

Instantly share code, notes, and snippets.

@Anonyfox
Created October 22, 2015 20:40
Show Gist options
  • Save Anonyfox/a8a7b9582f1366b6485b to your computer and use it in GitHub Desktop.
Save Anonyfox/a8a7b9582f1366b6485b to your computer and use it in GitHub Desktop.
Pattern how to test a controller that needs a logged-in user in phoenix. Follows the example code written in https://pragprog.com/book/phoenix/programming-phoenix
defmodule N3ws.ChannelControllerTest do
import Plug.Conn, only: [assign: 3]
@valid_attrs %{name: "some content"}
@invalid_attrs %{}
@user_attrs %{
email: "some content",
name: "some content",
password_virtual: "some content"
}
setup do
user = Repo.insert!(User.registration_changeset(%User{}, @user_attrs))
conn = assign(conn(), :current_user, user)
{:ok, conn: conn}
end
test "creates resource and redirects when data is valid", %{conn: conn} do
attrs = %{@valid_attrs | user_id: conn.assigns.current_user.id}
conn = post conn, channel_path(conn, :create), channel: attrs
assert redirected_to(conn) == channel_path(conn, :index)
assert Repo.get_by(Channel, attrs)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment