Overwrite connection inside a test

Hi, I am new to Phoenix. I want to test a controller function in a Phoenix App.
I created a tag for the setup in conn_case.ex.

setup tags do
  cond do
    tags[:example_tag] == true ->
      club = insert(:club, name: "example club")

      %{ build_conn() | host: "example_host.com"}
      |> assign(:club, club)

      {:ok, conn: conn}

Inside the test, I want to change the value of :club in conn.assigns:

@tag :example_tag
test "example test", %{ conn: conn } do
  club = conn.assigns.club 
    |> Map.put(:name, "new club")

  conn = conn
    |> Plug.Conn.assign(:club, club)

  get(conn, ClubRoutes.example_path(conn, :test_function, conn.assigns.locale))


The connection is successfully overwritten. However when I dispatch, the connection used inside test_function doesn’t contain my changes.

Instead it’s the original connection from the context with the old club (and hence the old club name “example club”).

I can solve this by adding the name as a value to the tag like @tag example_tag: "new club" and adapting the setup:

tags[:example_tag] ->
  club = insert(:club, name: if is_binary(tags[:example_tag]), do: tags[:example_tag], else: "example club" )

  %{ build_conn() | host: "example_host.com"}
  |> assign(:club, club)

  {:ok, conn: conn}

However, for me it’s more convenient to overwrite the connection after building it - inside the test. Is there a way I can do that? Is that recommended?


I can’t seem to reproduce:




defmodule Controller do
  use Phoenix.Controller
  import Plug.Conn

  def show(conn, _params) do
    IO.inspect(conn.assigns, label: "assigns")
    send_resp(conn, :ok, [])

defmodule Router do
  use Phoenix.Router
  get("/", Controller, :show)

defmodule Endpoint do
  use Plug.Builder

defmodule Test do
  use ExUnit.Case

  import Plug.Conn
  import Phoenix.ConnTest

  @endpoint Endpoint

  setup do
    {:ok, conn: Phoenix.ConnTest.build_conn()}

  test "example test", %{conn: conn} do
    conn = Plug.Conn.assign(conn, :club, "club")
    conn = get(conn, "/")
    assert conn.status == 200
> elixir test.exs

// ... phoenix warnings ...

00:14:31.334 [debug] Processing with Controller.show/2
  Parameters: [UNFETCHED]
  Pipelines: []
assigns: %{club: "club"}

Finished in 0.1 seconds (0.1s on load, 0.00s async, 0.00s sync)
1 test, 0 failures

Randomized with seed 325480

Note that assigns have been updated to %{club: "club"} before going into Controller.show.

Thanks ruslandoga for pointing me to the actual problem. In my case, club is an entry in my test database and I still needed to write my changes to the database.