I have a Phoenix Test Application with a Product schema. I have a GenServer started by the main application supervisor that gets a list of the products with handle_call.
def handle_call(:get_products, _from, _state)
products = Repo.all(Product)
{:reply, products, products}
end
Now I want to write a test for this GenServer.
I tried to do something like this in the test
setup do
pid = Process.whereis(MyGenServer)
Ecto.Adapters.SQL.Sandbox.allow(Repo, self(), pid)
ProductFactory.insert_list(3, :product) # using ExMachina for factories
end
The 3 products get created, I can find them in the test with Repo.all(Product), however running the MyGenServer.get_products()
will return an empty array.
I am not getting any error, but just returns an empty array, as if no products exist.
Is there any way to allow the existing PID to use the checkout sandbox connection, and retrieve my products in the GenServer process?
PS. I managed to run the test by restarting the GenServer process in the test setup, but I was wondering if there is a more "elegant" way to solve the issue.
setup do
Supervisor.terminate_child(MyApp.Supervisor, MyGenServer)
Supervisor.restart_child(MyApp.Supervisor, MyGenServer)
ProductFactory.insert_list(3, :product)
end
Thanks
Here's a minimal phoenix application that works with a
GenServer
started in the application supervisor, using:shared
mode for database interactions.Application Module:
Product Module:
GenServer Module:
Test Module:
DataCase Module
test_helper: