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}
[...]
end
end
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))
[...]
end
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?
Thanks!