jswny

jswny

Getting Plug.Conn.AlreadySentError but only in tests

I’m using Programming Phoenix by Chris McCord as a reference to build my personal blog. I’ve replicated the authentication implementation almost exactly, but now that I am working through the chapter about testing the authentication plug, I’m getting (Plug.Conn.AlreadySentError) the response was already sent. However, the site works fine when navigating through it regularly, just not in the tests. I’ve looked the problem up and ensured I don’t have plug :action anywhere and am calling halt() after I redirect when an action isn’t authorized. If anyone could help I’d really appreciate it :slight_smile: Relevant code:

  1) test login puts the user into the session (PhoenixBlog.AuthTest)
     test/plugs/auth_test.exs:28
     ** (Plug.Conn.AlreadySentError) the response was already sent
     stacktrace:
       (plug) lib/plug/conn.ex:862: Plug.Conn.put_session/3
       (phoenix_blog) web/plugs/auth.ex:25: PhoenixBlog.Plugs.Auth.login/2
       test/plugs/auth_test.exs:31: (test)

  2) test authenticate_user halts when no current_user exists (PhoenixBlog.AuthTest)
     test/plugs/auth_test.exs:14
     ** (Plug.Conn.AlreadySentError) the response was already sent
     stacktrace:
       (plug) lib/plug/conn.ex:607: Plug.Conn.put_resp_header/3
       (phoenix) lib/phoenix/controller.ex:303: Phoenix.Controller.redirect/2
       (phoenix_blog) web/plugs/auth.ex:57: PhoenixBlog.Plugs.Auth.authenticate_user/2
       test/plugs/auth_test.exs:15: (test)

Notice that only the tests which hit the current_user doesn’t exist clause in authenticate_user fail.

defmodule PhoenixBlog.AuthTest do
  use PhoenixBlog.ConnCase
  alias PhoenixBlog.Plugs.Auth

  setup %{conn: conn} do
    conn =
      conn
      |> bypass_through(Rumbl.Router, :browser)
      |> get("/")

    {:ok, %{conn: conn}}
  end

  test "authenticate_user halts when no current_user exists", %{conn: conn} do
    conn = Auth.authenticate_user(conn, [])
    assert conn.halted
  end

  test "authenticate_user continues when the current_user exists", %{conn: conn} do
    conn =
      conn
      |> assign(:current_user, %PhoenixBlog.User{})
      |> Auth.authenticate_user([])

    refute conn.halted
  end

  test "login puts the user into the session", %{conn: conn} do
    login_conn =
      conn
      |> Auth.login(%PhoenixBlog.User{id: 123})
      |> send_resp(:ok, "")

    next_conn = get(login_conn, "/")
    assert get_session(next_conn, :user_id) == 123
  end
end

Auth plug:

defmodule PhoenixBlog.Plugs.Auth do
  import Plug.Conn
  import Comeonin.Bcrypt, only: [checkpw: 2, dummy_checkpw: 0]

  def init(opts) do
    Keyword.fetch!(opts, :repo)
  end

  def call(conn, repo) do
    user_id = get_session(conn, :user_id)

    cond do
      user = conn.assigns[:current_user] ->
        conn
      user = user_id && repo.get(PhoenixBlog.User, user_id) -> 
        assign(conn, :current_user, user)
      true ->
        assign(conn, :current_user, nil)
    end
  end

  def login(conn, user) do
    conn
    |> assign(:current_user, user)
    |> put_session(:user_id, user.id)
    |> configure_session(renew: true)
  end

  def logout(conn) do
    configure_session(conn, drop: true)
  end

  def login_by_username_and_pass(conn, username, given_pass, opts) do
    repo = Keyword.fetch!(opts, :repo)
    user = repo.get_by(PhoenixBlog.User, username: username)

    cond do
      user && checkpw(given_pass, user.password_hash) ->
        {:ok, login(conn, user)}
      user ->
        {:error, :unauthorized, conn}
      true ->
        dummy_checkpw()
        {:error, :not_found, conn}
    end
  end

  import Phoenix.Controller
  alias PhoenixBlog.Router.Helpers

  def authenticate_user(conn, _opts) do
    if conn.assigns.current_user do
      conn
    else
      conn
      |> put_flash(:error, "You must be logged in to access that page")
      |> redirect(to: Helpers.page_path(conn, :index))
      |> halt()
    end
  end
end

Marked As Solved

jswny

jswny

Wow, I’m dumb :stuck_out_tongue: Turns out I forgot to change bypass_through(Rumbl.Router, :browser) to bypass_through(PhoenixBlog.Router, :browser) after I pasted the code from the book. Thanks Jose for your help and to @luke on Slack for talking the problem out with me and helping me fix it :smiley:

Also Liked

josevalim

josevalim

Creator of Elixir

I believe you need to call conn = recycle(conn) after using the connection if you want to do another request with it.

jswny

jswny

I’m not sure exactly where I would put that function, but I put it in the setup callback like so:

setup %{conn: conn} do
  conn =
    conn
    |> recycle()
    |> bypass_through(Rumbl.Router, :browser)
    |> get("/")

  {:ok, %{conn: conn}}
end

However that still did not fix my problem :confused: I also tried putting the recycle call in each of the failing tests before I used conn but that did not work either. I’m not sure what to do.

josevalim

josevalim

Creator of Elixir

It needs to be after get/2.

Where Next?

Popular in Questions Top

WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41989 114
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 48342 226
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement