SpecinboxDocs
← Dashboard

Test runner examples

Playwright, Cypress, pytest, Jest and CI: create an inbox, run the signup, poll for the OTP, assert, clean up.

Every runner does the same four calls: POST /v1/inboxes, your app's signup with the returned address, a poll of GET /v1/inboxes/{id}/messages?limit=1 every 2 seconds until a message appears, GET /v1/messages/{id} for the text, then the assertion and DELETE /v1/inboxes/{id}. Use a tm_live_ key so your app's real mail arrives; with a tm_test_ key nothing outside can reach the inbox, so inject the message after the signup step instead (the fixture message with code 424242 is already there). Prefer a push? Register a webhook and skip the poll.

Playwright (TypeScript)

Playwright's own request API (request.newContext) does the API calls, so no extra HTTP package. Set SPECINBOX_API_KEY in the environment.

// tests/signup.spec.ts
import { test, expect, request } from "@playwright/test";

const API = "https://api.specinbox.com/v1";
const KEY = process.env.SPECINBOX_API_KEY!; // tm_live_... so real mail arrives

test("signup sends a 6-digit code", async ({ page }) => {
  const api = await request.newContext({
    extraHTTPHeaders: { Authorization: `Bearer ${KEY}` },
  });
  const inbox = await (await api.post(`${API}/inboxes`, {
    data: { expires_in: 900 },
  })).json();
  // inbox.address looks like [email protected]

  await page.goto("https://staging.yourapp.example/signup");
  await page.fill("input[name=email]", inbox.address);
  await page.click("button[type=submit]");

  // poll the inbox every 2 s, up to 60 s
  let otp: string | undefined;
  const deadline = Date.now() + 60_000;
  while (!otp && Date.now() < deadline) {
    const { data } = await (
      await api.get(`${API}/inboxes/${inbox.id}/messages?limit=1`)
    ).json();
    if (data.length) {
      const msg = await (await api.get(`${API}/messages/${data[0].id}`)).json();
      otp = `${msg.subject}\n${msg.text}`.match(/\b\d{6}\b/)?.[0];
    }
    if (!otp) await page.waitForTimeout(2_000);
  }

  expect(otp).toMatch(/^\d{6}$/);
  await page.fill("input[name=code]", otp!);
  await expect(page.getByText("Welcome")).toBeVisible();

  await api.delete(`${API}/inboxes/${inbox.id}`);
});

Cypress

cy.request runs from the Node side, so the API key never reaches the browser. The poll is a recursive command chain, the Cypress way to wait on an external system.

// cypress/e2e/signup.cy.js
// CYPRESS_SPECINBOX_API_KEY=tm_live_... in the environment
const API = "https://api.specinbox.com/v1";
const headers = {
  Authorization: `Bearer ${Cypress.env("SPECINBOX_API_KEY")}`,
};

// recursive poll: every 2 s, up to 30 tries
function waitForOtp(inboxId, triesLeft = 30) {
  expect(triesLeft, "OTP arrived in time").to.be.greaterThan(0);
  return cy
    .request({ url: `${API}/inboxes/${inboxId}/messages?limit=1`, headers })
    .then(({ body }) => {
      if (!body.data.length) {
        return cy.wait(2000).then(() => waitForOtp(inboxId, triesLeft - 1));
      }
      return cy
        .request({ url: `${API}/messages/${body.data[0].id}`, headers })
        .then(({ body: msg }) => {
          const otp = `${msg.subject}\n${msg.text}`.match(/\b\d{6}\b/)?.[0];
          if (otp) return otp;
          return cy.wait(2000).then(() => waitForOtp(inboxId, triesLeft - 1));
        });
    });
}

it("signup sends a 6-digit code", () => {
  cy.request({
    method: "POST",
    url: `${API}/inboxes`,
    headers,
    body: { expires_in: 900 },
  })
    .its("body")
    .then((inbox) => {
      cy.visit("/signup");
      cy.get("input[name=email]").type(inbox.address);
      cy.get("button[type=submit]").click();

      waitForOtp(inbox.id).then((otp) => {
        expect(otp).to.match(/^\d{6}$/);
        cy.get("input[name=code]").type(otp);
        cy.contains("Welcome");
        cy.request({ method: "DELETE", url: `${API}/inboxes/${inbox.id}`, headers });
      });
    });
});

pytest

