In my Phoenix app I’m using Phoenix PubSub to subscribe interally to events and take actions based on them being broadcast.
In order to manage this I have an Events
module that includes a subscriber and handlers to various events:
defmodule MyApp.Events.Subscriber do
use GenServer
def start_link(_) do
GenServer.start_link(__MODULE__, name: __MODULE__)
end
def init(_) do
PubSub.subscribe(my_pubsub_module, "my_app_events")
{:ok, []}
end
def handle_info({:some_event, payload}, _) do
do_important_stuff_with(payload)
{:noreply, []}
end
end
To broadcast an event I just do something like:
PubSub.local_broadcast(my_pubsub_module, "my_app_events", {event, payload})
The subscriber is supervised by including it in the application’s children list.
This works well, but there’s a problem in my tests. Where the test calls a function that broadcasts an event that has a subscriber that does stuff (like access the DB, send an email etc) I get an error like so:
[error] Task #PID<0.510.0> started from #PID<0.449.0> terminating
** (stop) exited in: DBConnection.Holder.checkout(#PID<0.486.0>, [log: #Function<15.53332199/1 in Ecto.Adapters.SQL.with_log/3>, source: "users", caller: #PID<0.449.0>, timeout: 15000, pool_size: 10, pool: DBConnection.Ownership])
** (EXIT) shutdown: "owner #PID<0.485.0> exited"
(db_connection 2.3.0) lib/db_connection/holder.ex:86: DBConnection.Holder.checkout/2
(db_connection 2.3.0) lib/db_connection/holder.ex:67: DBConnection.Holder.checkout/2
The test still passes, but this suggests something is wrong.
How can I prevent such an error?