trenpixster/addict

How to use Addict in controller tests?

Qqwy opened this issue · 2 comments

Qqwy commented

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.

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.

As posted in a comment here by @trenpixster you can use this in your test:

setup do 
  user = %{ email: "test@example.com", name: "something" }
  conn = Plug.Test. init_test_session(build_conn(), %{current_user: user})
  {:ok, [conn: conn]}
end