Demo
GUIDE

Loops and conditionals

8 MIN READ

A loop must define what repeats, what it operates on, when it stops, and the final state after it stops. Use one of the three forms below.

1. Repeat one statement until a condition

Use this form when exactly one statement repeats a limited number of times while waiting for a visible condition to become achieved or no longer achieved.

text
Repeat <single statement> up to <x> times, until <condition is achieved or is no longer achieved>

Condition becomes achieved:

gherkin
Repeat clicking the "Refresh" button up to `10` times, until the "Status" field shows "Completed"
Then the "Status" field should show "Completed"

Condition becomes no longer achieved:

gherkin
Repeat clicking the "Load More" button up to `20` times, until the "Load More" button is no longer visible
Then all result rows should be loaded

x is the maximum number of attempts, not a requirement to continue after the stop condition is satisfied. Check the condition after every repetition, stop immediately when it reaches the requested state, and fail clearly if it does not reach that state within x attempts.

2. For each item, perform one statement

Use a single-line For each instruction when every row, record, data point, card, or other item receives exactly one action.

text
For each <item in a named collection>, <perform one statement>
gherkin
For each row in the "Opportunity Products" table, ensure its "Selected" checkbox is checked
Then every row in the "Opportunity Products" table should be selected

For each data point in the "Monthly Revenue" chart, record its label and value
Then the recorded data-point count should equal the rendered data-point count

Name the collection and its boundaries. Do not use this form when each item needs several steps — use a loop block instead.

3. START LOOP and END LOOP for multiple statements

Use a loop block when every item or repetition requires two or more steps.

text
START LOOP <name the collection or starting condition>
  <step 1>
  <step 2>
  <step n>
END LOOP when <condition is achieved or is no longer achieved>
gherkin
START LOOP for each unprocessed row in the "Quote Lines" table
  When I fill `2` in the row's "Quantity" field
  And I click "Calculate"
  And I wait until the row's "Net Total" updates
  And I mark the row as processed
END LOOP when no unprocessed quote-line rows remain
Then the processed row count should equal the quote-line row count

START LOOP names the finite collection or repeatable starting state. END LOOP names the observable stop condition. The ending condition may require a state to be achieved — such as Status is "Completed" — or no longer achieved, such as the "Next" button is no longer enabled.

Safety boundaries

Every loop must have at least one of these:

  • a finite named collection;
  • an exact repeat count;
  • a maximum attempt count;
  • an observable terminal condition plus a maximum duration.

After the loop, confirm the final state and reconcile the processed count with the source count whenever the collection has a measurable size.

API-agent loop examples

Repeat one API statement while polling an asynchronous job:

gherkin
Given I call `POST /api/reports` with body [$.testdata.report.request]
And I require the response status code to be `202`
And I save response field `job_id` as [$.output.job_id]
Repeat calling `GET /api/jobs/[$.output.job_id]` every `10` seconds for up to `30` attempts, until response field `status` is "Completed" or "Failed"
Then the final response field `status` should be "Completed"
And response field `download_url` should be non-empty

Perform one API statement for each input item:

gherkin
For each customer ID in [$.testdata.customer_ids], call `GET /api/customers/{customer_id}` and record its status code
Then the recorded response count should equal the customer ID count

Use a loop block for paginated API processing:

gherkin
Given I set [$.runtime.next_page] to `/api/orders?limit=100`
START LOOP while [$.runtime.next_page] is not empty
  When I call `GET [$.runtime.next_page]`
  And I require the response status code to be `200`
  And I append response array `items` to [$.output.orders]
  And I set [$.runtime.next_page] to response field `next_page`
END LOOP when response field `next_page` is empty
Then the collected order count should equal response field `total_count`

The API loop condition must use a response status, response field, pagination token, item count, or another explicit response value. Never poll without a maximum attempt count or duration.

SQL-agent loop examples

Perform one statement for each row returned by a query:

gherkin
Given I run the parameterized query `SELECT order_id, status FROM orders WHERE created_at >= :start_date ORDER BY order_id` with `start_date` [$.testdata.start_date]
For each returned row, record its `order_id` and `status`
Then the recorded row count should equal the SQL result row count

Use a loop block to process a large result in deterministic batches:

