Inferensys

Prompt

Automation-Ready Assertion Generation Prompt Template

A practical prompt playbook for converting manual test expected results into precise, non-flaky automation assertions for Playwright, Selenium, or Cypress.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Automation-Ready Assertion Generation Prompt Template.

This prompt is designed for SDETs and automation engineers who need to convert the expected results from a manual test case into a precise, non-flaky, and maintainable set of automation assertions. The core job-to-be-done is translating a human-readable description of correct behavior—often vague or implicit—into an explicit chain of code-level matchers, tolerance ranges, and negative checks that can be directly wired into a test script for frameworks like Playwright, Selenium, or Cypress. The ideal user is someone who understands both the application under test and the pitfalls of UI automation, such as timing issues, dynamic content, and selector brittleness. Required context includes the manual test step, the expected result, the type of UI element involved (e.g., text, input, visibility state), and the target automation framework.

You should not use this prompt when the expected result is fundamentally unverifiable through the UI layer alone, such as a backend state change with no visible side effect. It is also the wrong tool for generating entire test scripts from scratch; it focuses exclusively on the assertion block. Avoid using it for performance or load test assertions, which require statistical analysis over time rather than binary pass/fail checks. If the manual expected result is ambiguous or contains multiple conflicting conditions, resolve that ambiguity through human analysis first. Feeding an unclear expected result into this prompt will produce a brittle assertion chain that is likely to generate false positives or false negatives in CI.

