Keep the Gherkin free of codes and phone details. In a step definition, generate a unique phone number for the scenario, remember the time before the SMS is triggered, and poll the mock inbox's HTTP API for the code. Store the phone number and time on Cucumber's World so the next steps can read them. The same pattern works in Cucumber-JS, Cucumber-JVM and SpecFlow, because the only moving part is one HTTP request.
Step 1: route SMS to the mock
Your application sends the SMS, not Cucumber. In the test or staging environment, point your SMS provider's SDK at otpmock with one option. Each provider's option is on its provider page; otpmock emulates fifteen, including Twilio, Vonage, AWS SNS and Infobip. Production keeps using the real provider because the option is only set in test environments.
Step 2: write the scenario
Describe behavior, not plumbing. The scenario never mentions the code itself, so it keeps working when the code length or provider changes.
Feature: Phone signup
Scenario: A new user signs up with an SMS code
Given a new visitor with a unique phone number
When they request a verification code
And they enter the code they received by SMS
Then they see the welcome screen
Scenario: A wrong code is rejected
Given a new visitor with a unique phone number
When they request a verification code
And they enter a wrong code
Then they see an error about the codeStep 3: the step definitions
Download the dependency-free helper from /sdk/otpmock.mjs (or .ts) into features/support/. It exposes randomPhone() and waitForCode(phone, { since }). The steps below use Cucumber-JS with Playwright; use regular functions, not arrow functions, so that this is the World.
import { Given, When, Then, Before, After, setDefaultTimeout } from '@cucumber/cucumber';
import { chromium } from 'playwright';
import { expect } from '@playwright/test';
import { OtpMock } from '../support/otpmock.mjs';
setDefaultTimeout(60_000); // a page flow plus an SMS wait outlasts the 5 s default
const otp = new OtpMock({
baseUrl: process.env.OTPMOCK_URL ?? 'https://api.otpmock.com',
apiKey: process.env.OTPMOCK_API_KEY,
});
const BASE_URL = process.env.BASE_URL ?? 'https://staging.example.com';
Before(async function () {
this.browser = await chromium.launch();
this.page = await this.browser.newPage();
});
After(async function () {
await this.browser.close();
});
Given('a new visitor with a unique phone number', function () {
this.phone = otp.randomPhone(); // unique per scenario, so parallel scenarios never share an inbox
});
When('they request a verification code', async function () {
await this.page.goto(`${BASE_URL}/signup`);
await this.page.getByLabel('Phone').fill(this.phone);
this.since = Date.now() - 5_000; // taken before the SMS is triggered, with a margin for clock skew
await this.page.getByRole('button', { name: 'Send code' }).click();
});
When('they enter the code they received by SMS', async function () {
const { code } = await otp.waitForCode(this.phone, { since: this.since, timeout: 20_000 });
await this.page.getByLabel('Verification code').fill(code);
await this.page.getByRole('button', { name: 'Verify' }).click();
});
When('they enter a wrong code', async function () {
const { code } = await otp.waitForCode(this.phone, { since: this.since, timeout: 20_000 });
const wrong = code === '000000' ? '111111' : '000000';
await this.page.getByLabel('Verification code').fill(wrong);
await this.page.getByRole('button', { name: 'Verify' }).click();
});
Then('they see the welcome screen', async function () {
await expect(this.page.getByText('Welcome')).toBeVisible();
});
Then('they see an error about the code', async function () {
await expect(this.page.getByText('code is incorrect')).toBeVisible();
});Run it with npx cucumber-js --import 'features/**/*.mjs'. Pass OTPMOCK_API_KEY as an environment variable from your CI secret store; never write it in a step file.
Why the wrong-code scenario reads the real code first
The negative scenario still waits for the real code, then types a different one. That proves the SMS was sent (the scenario fails early if it was not) and guarantees the wrong value really is wrong. Reusing a fixed value such as 000000 could accidentally match a real code once in a million runs.
Other Cucumber flavors
- Cucumber-JVM. Put the polling in a small helper class that calls
GET https://api.otpmock.com/v1/inbox/{phone}/code?since={unix_ms}withjava.net.http.HttpClient, and keep the phone number and timestamp in a scenario-scoped object injected by PicoContainer or Spring. - SpecFlow / Reqnroll (.NET). Store the phone and timestamp in
ScenarioContextand poll the same URL withHttpClient. The Twilio in C# guide shows the polling helper. - Behave and pytest-bdd (Python). Use the context object or a fixture for the phone number, and
requests.getin the step.
Running scenarios in parallel
Cucumber-JS can run scenarios in parallel with --parallel. Because every scenario calls randomPhone(), no two scenarios share an inbox, and the since filter ignores any older code on the same number. If your app rejects +1555 numbers, pass another prefix such as otp.randomPhone('+4479').
Common pitfalls
- Putting the code in the Gherkin. A hard-coded code in a scenario is a test-only backdoor in disguise. Fetch it from the inbox instead.
- Arrow functions in steps. They do not get the World as
this, sothis.phoneis undefined. - Setting the variable only on the test runner. The app server sends the SMS, so the otpmock option must be set where the app runs.
- Taking
sinceafter the click. Note the time before the step that triggers the SMS. - Default step timeout. Cucumber-JS allows 5 seconds per step; raise it with
setDefaultTimeout.
FAQ
Should the code appear in the feature file?
No. Scenarios describe what a user does ("enters the code they received"). The step definition fetches the actual value from the inbox, so the feature file stays stable when the code length, SMS text or provider changes.
Does this work with Cypress or Selenium instead of Playwright?
Yes. Only the browser lines in the steps change. The inbox call is plain HTTP from the test process. See the Cypress and Selenium guides for the browser side.
Do I need to change application code?
Only where the SMS client is created, behind an environment variable that is set in test environments.
The free plan includes 300 messages a month. No card required.
Get a free API key