gherkin
Given I set [$.runtime.last_order_id] to `0`
START LOOP while the current SQL batch contains rows
  When I run the parameterized query `SELECT order_id, status FROM orders WHERE order_id > :last_order_id ORDER BY order_id LIMIT :batch_size` with the current cursor and [$.testdata.batch_size]
  And I require every returned `order_id` to be greater than [$.runtime.last_order_id]
  And I append the returned rows to [$.output.orders]
  And I set [$.runtime.last_order_id] to the greatest returned `order_id`
END LOOP when the SQL query returns no rows
Then the collected `order_id` values should be unique and strictly increasing

SQL loops must use parameterized queries, deterministic ordering, a finite result boundary, and a final row-count or uniqueness reconciliation. Use read-only queries unless the test explicitly requires an authorized database mutation.

Fixed cases are not runtime loops

Use Scenario Outline when the input set is known before execution.

gherkin
Scenario Outline: Validate each account type
  When I select "<account_type>" from the "Type" picklist
  Then the "Type" picklist should show "<account_type>"

  Examples:
    | account_type      |
    | Customer - Direct |
    | Customer - Channel |

NEVER

Never write only loop through all rows, repeat until done, or keep trying. Choose the appropriate loop form and state its boundary and completion condition.

Conditional flows

A conditional flow must use an observable application condition. State what happens when the condition is achieved and, when required, what happens when it is not.

1. Single-line IF and ELSE

Use one line when each branch contains one action.

text
IF <condition is achieved>, <do one statement>; ELSE <do one alternate statement>
gherkin
If the "Existing Account" result is visible, click its "Open" link; else click the "Create Account" button
Then the Account page or the "New Account" modal should be visible

The condition must identify a visible field state, message, record, button state, page state, response value, or other observable result. The ELSE branch runs only when the stated condition is not achieved.

2. START IF and END IF for multiple statements

Use an IF block when the achieved branch needs two or more steps.

gherkin
START IF the "Approval Required" message is visible
  When I select [$.testdata.approver.name] from the "Approver" lookup
  And I fill [$.testdata.approval.reason] in the "Approval Reason" textarea
  And I click the "Submit for Approval" button
  Then the "Approval Status" field should show "Submitted"
END IF

When a multi-step alternate path is required, place ELSE between the two blocks:

gherkin
START IF the "Existing Account" result is visible
  When I open the exact matching account
  Then the Account record page should be visible
ELSE
  When I click the "Create Account" button
  Then the "New Account" modal should be visible
END IF

After END IF, use a common assertion only when both branches are expected to reach that state. Do not use a conditional to make a required assertion optional.

API-agent conditional examples

Use a single-line branch when each API outcome needs one action:

gherkin
Given I call `GET /api/customers/by-external-id/[$.testdata.customer.external_id]`
If the response status code is `200`, save response field `id` as [$.output.customer_id]; else call `POST /api/customers` with body [$.testdata.customer.create_request]
Then [$.output.customer_id] or the create-response field `id` should be non-empty

Use an IF block when an accepted API request requires several follow-up steps:

gherkin
Given I call `POST /api/exports` with body [$.testdata.export.request]
START IF the response status code is `202`
  And I save response field `job_id` as [$.output.export_job_id]
  Repeat calling `GET /api/exports/[$.output.export_job_id]` up to `30` times, until response field `status` is "Completed" or "Failed"
  Then the final response field `status` should be "Completed"
END IF

API conditions must name the exact status code, response field, header, array length, or business status that selects the branch.

SQL-agent conditional examples

Use a single-line branch for one action per SQL result state:

gherkin
Given I run the parameterized query `SELECT COUNT(*) AS duplicate_count FROM customers WHERE external_id = :external_id` with [$.testdata.customer.external_id]
If `duplicate_count` is `0`, record the result as "Unique"; else record the result as "Duplicate"
Then the recorded result should equal [$.testdata.customer.expected_uniqueness]

Use an IF block when a SQL condition requires several validations:

gherkin
Given I run the parameterized query `SELECT customer_id, status, updated_at FROM customers WHERE external_id = :external_id` with [$.testdata.customer.external_id]
START IF the SQL query returns exactly one row
  Then its `customer_id` should be non-empty
  And its `status` should equal [$.testdata.customer.expected_status]
  And its `updated_at` should be later than [$.testdata.test_start_time]
ELSE
  Then the SQL result should fail with "Expected exactly one customer row"
END IF

SQL conditions must name the query, parameters, expected row count, and exact column values used by the branch. Never place credentials or unescaped user values inside SQL text.