Email verification tests tend to become unreliable for a reason that is easy to miss: the inbox is shared state. One test creates an account, another test reads its message, and a retry may find an old verification link instead of the one it expected.
I have had better results by treating every test inbox and verification record as a run-scoped fixture. The fixture gets an owner, an expiry time, and a correlation ID. PostgreSQL stores the relationship, while the test client uses the correlation ID to ask the REST API for exactly one expected result.
This approach works whether the test system creates mailboxes internally or uses a controlled free throwaway email provider in staging. Isolation belongs in our application and test design.
Why email fixtures need a scope
A test that searches an inbox for “verification” is asking a vague question. It may match a message from a previous run, a parallel test, or a user who happens to share the same fixture address. The failure often looks like a timing bug, but the root cause is missing ownership.
I put a run ID on every fixture and include it in the local-part or provider metadata when the provider allows that. The database record also stores the expected recipient, test case ID, and creation timestamp. A message is accepted only when those values match.
The important part are the boundaries. A test can read its own fixture, but it should not be able to consume another test's message simply because it arrived first. For a shared CI environment, this rule matters more than shaving a few seconds off polling.
Model the fixture lease in PostgreSQL
A small table is enough for most systems:
CREATE TABLE email_test_fixtures ( id uuid PRIMARY KEY, run_id text NOT NULL, test_case text NOT NULL, address text NOT NULL, status text NOT NULL DEFAULT 'active', lease_until timestamptz NOT NULL, consumed_at timestamptz, created_at timestamptz NOT NULL DEFAULT now(), UNIQUE (run_id, test_case) ); The unique constraint makes fixture creation idempotent for a test case. If a worker retries after a network timeout, it can retrieve the existing row instead of allocating another address. This is less clever, but more reliable then creating another inbox on every retry.
The lease gives cleanup a safe rule. A fixture is active while its lease is valid; after that, a reaper may mark it expired and ask the provider to remove it. The reaper should update rows in small batches and record failures. A fixture should be deleted when it is no longer need, but deletion errors must remain visible.
For parallel workers, claim expired rows with a short transaction:
WITH candidates AS ( SELECT id FROM email_test_fixtures WHERE status = 'active' AND lease_until < now() ORDER BY lease_until FOR UPDATE SKIP LOCKED LIMIT 100 ) UPDATE email_test_fixtures AS f SET status = 'cleaning' FROM candidates WHERE f.id = candidates.id RETURNING f.id, f.address; Do not hold the row lock while calling an external mailbox API. Claim the work, commit, perform the network operation, and then write the outcome with the fixture ID and worker token. Otherwise one slow provider can block every cleanup worker.
Keep REST API tests idempotent
The test-facing endpoint should expose a stable contract, even if the mailbox provider is eventually consistent. For example, POST /test-fixtures can accept a run ID and test case, then return the existing fixture when the same pair is submitted again.
The response should include a fixture ID, address, lease expiration, and a correlation ID. It should not return a mailbox password or expose internal provider tokens. The test can then call GET /test-fixtures/{id}/messages?correlation_id=... and receive a clear state such as pending, matched, or expired.
Polling is easier to debug when each attempt has a deadline. The test don't need to guess how many retries are enough; the API can return Retry-After for a pending message, and the client stops at the fixture lease deadline. In practise, this also prevents a stuck inbox from extending the whole CI job forever.
A freshness gate is valuable here. Before accepting a message, check its received time and correlation data, not only its subject. The ideas in a freshness gate for email tests map well to backend integration tests too. A string like tempail mail in a fixture label is harmless; using arbitrary text as identity is not.
Make cleanup observable
Cleanup is part of the test result, not housekeeping after it. I record these counters per run:
- fixtures created, reused, consumed, expired, and deleted
- messages matched and rejected as stale
- provider cleanup failures
- the oldest active lease
When a run ends, the test harness can call a bulk cleanup endpoint with its run ID. That endpoint should be idempotent and return counts. A scheduled reaper remains necessary for crashed runners.
The same principle applies to PostgreSQL rows. Marking a fixture deleted before the provider confirms removal can make the database look healthy while external data remains behind. I prefer a cleanup_pending state and a bounded retry policy. It make dashboards slightly more detailed, but incidents are much easier to explain.
If a team already uses an approval workflow for generated test plans, freezing the test plan before execution is a useful companion practice. The run ID, test list, and fixture policy should be fixed before workers start.
A practical integration-test checklist
Before relying on run-scoped email fixtures in CI, check the following:
- Every fixture has a run ID, test case ID, lease, and correlation ID.
- Fixture creation is idempotent under client and worker retries.
- Message matching checks recipient, freshness, and correlation data.
- REST API responses expose states and deadlines instead of provider internals.
- PostgreSQL claims use short transactions and
SKIP LOCKEDwhere parallel cleanup needs it. - End-of-run cleanup reports counts and failures.
- A background reaper handles runners that disappear without cleanup.
Run-scoped fixtures remove a large class of false failures. The test result then describes the system under test, instead of which parallel job read the inbox first.