r11na

r11na

How to stop Supervisors starting GenServer during Exunit tests?

I’m having difficult figuring out how to stop supervisors running genservers during my tests and I haven’t found any helpful guides online.

I have the following setup in a test file:

setup do
  {:ok, server_pid} = Program.Myserver.start_link()
  {:ok, server: server_pid}
end

When I run my tests I get an
** (MatchError) no match of right hand side value: {:error, {:already_started, #PID<0.405.0>}}

No doubt because the supervisor has already started the genserver but I don’t know how to stop it doing this during my tests…

Any ideas on the best way to stop this?

Most Liked

michalmuskala

michalmuskala

Since Elixir 1.5 the recommened approach for starting processes in a test is to use start_supervised/2. This is an easy way to ensure the process is started and stopped together with the test process.

blatyo

blatyo

Conduit Core Team

What I typically do for this situation is set something like this in config/test.exs:

config :my_app, :env, :test

Then in my application supervisor, I separate out the processes I don’t want to start automatically and check the env.

children = [{MyApp.Endpoint, []), {MyApp.Repo, []}]

children = case Application.get_env(:my_app, :env) do
  :test -> children ++ [{MyApp.OtherThing, []}]
  _ -> children
end

Supervisor.init(children, strategy: :one_for_one)

If there’s a better way than this, I’m not aware of it.

SZJX

SZJX

It seems that the easiest way to solve it is just to start your GenServer under a different name, using the :name option? Though if your GenServer functions depend on a hardcoded :name such as __MODULE__ it would indeed making testing harder.

e.g. instead of writing

  def start_link(_) do
    GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
  end

write

  def start_link(opts) do
    GenServer.start_link(__MODULE__, :ok, opts)
  end

and then the child spec:

      %{
        id: MyApp.MyGenServer,
        start: {MyApp.MyGenserver, :start_link, [[name: MyApp.MyGenServer]]}
      }

then in your test you can give a different name, e.g.

  setup context do
    _ = start_supervised!({MyApp.MyGenserver, name: context.test})
    %{producer: context.test}
  end
OvermindDL1

OvermindDL1

You just need to tear it down after, see another thread already talking about this at:

:slight_smile:

blatyo

blatyo

Conduit Core Team

The setup callback needs you to return one of those types. Like:

setup do
  start_supervised(CeresCore.Queue.Consumers.PaymentConsumer)
  :ok
end

The other issue appears to be that CeresCore.Queue.Consumers.PaymentConsumer.start_link/1 is not a function that exists.

Where Next?

Popular in Questions Top

Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Other popular topics Top

belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement