Elixir/Phoenix/Guardian - Assigning current_user in conn doesn't work for testing

522 Views Asked by At

If have some controllers like this

def index(%{assigns: %{current_user: %User{} = current_user}}} = conn, params) do
    ## User exists
end

def index(conn, params) do
    ## No user exists
end

If I run this test, I expect it to call the first #index action, but it calls the second action, with no users, and by conn assigns are %{current_user: nil}

test "GET /posts", %{conn: conn} do
    user = insert(:user)
    conn = assign(conn, :current_user, user)
    get(conn, post_path(conn, :index))
end

Why isn't the current_user being assigned properly? Why is it disappearing?

1

There are 1 best solutions below

1
On

I'm not sure but try this instead

def index (conn,params)
 current_user = conn.assigns.current_user
## User exists
end

try this