How to start a persistent process in the test env only


I’m working on a library that supports different adapters to send and receive notifications.
Each adapter relies on an optional dependency, so that host applications can only require the one that’s being used.

In some cases, the host applications are also supposed to inject a client object. This can be a pid, or a public name for a GenServer.
The specific case I’m dealing with is a Phoenix.PubSub name (an atom). If the host Phoenix application wants the library to use the phoenix pubsub functionality, then the pubsub name configured in Phoenix needs to be passed down.

This works, but I’m having troubles testing it.
I need to start a named Phoenix.PubSub.PG2 broker with my application, and then configure things so that the name is being used.

My question is: where should I start this GenServer? If I add it to the application’s child processes it works, and I can easily add a check to only start it if Mix.env == "test", or if System.get_env("BROKER") returns the right value.
Still, it doesn’t seem very clean.

I tried to add it to test/test_helper.exs, but it doesn’t seem to work because it looks like it’s started after the rest of the application. Starting it from config/test.exs doesn’t work either.

You could use mix test --no-start, and then have something like


in your test_helper.exs. Would that work?

1 Like

That did the trick, thank you.