From ceb8da8eecabfb0240c3dda2e8a2fba4ad41231e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Eppl=C3=A9e?= Date: Wed, 3 Dec 2025 10:41:40 +0100 Subject: [PATCH] Fix postgres errors when running tests --- config/test.exs | 3 +++ lib/mv_web/endpoint.ex | 5 +++++ test/support/conn_case.ex | 10 ++++++++-- test/support/data_case.ex | 2 ++ 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/config/test.exs b/config/test.exs index bcb55eb..2c4d2ba 100644 --- a/config/test.exs +++ b/config/test.exs @@ -45,3 +45,6 @@ config :mv, :token_signing_secret, "test_secret_key_for_ash_authentication_token config :mv, :session_identifier, :unsafe config :mv, :require_token_presence_for_authentication, false + +# Enable SQL Sandbox for async LiveView tests +config :mv, :sql_sandbox, true diff --git a/lib/mv_web/endpoint.ex b/lib/mv_web/endpoint.ex index 97dcae4..d1b4247 100644 --- a/lib/mv_web/endpoint.ex +++ b/lib/mv_web/endpoint.ex @@ -39,6 +39,11 @@ defmodule MvWeb.Endpoint do plug Phoenix.Ecto.CheckRepoStatus, otp_app: :mv end + # Enable Ecto SQL Sandbox in test environment for async tests + if Application.compile_env(:mv, :sql_sandbox) do + plug Phoenix.Ecto.SQL.Sandbox + end + plug Phoenix.LiveDashboard.RequestLogger, param_key: "request_logger", cookie_key: "request_logger" diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex index 0ee2364..853a326 100644 --- a/test/support/conn_case.ex +++ b/test/support/conn_case.ex @@ -123,7 +123,13 @@ defmodule MvWeb.ConnCase do end setup tags do - Mv.DataCase.setup_sandbox(tags) - {:ok, conn: Phoenix.ConnTest.build_conn()} + pid = Mv.DataCase.setup_sandbox(tags) + + conn = Phoenix.ConnTest.build_conn() + # Set metadata for Phoenix.Ecto.SQL.Sandbox plug to allow LiveView processes + # to share the test's database connection in async tests + conn = Plug.Conn.put_private(conn, :ecto_sandbox, pid) + + {:ok, conn: conn} end end diff --git a/test/support/data_case.ex b/test/support/data_case.ex index 6e53c38..4ba75ef 100644 --- a/test/support/data_case.ex +++ b/test/support/data_case.ex @@ -34,10 +34,12 @@ defmodule Mv.DataCase do @doc """ Sets up the sandbox based on the test tags. + Returns the owner pid for use with Phoenix.Ecto.SQL.Sandbox. """ def setup_sandbox(tags) do pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Mv.Repo, shared: not tags[:async]) on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end) + pid end @doc """