To use this effectively, provide the prompt with a single, well-scoped expected result statement and specify the target assertion library (e.g., Playwright's expect, Chai, Jest). The output should be treated as a first draft that requires human review against the criteria of over-assertion (checking more than necessary), under-assertion (missing a critical condition), and ordering dependencies (assertions that fail if run in the wrong sequence). After generating the assertions, run them against a known-good application state and a deliberately broken state to validate their precision before committing them to your test suite.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and the operational risks to manage before putting it into a test automation pipeline.

01

Good Fit: Structured Expected Results

Use when: manual test cases already define expected results with specific values, states, or conditions. The prompt excels at converting 'the button should be disabled' into precise assertion chains with explicit matchers. Avoid when: expected results are vague ('works correctly') or purely subjective ('looks good').

02

Bad Fit: Visual-Only Verification

Avoid when: the expected result can only be verified by human visual inspection—layout aesthetics, animation smoothness, or color harmony. The prompt generates functional assertions, not perceptual judgments. Guardrail: pair with visual regression tools for pixel-level checks; use this prompt only for behavioral assertions.

03

Required Inputs: Expected Results with Tolerances

Risk: the prompt cannot invent acceptable tolerance ranges for numeric or temporal assertions. Guardrail: ensure manual test cases specify precision requirements (e.g., 'within 500ms', '±0.5%'). If tolerances are missing, flag the test case as incomplete before generating assertions.

04

Operational Risk: Over-Assertion Creep

Risk: the model may generate assertions for every observable property, creating brittle tests that fail on irrelevant changes. Guardrail: always run the output through the prompt's built-in over-assertion review criteria. Remove assertions that don't directly validate the expected behavior under test.

05

Operational Risk: Assertion Ordering Dependencies

Risk: generated assertion chains may have hidden ordering dependencies where an early assertion failure masks later, more informative failures. Guardrail: review the assertion sequence for independence. Use soft assertions where appropriate, and ensure the most diagnostic assertions run first.

06

Pipeline Integration: Human Review Gate

Risk: auto-generated assertions entering a CI pipeline without review can cause false-positive test failures that erode team trust in automation. Guardrail: require human approval for first-time assertion generation on each test case. After the assertion set stabilizes, allow automated regeneration only when the expected result text changes.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for generating precise, non-flaky automation assertions from manual test case expected results.

This prompt template converts the 'Expected Result' column of a manual test case into a chain of programmatic assertions suitable for Playwright, Selenium, or Cypress. It forces the model to produce explicit matchers, tolerance ranges, and negative assertions rather than vague expect(page).toContain('success') statements. The template is designed to be copied directly into your test generation pipeline, with square-bracket placeholders replaced by your test management system or CI context.

text
You are an SDET converting manual test case expected results into automation-ready assertion chains for [FRAMEWORK, e.g., Playwright, Selenium, Cypress].

## INPUT
Test Case ID: [TEST_CASE_ID]
Test Step Description: [STEP_DESCRIPTION]
Expected Result (manual): [EXPECTED_RESULT]
Application Under Test URL/Context: [APP_CONTEXT]
Known UI Element Selectors: [SELECTOR_MAP, e.g., data-testid attributes or CSS classes]

## CONSTRAINTS
- Produce assertions that are deterministic and not timing-dependent.
- Prefer `data-testid` selectors over CSS classes or XPath when available.
- Include explicit tolerance ranges for any numeric or datetime values.
- Add at least one negative assertion to confirm the absence of error states or stale content.
- Do not use `sleep()` or fixed-time waits. Use framework-native wait strategies tied to specific conditions.
- If the expected result is ambiguous, flag it as [NEEDS_CLARIFICATION] and explain what is missing.

## OUTPUT_SCHEMA
Return a JSON object with the following structure:
{
  "test_case_id": "string",
  "assertions": [
    {
      "assertion_id": "string",
      "type": "positive | negative | visual | contract",
      "framework_code": "string (the actual assertion statement)",
      "matcher": "string (e.g., toEqual, toContainText, toHaveCount)",
      "target_selector": "string",
      "expected_value": "string | number | boolean | null",
      "tolerance": "string | null (e.g., '+/- 5%', 'within 2 seconds')",
      "wait_strategy": "string (e.g., 'waitForSelector', 'waitForResponse')",
      "failure_message": "string (custom error message if assertion fails)"
    }
  ],
  "ordering_notes": "string (explain assertion dependency order if any)",
  "clarifications_needed": ["string (list of ambiguous inputs that need human resolution)"]
}

## EXAMPLES
[EXAMPLES: Provide 1-2 few-shot examples of manual expected results and their corresponding assertion chains in the target framework.]

## RISK_LEVEL
[RISK_LEVEL: low | medium | high. If high, add a note that assertions must be reviewed by a senior SDET before merging.]

Generate the assertion chain now.

To adapt this template, replace the square-bracket placeholders with values from your test management system. The [SELECTOR_MAP] is critical: providing known stable selectors prevents the model from inventing brittle CSS paths. The [EXAMPLES] placeholder should contain 1-2 few-shot demonstrations of your team's preferred assertion style and framework conventions. If the [RISK_LEVEL] is high, the output should be routed through a human review step before the assertions are committed to the test repository. After generating the assertions, validate them against the eval criteria in the companion evaluation section of this playbook before integrating them into your CI pipeline.

IMPLEMENTATION TABLE

Prompt Variables

Inputs required for the Automation-Ready Assertion Generation Prompt Template. Each placeholder must be populated before the prompt is sent. Validation notes describe how to confirm the input is sufficient to produce reliable assertions.

PlaceholderPurposeExampleValidation Notes

[TEST_STEPS]

The manual test case steps including actions and expected results

  1. Click 'Submit' button. 2. Verify success toast appears with text 'Saved'.

Must contain at least one action and one expected result. Reject if only actions or only results are present.

[APPLICATION_CONTEXT]

Description of the application type, UI framework, and relevant technology stack

React SPA with Material UI components. Toast notifications use notistack library.

Must include UI framework name. If framework is unknown, set to 'Unknown' and flag for selector strategy review.

[AUTOMATION_FRAMEWORK]

Target test automation framework for assertion syntax generation

Playwright

Must be one of: Playwright, Selenium, Cypress, WebDriverIO, Puppeteer. Reject unsupported frameworks.

[ASSERTION_STYLE]

Preferred assertion library and matcher style

expect-style with soft assertions enabled

Must specify library (expect, assert, should) and whether soft assertions are allowed. Default to expect-style if not provided.

[TOLERANCE_RULES]

Numeric and timing tolerance boundaries for assertions

Date comparisons: ±1 second. Pixel dimensions: ±2px. Text match: exact.

Must define tolerance per data type present in expected results. Missing tolerance for numeric assertions triggers a pre-flight warning.

[NEGATIVE_ASSERTION_SCOPE]

Instructions for when to include negative assertions

Include negative assertions for elements that must NOT appear after success actions.

Must be one of: none, success-paths-only, all-paths, or a custom rule. If custom, must include at least one concrete example.

[SELECTOR_MAP]

Known stable selectors for elements referenced in test steps

Submit button: data-testid='submit-btn'. Success toast: .notistack-Snackbar[role='alert'].

Each element in TEST_STEPS must have at least one selector. Missing selectors trigger a selector generation fallback with brittleness warning.

[FLAKY_PATTERNS]

Known flaky behaviors or timing issues in the application

Toast animation takes 300ms. Button disabled for 200ms after click during debounce.

If empty, add a note that assertions assume instantaneous UI updates. Non-empty values must include timing estimates or observable conditions.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the assertion generation prompt into a test automation pipeline with validation, retries, and human review gates.

The Automation-Ready Assertion Generation Prompt Template is designed to be integrated into a test authoring workflow, not used as a one-off chat interaction. In a production harness, this prompt typically sits between a manual test case parser and a script generation engine. The input to the prompt is a structured extraction of the 'Expected Result' field from a test management system (e.g., TestRail, Xray, or Azure DevOps), along with the UI element context and the automation framework target. The output—a JSON array of assertion objects—is then consumed by a downstream script assembler that maps each assertion to framework-specific code (e.g., expect(locator).toHaveText() in Playwright or assertThat(element).containsText() in Selenium). The harness should never directly execute model-generated assertions without validation, as a hallucinated matcher or incorrect selector can silently pass a test or cause a flaky failure that erodes trust in the automation suite.

A robust implementation wraps the LLM call in a validation layer that checks three things before the assertion reaches the script. First, schema conformance: the output must match the expected JSON structure with required fields like assertion_type, matcher, target_value, tolerance, and selector_context. A JSON Schema validator should reject any response missing these fields or containing unknown assertion types. Second, selector existence: if the prompt output references a data-testid or CSS selector, the harness should verify that selector exists in the page object model or a live DOM snapshot before generating code. Third, assertion logic review: for high-risk test areas (e.g., payment flows, authentication, data integrity checks), the harness should route the generated assertions to a human reviewer queue. The review UI should display the original manual expected result, the model's assertion chain, and a diff against any previously approved assertions for the same test case. This review step catches over-assertion (checking ten things when the manual test only specified two) and under-assertion (missing a critical side-effect like a database write or an audit log entry).

For retry and error handling, the harness should implement a two-stage recovery pattern. If the model output fails schema validation, the harness should retry the prompt once with the validation error appended as a [CONSTRAINTS] update, instructing the model to fix the specific structural issue. If the retry also fails, the harness should log the failure, flag the test case for manual assertion authoring, and not block the overall pipeline. For selector verification failures, the harness should invoke a fallback prompt that requests alternative selectors using the same [CONTEXT] block, then re-validate. Model choice matters here: a faster, cheaper model (e.g., Claude Haiku or GPT-4o-mini) is sufficient for straightforward assertions on stable UIs, but complex asynchronous flows or shadow DOM interactions benefit from a more capable model with stronger instruction-following. The harness should log every assertion generation attempt—including the prompt version, model, input context, raw output, validation result, and reviewer decision—so that assertion quality trends can be analyzed over time and flaky assertion patterns can be traced back to specific prompt behaviors.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required structure, types, and validation rules for the assertion chain output. Use this contract to parse, validate, and integrate the generated assertions into your test harness.

Field or ElementType or FormatRequiredValidation Rule

assertions

Array of Assertion Objects

Array length >= 1. Reject if empty.

assertions[].id

String (kebab-case)

Matches pattern: ^assertion-[a-z0-9-]+$. Must be unique within the array.

assertions[].description

String (plain text)

Length between 10 and 200 characters. Must not contain unresolved placeholders.

assertions[].matcher

Enum String

Must be one of: 'equals', 'contains', 'matchesPattern', 'isVisible', 'isEnabled', 'hasLength', 'isWithinRange', 'isNull', 'isNotNull'.

assertions[].target

String (selector or variable)

If starts with 'var:', must reference a key in the top-level 'variables' object. Otherwise, must be a valid CSS or data-testid selector.

assertions[].expected

String, Number, Boolean, or null

Type must be compatible with the specified 'matcher'. Use null only with 'isNull' or 'isNotNull' matchers.

assertions[].tolerance

Number or null

Required only when matcher is 'isWithinRange'. Must be a positive number. Reject if present for non-range matchers.

assertions[].negativeAssertion

Boolean

Defaults to false. If true, the assertion logic must be inverted. Reject if used with 'isNull' or 'isNotNull'.

assertions[].orderDependency

String or null

If set, must reference a preceding assertion 'id'. Reject if it references its own id or a non-existent id, creating a circular dependency.

variables

Object (key-value pairs)

Keys must be valid JavaScript identifiers. Values must be strings or numbers. Reject if a 'var:' target in assertions does not have a corresponding key here.

PRACTICAL GUARDRAILS

Common Failure Modes

Assertion generation prompts fail in predictable ways. These are the most common failure modes when converting manual expected results into automation-ready assertions, with concrete guardrails to catch them before they reach CI.

01

Over-Assertion: Validating Implementation Details

What to watch: The prompt generates assertions against internal state, exact CSS class strings, or transient DOM attributes that change with every UI refactor. Tests break on cosmetic changes, not functional regressions. Guardrail: Add a constraint in the prompt template requiring assertions to target user-visible outcomes and data-testid attributes only. Include a review step that flags any assertion not tied to a user-facing behavior or explicit contract.

02

Under-Assertion: Missing Side-Effect Validation

What to watch: The prompt generates only a single happy-path assertion (e.g., 'element is visible') and ignores downstream side effects like database writes, API calls, toast messages, or sibling element updates. Bugs that corrupt state pass silently. Guardrail: Add a [SIDE_EFFECTS] placeholder in the prompt template that forces the model to list expected side effects before generating assertions. Validate that each side effect has at least one corresponding assertion in the output.

03

Assertion Ordering Dependencies

What to watch: The generated assertion chain assumes a strict sequential order where assertion B depends on assertion A's side effect completing synchronously. In async UIs, this produces flaky false negatives when the DOM hasn't settled. Guardrail: Include an explicit instruction in the prompt to wrap dependent assertions in wait-for-state blocks and to flag any assertion pair that has an ordering dependency. Review the output for assertions that lack independent stability gates.

04

Tolerance Mismatch: Exact Matches on Variable Data

What to watch: The prompt generates exact equality assertions on timestamps, generated IDs, floating-point calculations, or localized strings. Tests fail on millisecond differences or locale variations that are functionally irrelevant. Guardrail: Add a [TOLERANCE_RULES] section to the prompt specifying which data types require range matchers, regex patterns, or normalization before comparison. Validate that no exact match assertion targets a field known to vary across runs.

05

Missing Negative Assertions

What to watch: The prompt generates only positive assertions (confirming something exists) and omits negative assertions (confirming something does not exist). Error states, loading spinners that should have disappeared, and deleted records go unverified. Guardrail: Add a [NEGATIVE_ASSERTIONS] section to the prompt template requiring at least one negative check per test case—verifying that a previous state no longer exists or that an error element is absent. Review the output for test cases with zero negative assertions.

06

Selector Fragility in Generated Assertions

What to watch: The prompt generates assertions using brittle selectors—XPath indexes, nth-child locators, or deeply nested CSS paths—that break on minor DOM restructuring. The assertion logic is correct, but the locator strategy is not. Guardrail: Include a [SELECTOR_POLICY] constraint in the prompt that prioritizes data-testid, aria labels, and role-based locators. Add a post-generation validation step that flags any assertion using an XPath or nth-child selector for manual review.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of generated assertion chains before integrating them into an automation suite. Each criterion targets a specific failure mode common in auto-generated assertions.

CriterionPass StandardFailure SignalTest Method

Assertion Specificity

Each assertion targets a single, explicit property of the expected result (e.g., text content, element count, CSS class, input value).

Assertion uses a generic 'is visible' or 'exists' check when a more specific property is verifiable.

Manual review: check if the assertion can pass while the application is in a wrong state.

Negative Assertion Coverage

At least one negative assertion is present to confirm a previous state, loading indicator, or error message is no longer visible.

Only positive assertions are generated, missing checks for the absence of transient states.

Parse script for .not. or equivalent negation matchers; flag if count is zero for stateful workflows.

Tolerance and Range Handling

Numeric or datetime assertions use explicit tolerance ranges (e.g., toBeCloseTo) instead of exact equality.

Assertion uses toEqual for a timestamp or a calculated value subject to minor rendering delays.

Lint check: scan for exact matchers on dynamic values; verify a tolerance or range matcher is used.

Selector Independence

Assertions are attached to resilient locators (data-testid, role, or text) that are distinct from the action selectors.

Assertion reuses a brittle CSS path or an index-based selector that is tightly coupled to the interaction step.

Static analysis: verify assertion locators are not identical to the preceding action locator without a fallback strategy.

Over-Assertion Prevention

The assertion chain verifies the critical outcome without asserting on every intermediate UI element.

The script asserts on every element in a container, including decorative icons or layout divs, causing false failures on minor UI updates.

Count assertions per logical step; flag if more than 3 assertions exist for a single user-visible outcome.

Ordering Dependency Check

Assertions are ordered logically but do not depend on a previous assertion's side effect to pass.

A later assertion implicitly relies on a prior expect to have scrolled an element into view or closed a modal.

Reorder assertions in a dry-run script; flag if reordering causes a false negative.

Async Maturity

All assertions are wrapped in explicit wait conditions (waitFor, should) with a timeout, not a fixed sleep.

Assertion is preceded by cy.wait(5000) or page.waitForTimeout(5000) without a condition.

Scan for static wait calls immediately before an assertion; flag as a flakiness risk.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single assertion target and a relaxed output schema. Focus on getting correct matchers and tolerance ranges for one assertion at a time. Remove the negative-assertion requirement and the ordering-dependency check to reduce complexity during early exploration.

Prompt modification

code
Generate a single automation-ready assertion for [EXPECTED_RESULT] in [TEST_CONTEXT].
Return JSON with: assertion, matcher, target_value, tolerance.

Watch for

  • Overly specific matchers that break on minor DOM changes
  • Missing tolerance ranges causing false positives on timing-dependent values
  • Assertions that pass in isolation but fail when chained
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.