Passing data/state from test_setup to tests

I am trying to build a Phoenix multi-tenant app and am getting stuck trying to pass tenant info from the one-time test_setup to the running tests. Ideally what I want to do is create a new tenant when tests start and pass the ID to the running tests so they can use the tenant ID and pass it to their respective Repo functions.

test_setup.exs

ExUnit.start()

tenant = "user#{System.unique_integer()}"

# Create a tenant for tests.  For performance reasons, the tenant is created
# and migrated only once before all tests run.
IO.puts("Creating tenant for tenantID: #{tenant}")
{ :ok, _tenant } =
    Analytics.Tenant.create(%{ username: tenant, company_name: "abc corp"})

{:ok, tenant}

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

I discovered that I can pass state from the conn_case.exs…

setup tags do

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

    unless tags[:async] do

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

    end

    {:ok, %{ tenant: "HOW CAN I GET THE test_setup tenant????" } }

  end

As a secondary question, how can I tear down the initial setup after the tests run? I want to delete the tenant that was created when the tests start.

Quick and dirty: use an Agent registered with a name so store and retrieve the tenant id from anywhere. Or maybe use Application.put_env/2.

Thanks, that gives me some direction.

Have you seen ExUnit.Callbacks — ExUnit v1.12.1 ? I think setup_all and on_exit might be useful for your case.

Yes, I did see this in the docs. For tearing down database, it seems like on_exit should work. For now, I am just setting up a single setup for testing and just keep it around between tests.