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
GenServerto do the work? Why not just call a function, that way you won't block for every request to theGenServer. - Justin Woodproducts = Repo.all(Product)just to have a simple interaction with the database. So this is the question about Ecto Sandbox behaviour, not about the GenServer results - iacobSonEcto.Adapters.SQL.Sandbox.mode(Repo, :manual)is called in thetest_helper.exs? Are you usingConnCaseorDataCasetemplates from the phoenix generator ? Are you running the tests withasync: true? If not, then it should work automatically in:sharedmode. - Mike Buhottest_helper.exsusing DataCase tried both withasync: trueand without, so it is not working in shared mode unless I restart the process as stated above. Please note that MyGenServer process is started together with the app, so before the::ok = Ecto.Adapters.SQL.Sandbox.checkout(MyApp.Repo)All the examples on Ecto Sandbox are starting the processes in the test, so after the owner process (test process) - iacobSon