Background
I have a set of tests that need a GenServer to be started before. As a rule of thumb, I understand it is a good practice to cleanup after each test, so I also want to stop the GenServer after each test.
Problem
The problem here is that I don't know how to stop a GenServer after the test has finished. I always end up with some concurrency issue.
defmodule MyModuleTest do
use ExUnit.Case
alias MyModule
setup do
MyModule.Server.start_link(nil)
context_info = 1
more_info = 2
%{context_info: context_info, more_info: more_info}
end
describe "some tests" do
test "returns {:ok, order_id} if order was deleted correctly", context do
# do test here that uses created server and passed context
assert actual == expected
#clean up?
end
end
end
Now, I have tried on_exit
/2 like the following:
setup do
{:ok, server} = MyModule.Server.start_link(nil)
context_info = 1
more_info = 2
on_exit(fn -> GenServer.stop(server) end)
%{context_info: context_info, more_info: more_info}
end
But i get this error:
** (exit) exited in: GenServer.stop(#PID<0.296.0>, :normal, :infinity)
** (EXIT) no process: the process is not alive or there's no process currently associated with the given name, possibly because its application isn't started
I have the feeling this is exiting too soon.
I also tried using start_supervised
however since my GenServer
has a lengthy initialization in handle_continue
the tests run before the server is ready.
Question
How can I fix this?