DEV Community

Silviu Technology
Silviu Technology

Posted on

Playwright Email Tests Need a Fixture Lease

Email verification tests often look stable until the suite runs in parallel. Then a test reads a message created by another test, cleanup removes an inbox that is still in use, or a retry finds an old verification link. The failure message usually says “expected 1 message, received 0,” but the real problem is ownership.

I use a fixture lease to make ownership visible. Every Playwright worker gets a run-scoped inbox, a lease with an expiry time, and a cleanup record. The test can use a free temp email address for a controlled verification flow, while the fixture controls when that address belongs to the test and when it is safe to release.

The failure pattern: a test passes with the wrong inbox

Consider two tests running together:

signup.spec.ts      -> creates user A -> waits for verification
password-reset.spec.ts -> creates user B -> waits for reset email
Enter fullscreen mode Exit fullscreen mode

If both tests use qa@example.test, a broad “latest message” query can return either message. A slower test may pass today because the timing happens to be friendly. Tomorrow, a faster CI runner changes the order and the same assertion fails.

There are a few less obvious versions of the same bug:

  • A worker reuses an inbox after a test timeout, so the next test sees stale mail.
  • Cleanup runs immediately after the assertion, while a delayed provider webhook is still arriving.
  • A retry keeps the browser state but creates a new inbox, so the logs no longer describe one test run.
  • A test fixture has a fixed address such as temp org mail, and parallel shards quietly share it.

These are isolation failures, not usually Playwright selector failures. Fixing the timeout can hide the symptom, but it does not establish ownership.

What a fixture lease guarantees

A lease is a small contract between the test and the inbox service. It should answer four questions:

  1. Which run and worker currently own this inbox?
  2. When does that ownership expire?
  3. What happens if the test crashes without cleanup?
  4. Can a later test prove that a message belongs to its own flow?

The lease record can be simple:

type FixtureLease = {
  id: string;
  address: string;
  owner: string;
  expiresAt: string;
  createdAt: string;
};
Enter fullscreen mode Exit fullscreen mode

The important field is not the email address. It is the owner, which should include a CI run ID, project name, worker index, and a short test identifier. A message assertion can then require the expected owner or a correlation token in the message body.

I also prefer a lease that expires automatically. If a worker is killed, the inbox should become recoverable after a bounded period. The lease should not last forever just because teardown did not run; teardown is helpful, but it is not a reliability strategy by itself.

Implement the lease as a Playwright fixture

Create the inbox in a worker-scoped fixture when several tests can safely share one isolated worker resource. Use a test-scoped fixture when each test needs stronger separation. The choice should be explicit in the fixture name, because a shared resource can look private in a test file.

Here is the shape of a test-scoped fixture. The API client details are intentionally small; the useful part is the ownership and cleanup order:

import { test as base } from '@playwright/test';

type Fixtures = {
  emailFixture: { address: string; owner: string };
};

export const test = base.extend<Fixtures>({
  emailFixture: async ({}, use, testInfo) => {
    const owner = `${process.env.CI_RUN_ID ?? 'local'}-${testInfo.workerIndex}-${testInfo.testId}`;
    const lease = await inboxApi.reserve({ owner, ttlSeconds: 300 });

    try {
      await use({ address: lease.address, owner });
    } finally {
      await inboxApi.release({ leaseId: lease.id, owner });
    }
  },
});
Enter fullscreen mode Exit fullscreen mode

The finally block matters because assertion failures still need cleanup. It do not solve a machine kill, so the service must also enforce ttlSeconds on the server side.

When waiting for a message, filter by both the leased address and a correlation value generated for the test. Matching only on subject is too broad. A small message contract, such as a verification ID rendered in a data attribute or text token, makes a wrong-message failure much easier to diagnose.

For teams already collecting CI evidence, GitHub Actions summaries for email checks is a useful related pattern. Put the lease owner, wait duration, and message ID in the summary, but redact the message body if it can contain user data.

Diagnose expiry, cleanup, and parallelism

When a test fails, log facts that identify the lifecycle without leaking the full email content:

  • lease ID and owner
  • reservation and expiry timestamps
  • worker index and shard
  • message correlation ID
  • number of polling attempts
  • cleanup result and release timestamp

A tem email string in a debug note may look harmless, but inconsistent fixture labels make searches harder. Use stable field names in JSON logs instead.

Three failure classes are especially useful:

Expired lease. The wait exceeded the lease TTL. Either the provider is slower than expected or the test is doing too much work before reading the message. Increase the TTL only after measuring the wait, otherwise a stuck test gets a larger hiding place.

Wrong owner. The message exists, but its correlation token belongs to another test. This points to address reuse, a broad query, or a provider that did not isolate the inbox as expected.

Cleanup conflict. The release call reports that the lease is already gone or owned by another run. Treat this as evidence of a race. The cleanup are not allowed to delete a resource that a newer owner has reserved.

For API-backed inboxes, contract-testing email APIs in GitHub Actions can catch schema drift before browser tests turn it into a confusing timeout. Keep the browser test focused on user behavior; validate reservation and message filtering contracts at the API boundary.

A repeatable CI checklist

Before calling an email test reliable, check these points:

  • Does every run receive a unique owner and correlation ID?
  • Can two workers reserve separate inboxes at the same time?
  • Does a server-side TTL reclaim abandoned leases?
  • Does the message query filter by address, owner evidence, and correlation ID?
  • Is cleanup safe when a later run already owns the same resource?
  • Are lease and polling timings visible in CI artifacts?
  • Can a failed test preserve its lease metadata long enough for diagnosis?

Run the test with at least two workers and an intentionally delayed message. A suite that only passes with one worker has not proven isolation. It merely has less opportunity to expose the race.

Questions that come up in review

Should every test get a new inbox?

Not always. A worker-scoped inbox can reduce setup time when messages are correlated strictly and tests never overlap within that worker. Use test scope for flows that mutate shared mailbox state or are still being stabilized. Faster setup is not worth ambiguous ownership.

Is a longer timeout the fix?

Usually no. A timeout should represent an expected provider delay plus margin. A longer timeout cannot distinguish a slow message from a message that belongs to another test. Measure the distribution, then set a bounded wait and report the reason for expiry.

Can a temporary inbox be used in production tests?

It can be appropriate for staging and controlled QA, but do not use disposable mailboxes for real customer data or as an authentication guarantee. The test system should prove your application contract, not depend on an inbox remaining available forever.

The fixture lease is a small addition, but it changes the debugging question from “why did Playwright miss the email?” to “which run owned this message, and for how long?” That is a much better starting point for reliable automation.

Top comments (0)