Contract-Driven TDD with AI: Building a Strict Gatekeeper for Your Team

    This article explores how Contract-Driven TDD helps teams handle the risks of AI-generated code by making machine-readable specifications the single source of truth. It breaks down the three-layer structure of specification, tests, and implementation, then walks through writing a contract, using role-based prompts to generate tests from it, extending coverage to integration tests, and enforcing the gatekeeper in CI pipelines. Readers will learn how to reduce review burden, catch specification gaps, and balance fast generation with stable delivery.

    1. The Starting Point: Why Teams Get More Anxious After AI Generates Code

    When intelligent coding tools can produce a complete feature module in minutes, the team’s real pain point shifts. We used to worry about not finishing; now we worry about writing the wrong thing, missing something, or producing code nobody dares to change. The faster the generation, the higher the risk of unverified code reaching the main branch.

    Traditional code review is a serial bottleneck: one person can carefully read only so much code per day, while the volume of generated code has no limit. Relying on manual review alone is essentially using linear resources to fight exponential output, and the result is review that becomes a formality.

    Contract-Driven TDD offers a different path: move the definition of “what counts as correct” out of people’s heads and into machine-readable specification files, make the specification the single source of truth, make tests the executable projection of the specification, and make the pipeline an uncompromising gatekeeper. AI’s role here is “translator” and “gatekeeper,” not “decision-maker.”

    2. The Three-Layer Structure of Contract-Driven TDD

    To understand this method, you need to separate three layers whose change frequency and ownership are completely different.

    The first layer is the specification layer. It describes the interface’s inputs, outputs, error semantics, and boundary conditions, without caring about internal implementation. This layer is jointly reviewed and agreed upon by the team, and changes require explicit review because it is an external commitment.

    The second layer is the test layer. It is mechanically derived from the specification, including unit tests and integration tests. Tests should not introduce business assumptions beyond the specification; if you find you need to add assumptions, that means the specification itself has a gap and should be filled first.

    The third layer is the implementation layer. This is where AI-assisted generation is most efficient and also the most easily over-trusted part. The implementation can be rewritten, optimized, or replaced repeatedly as long as the specification stays unchanged.

    The key constraint of the three-layer structure is one-way dependency: implementation depends on tests, tests depend on the specification, and the specification depends on no specific implementation. Once this direction is broken, tests degrade into a “behavior snapshot of the implementation” and lose their gatekeeping ability.

    3. Step One Is Always Writing the Specification, Not the Code

    Take voucher redemption in an e-commerce system, an extremely common example. We need a machine-readable contract file, shown below (YAML style, illustrative):

    1. # voucher_spec.yaml (simplified illustration)
    2. contracts:
    3. RedeemVoucherAPI:
    4. endpoint: /voucher/redeem
    5. method: POST
    6. request:
    7. voucher_id: { type: string, required: true }
    8. order_id: { type: string, required: true }
    9. order_amount: { type: float, required: true, minimum: 0.01 }
    10. response:
    11. success:
    12. code: 200
    13. data: { deducted_amount: float }
    14. errors:
    15. - { code: 40401, message: "Voucher not found" }
    16. - { code: 40402, message: "Voucher already redeemed" }
    17. - { code: 40403, message: "Order amount below minimum requirement" }
    18. invariants:
    19. - Redemption must be idempotent: repeated requests with the same voucher_id return 40402, and the balance is not deducted twice
    20. - deducted_amount must not exceed order_amount, nor the voucher face value
    21. - Redemption and order status change must complete within the same transaction boundary

    This file is worth writing because it makes three often-overlooked things explicit: the one-to-one mapping of error codes to business semantics, the boundaries of numeric fields (minimum amount 0.01), and invariants (idempotency, deduction limits, transaction boundaries). Invariants are the most valuable part because they constrain properties that “must always hold for any implementation,” not just the return value of a single call.

    4. Step Two: Use Prompts to Translate the Specification into Tests

    When you hand the specification to an intelligent coding tool, the quality of the prompt directly determines the quality of the tests. A usable role-based prompt structure is as follows:

    1. # Role
    2. You are an extremely strict test engineer who believes in the contract spirit and accepts no business assumptions beyond the specification.
    3. # Task
    4. Based on the interface specification file I provide, generate test code using Python + Pytest.
    5. # Constraints
    6. 1. At least one case per error code, asserting code and message match exactly;
    7. 2. Generate a missing-field case for each required field, and boundary-value cases for constraints like minimum (0.01 / 0.009);
    8. 3. Generate a separate case for each invariant in invariants, especially idempotency and concurrency scenarios;
    9. 4. Interact only through public interfaces; depending on internal private methods is forbidden;
    10. 5. Use parameterization to reduce duplication; test names must self-explain the failure reason;
    11. 6. Do not guess uncertain semantics; mark them with # TODO: specification gap.
    12. # Output
    13. A directly runnable test file + a list of specification gaps.

    The last constraint is especially important. It makes the tool choose to expose problems when it encounters ambiguous parts of the specification, rather than fabricating a behavior and hard-coding an assertion. In practice, this “specification gap list” is often more valuable than the test code itself, because it directly points out where the team’s understanding is inconsistent.

    The generated result usually covers the following case matrix:

    • Happy path: voucher exists, amount meets the requirement, deducted amount is calculated correctly;
    • Error paths: voucher not found (40401), already redeemed (40402), amount below requirement (40403);
    • Boundaries and exceptions: amount of 0.01 and 0.009, voucher face value less than order amount, missing fields or wrong types;
    • Invariants: idempotency of repeated requests, only one success under concurrent redemption, voucher state not consumed after transaction rollback.

    5. Step Three: Move from Unit Tests to Integration Tests

    Unit tests verify logic branches, but the correctness of voucher redemption depends heavily on external collaborators: the order service, account balance, database transactions, and message notifications. These must be covered by integration tests.

    There are three key points for writing integration tests in a specification-driven way. First, abstract external dependencies into replaceable test doubles, using controllable in-memory implementations or containerized dependencies instead of real production systems. Second, add “collaboration contracts” to the specification, clarifying what event must be emitted after successful redemption and that no side effects may occur on failure. Third, declare a cleanup strategy before preparing data, ensuring cases are repeatable and do not pollute each other.

    Illustration:

    1. @pytest.mark.parametrize("amount,expected", [
    2. (0.01, 200),
    3. (0.009, 40403),
    4. ])
    5. def test_redeem_amount_boundary(api_client, seeded_voucher, amount, expected):
    6. resp = api_client.post("/voucher/redeem", json={
    7. "voucher_id": seeded_voucher.id,
    8. "order_id": "o-1001",
    9. "order_amount": amount,
    10. })
    11. assert resp.json()["code"] == expected
    12. def test_redeem_is_idempotent(api_client, seeded_voucher):
    13. payload = {"voucher_id": seeded_voucher.id,
    14. "order_id": "o-1001", "order_amount": 100.0}
    15. first = api_client.post("/voucher/redeem", json=payload)
    16. second = api_client.post("/voucher/redeem", json=payload)
    17. assert first.json()["code"] == 200
    18. assert second.json()["code"] == 40402
    19. assert seeded_voucher.reload().deducted_total == first.json()["data"]["deducted_amount"]

    6. Step Four: Put the Gatekeeper into the Pipeline, Not Just the Docs

    Writing tests only creates an asset; integrating them into the pipeline makes them a gate. Recommended mandatory rules include: specification file changes must be accompanied by test change review; coverage and case pass rate are hard conditions for merging; invariant cases are marked as non-skippable; failure blocks immediately, with no “merge first, fix later.”

    At the same time, avoid two anti-patterns. The first is coverage worship: generating many assertion-free call-type tests to hit a number, resulting in high coverage but no gatekeeping ability; during review, focus on assertion density rather than line coverage. The second is tests and implementation from the same source: if the implementation and tests come from the same generation task, they share the same misunderstanding; the specification must be confirmed by humans, and test assertions must be traceable to specification items.

    7. Adoption Benefits and Rollout Pace

    The benefits of this method are structural: the specification becomes a clear commitment between the team and external collaborators; tests become executable documentation, and newcomers understand business boundaries by reading tests; AI-generated implementations are constrained within a clear correctness framework, and the review burden shifts from “reading line by line” to “checking specification consistency”; regression risk drops significantly because invariants are always guarded.

    For rollout, proceed in three steps: first, pilot on a link with clear boundaries, and turn the specification template and prompts into team assets; then, connect the gate to continuous integration, observe the block rate and false-positive rate, and adjust thresholds; finally, replicate to more links while establishing a specification review mechanism to prevent contract decay. When the gatekeeper handles mechanical comparison by AI and semantic decisions by humans, the team truly gains the dual capability of “generating fast” and “delivering steadily.”