Share repo transaction in tests

Hi,

My app makes use of two separate Repo, is there a way my tests can share the same “transaction” through the multiple repos?
I have a setup like this in my conn_case.ex

    :ok = Ecto.Adapters.SQL.Sandbox.checkout(MyCoolApp.Repo)
    :ok = Ecto.Adapters.SQL.Sandbox.checkout(MyCoolModule.Repo)

    Ecto.Adapters.SQL.Sandbox.mode(MyCoolApp.Repo, {:shared, self()})
    Ecto.Adapters.SQL.Sandbox.mode(MyCoolModule.Repo, {:shared, self()})

And my test_helper.ex is like that:

ExUnit.start(capture_log: true, timeout: 1_000)

Ecto.Adapters.SQL.Sandbox.mode(MyCoolApp.Repo, :manual)
Ecto.Adapters.SQL.Sandbox.mode(MyCoolModule.Repo, :manual)

{:ok, _} = Application.ensure_all_started(:ex_machina)
{:ok, _} = Application.ensure_all_started(:faker)

Application.put_env(:plug, :validate_header_keys_during_test, false)

But if I insert(:my_object) in a test, it goes into the MyCoolModule.Repo and if for some reason one of my resolvers calls a query that hits MyCoolApp.Repo it comes back empty (makes sense).

Can I somehow set it up so that the sandbox transaction would encompass both Repo?

Thanks!

A transaction is scoped to a single database connection, and by definition each repo will have its own connection set, so I don’t see how this is possible. Can you elaborate on the need for this use case?

1 Like

I have several Query modules across different umbrella apps. The idea is to maximize re-usability of the code by calling a Query from separate apps into my resolvers. While that works outside of tests since the database would get updated for all connections, it doesn’t in test due to the repo isolation. I’m trying to see if I’ll have to duplicate my query into the app using it for the sake of the tests, or if I can get away with some clever configuration to avoid doing that.

Hi,

Even i have a similar requirement, where in a master database is used for writes and slave database for reads. Now, when i wanted to setup a test using sandbox, I would like to write data into data to master and read data from slave in single test.

Is it possible to do with sandbox testing?

Can someone provide an example for the same.

There’s some docs on testing with read replicas: https://hexdocs.pm/ecto/replicas-and-dynamic-repositories.html#testing-replicas

1 Like