The inbox is a fixture with teardown, so a failed test still deletes it. The page argument is pytest-playwright's; swap in Selenium or a plain HTTP signup call and the mail side is unchanged.

# tests/test_signup.py
# SPECINBOX_API_KEY=tm_live_... in the environment; the mail side is plain
# requests, so any browser driver works (pytest-playwright shown).
import os, re, time
import pytest, requests

API = "https://api.specinbox.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['SPECINBOX_API_KEY']}"}


@pytest.fixture
def inbox():
    box = requests.post(f"{API}/inboxes", headers=HEADERS,
                        json={"expires_in": 900}).json()
    yield box  # box["address"] looks like [email protected]
    requests.delete(f"{API}/inboxes/{box['id']}", headers=HEADERS)


def wait_for_otp(inbox_id, timeout=60):
    deadline = time.time() + timeout
    while time.time() < deadline:
        page = requests.get(f"{API}/inboxes/{inbox_id}/messages",
                            headers=HEADERS, params={"limit": 1}).json()
        if page["data"]:
            msg = requests.get(f"{API}/messages/{page['data'][0]['id']}",
                               headers=HEADERS).json()
            match = re.search(r"\b\d{6}\b", f"{msg['subject']}\n{msg['text']}")
            if match:
                return match.group()
        time.sleep(2)
    raise TimeoutError("No OTP arrived in time")


def test_signup_sends_code(inbox, page):
    page.goto("https://staging.yourapp.example/signup")
    page.fill("input[name=email]", inbox["address"])
    page.click("button[type=submit]")

    otp = wait_for_otp(inbox["id"])
    assert re.fullmatch(r"\d{6}", otp)

    page.fill("input[name=code]", otp)
    assert page.get_by_text("Welcome").is_visible()

Jest / Vitest

For an API-level test with no browser: the quickstart's JavaScript, inside a test with a 90-second timeout.

// signup.test.ts (Jest or Vitest, plain fetch, no extra packages)
const API = "https://api.specinbox.com/v1";
const headers = { Authorization: `Bearer ${process.env.SPECINBOX_API_KEY}` };
const call = (path: string, init?: RequestInit) =>
  fetch(`${API}${path}`, { headers, ...init }).then((r) => r.json());

test("signup sends a 6-digit code", async () => {
  const inbox = await call("/inboxes", { method: "POST" });
  await signUp(inbox.address); // your app's signup call or page driver

  let otp: string | undefined;
  for (let i = 0; i < 30 && !otp; i++) {
    const { data } = await call(`/inboxes/${inbox.id}/messages?limit=1`);
    if (data.length) {
      const msg = await call(`/messages/${data[0].id}`);
      otp = `${msg.subject}\n${msg.text}`.match(/\b\d{6}\b/)?.[0];
    }
    if (!otp) await new Promise((r) => setTimeout(r, 2_000));
  }

  expect(otp).toMatch(/^\d{6}$/);
  await fetch(`${API}/inboxes/${inbox.id}`, { method: "DELETE", headers });
}, 90_000);

GitHub Actions and GitLab CI

Put the key in a secret and run the shards. Limits that matter here (details): the 10 requests per second rate limit is per key, the 60 inbox creations per minute are per organization. Four shards polling every 2 seconds use 2 requests a second, so one key is enough; add a key per pipeline only when their combined polling nears 10 a second. One inbox per test, deleted in teardown, keeps you far from the active-inbox cap; on a retried POST /v1/inboxes send the same Idempotency-Key so a timeout never creates two.

# .github/workflows/e2e.yml
jobs:
  e2e:
    runs-on: ubuntu-latest
    strategy:
      matrix: { shard: [1, 2, 3, 4] }
    steps:
      - uses: actions/checkout@v4
      - run: npm ci && npx playwright install --with-deps chromium
      - run: npx playwright test --shard=${{ matrix.shard }}/4
        env:
          # one key for the project; see the note below before adding more
          SPECINBOX_API_KEY: ${{ secrets.SPECINBOX_API_KEY }}
# .gitlab-ci.yml  (SPECINBOX_API_KEY as a masked CI/CD variable)
e2e:
  image: node:22
  parallel: 4
  script:
    - npm ci
    - npx playwright install --with-deps chromium
    - npx playwright test --shard=$CI_NODE_INDEX/$CI_NODE_TOTAL