How to Guide AI with Rules and Tests

by SkillAiNest

Building great software isn’t about perfect pointers, it’s about a disciplined process. In this guide, I’ll share my workflow for delivering secure code: defining clear goals, mapping edge cases, and building incrementally with runnable tests.

Using a Node.js shopping cart example, I’ll show why server-side validation and test-driven development beats “one-shot” AI output every time. Let’s consider how to make AI your most trusted companion.

Some background

Last week I did something that felt amazing for about five seconds. I opened an AI tool, typed in a phrase, and it generated an entire shopping cart module for an e-commerce app. Lots of files, lots of code, even folders and patterns. It looked professional.

And then I realized something: the problem wasn’t “how fast the AI ​​wrote the code.” The problem was “How do I know this code is correct?”

Here’s the truth: A big pile of code you didn’t write isn’t a shortcut. For most developers, this is actually extra work. You have to read it, understand it, and still catch the hidden mistakes.

So today I’m not going to give you another “AI is coming” talk. Instead, I’ll show you a simple loop that any developer – beginner, intermediate, or senior – can follow to get better results from AI step by step, without any pitfalls. And I’ll show it with a real example that you can run in a file.

Here’s what we’ll cover:

5 seconds high (and the real problem)

Many people misunderstand AI coding. They think the main job is to type code. But the real task is to think clearly. Typing is now cheaper. Thinking is expensive.

When AI creates a “perfect-looking” module in one shot, the original work doesn’t disappear. It goes down to:

  • You still need to understand what created it.

  • You still need to verify that it matches your rules.

  • You still need to catch errors that hide within “nice looking code”.

If you can’t verify it, you don’t own it. And if you don’t own it, you can’t send it securely.

Tip: Treat AI output like code from a stranger on the Internet: useful, but unreliable until proven.

The Golden Rule: Never trust consumer prices.

I started just like a beginner would. I opened AI and wrote a vague hint:

Design and develop an e-commerce shopping cart module for me.

The AI ​​responded with a large output. It looked clear. If you’re new, you might think:

Wow, that solved it.

But then I asked myself:

What’s the easiest way to go wrong in real life?

And the answer is also simple: “money can be stolen”. Because there’s a golden rule of shopping carts: never trust the prices the user comes up with.

If the browser sends you: “T-shirt price is \(1” and you accept it, then someone might pay \)1 for a $20 product. And when the AI ​​quickly generates a large module, this type of error can easily be hidden within “nice-looking code”.

Warning: Any system that accepts client-sent prices essentially invites price manipulation.

Mindset Shift: Stop asking for the whole app.

So instead of accepting the massive AI output, I changed my approach. I said:

I wouldn’t ask AI to build an entire app. I’ll break the big thing down into smaller parts, and I’ll guide the AI ​​like a real engineer.

This is the first mindset shift. In the AI ​​age, your value is not how fast you type. Your value is based on how well you can do three things:

  • Clearly define the problem

  • Break it into small pieces

  • Prove the result

Large systems are built from small precision pieces. This is not “quick engineering”. This is engineering.

AI Coding Loop (7 Step Workflow)

This is the loop I use. This is plain English. You can copy it and use it for any project:

  • Write the purpose in one sentence.

  • Write the rules (what must be true)

  • Write two examples (Input → Output)

  • Write two bad situations (weird situations).

  • Ask the AI ​​for a small piece, not the whole thing.

  • Ask for tests, then run them.

  • If something fails, immediately improve and do it again

That’s it. That’s the loop. Here it is in visual form:

AI coding loop workflow

Tip: The loop is skill. Tools will change. The loop will still work.

Apply Loop: Server-Side Cart Total Calculator

Now let’s apply this to the shopping cart example. Instead of “make me a cart module” I wrote a small requirement note:

We need a cart total calculator on the server. User sends. productId And quantity. We must ignore someone. price from the user. We should use our product list. We must handle unknown products and false. quantity. We have to account. subtotal, discount, taxand the finale total. We must round the money properly. We should have tests.

This is not a large or complex requirements specification – just a clear and concise note.

And then I asked the AI ​​just one small piece:

  • Not the UI.

  • Not a database.

  • Not the whole architecture.

  • Just a function with a test

Because the fastest way to build something real is to prove it one brick at a time. We have written down everything we have discussed in the note of need. It would also be great to create a visual representation of these ideas. With a note of the requirement, we can create a simple diagram or sketch for our reference. Thus, it can serve as a clean and well-documented requirement specification, which we can record in our project’s GitHub. README.md File

In the diagram below, we can place the browser on the left and the server on the right. The browser/user is an unreliable input source. User can send productId, qtyand even a fake pricebut the server should only treat productId And qty Any value sent as input and sent by the client should be ignored. The server then looks up the actual price from its trusted product catalog, validates the quantity, and calculates the total from the server-side data. This is the trust limit: values ​​come from the server, not the client.

Trust boundary and price tampering

Prompt (short piece, strong constraints)

This is the format of the prompt I used:

Create a single JavaScript file that I can run with Node.

Purpose:

Calculate the shopping cart total.

Principles:

  • Input items contain product id and quantity.

  • Do not rely on the value from user input.

  • Use my product catalog.

  • Quantity must be at least 1.

  • Discount percentage and tax percentage should not be negative.

  • Discount first, then tax.

  • Round the amount to 2 decimal places.

Examples:

  • 2 t-shirts (20 each) + 1 mug (12.50) => sub total 52.50

  • Discount 10%, tax 8% => discount first, then tax

Deliver:

A small change makes a big difference: “Rules + Examples + Tests”. The AI ​​still tries to help quickly, but now it has guardrails. And if it still makes a mistake, you can catch it, because you asked for proof.

Here is a visual representation of the “Cart Totals Pipeline” that covers all the use cases involved in the cart totals calculation process.

Cart Total Pipeline (discount then tax)

In the diagram, the total cart computation follows a fixed pipeline. First, validate the inputs (known as productIdcorrect qtynon-negative discount/tax). Next, the calculation subtotal From the trusted product catalog. Then apply the discount to get the discount amount. Next, calculate the tax on the discounted amount (not on the actual subtotal). Finally, round the values ​​correctly and return the result (subtotal, discount, taxand total). The key rule is the order: discount first, then tax.

An executable example file (with the wrong version on target)

Now here’s an example file that you can run right now. No setup. Node only. Create a file named cart.jspaste in the code below, and run. node cart.js.

It includes two versions:

// cart.js

// Run: node cart.js

const assert = require("node:assert/strict");

// Trusted product catalog (server-side truth)

const PRODUCTS = {
    tshirt: { name: "T-shirt", priceCents: 2000 }, // $20.00

    mug: { name: "Mug", priceCents: 1250 }, // $12.50

    book: { name: "Book", priceCents: 1599 }, // $15.99
};

function money(cents) {
    return (cents / 100).toFixed(2);
}

// WRONG: trusts user price

function cartTotal_WRONG(cartItems, discountPercent = 0, taxPercent = 0) {
    let subtotalCents = 0;

    for (const item of cartItems) {
        const priceCents = Math.round((item.price ?? 0) * 100); // user can cheat

        subtotalCents += priceCents * item.qty;
    }

    const discountCents = Math.round(subtotalCents * (discountPercent / 100));

    const afterDiscount = subtotalCents - discountCents;

    const taxCents = Math.round(afterDiscount * (taxPercent / 100));

    const totalCents = afterDiscount + taxCents;

    return totalCents;
}

// Correct: uses trusted catalog + checks

function cartTotal(cartItems, discountPercent = 0, taxPercent = 0) {
    if (!Array.isArray(cartItems))
        throw new Error("cartItems must be an array");

    if (typeof discountPercent !== "number" || discountPercent < 0)
        throw new Error("discountPercent must be non-negative");

    if (typeof taxPercent !== "number" || taxPercent < 0)
        throw new Error("taxPercent must be non-negative");

    let subtotalCents = 0;

    for (const item of cartItems) {
        const { productId, qty } = item || {};

        if (typeof productId !== "string" || !PRODUCTS(productId)) {
            throw new Error("Unknown productId: " + productId);
        }

        if (typeof qty !== "number" || qty < 1) {
            throw new Error("qty must be at least 1");
        }

        subtotalCents += PRODUCTS(productId).priceCents * qty;
    }

    const discountCents = Math.round(subtotalCents * (discountPercent / 100));

    let afterDiscountCents = subtotalCents - discountCents;

    if (afterDiscountCents < 0) afterDiscountCents = 0;

    const taxCents = Math.round(afterDiscountCents * (taxPercent / 100));

    const totalCents = afterDiscountCents + taxCents;

    return { subtotalCents, discountCents, taxCents, totalCents };
}

function runTests() {
    // Normal example

    const cart = (
        { productId: "tshirt", qty: 2 },

        { productId: "mug", qty: 1 },
    );

    const r = cartTotal(cart, 10, 8);

    assert.equal(r.subtotalCents, 5250); // 52.50

    assert.equal(r.discountCents, 525); // 10% of 52.50

    assert.equal(r.taxCents, 378); // 8% of 47.25

    assert.equal(r.totalCents, 5103); // 51.03

    // Attack example: user tries to cheat with price = 1

    const attackerCart = (
        { productId: "tshirt", qty: 2, price: 1 },

        { productId: "mug", qty: 1, price: 1 },
    );

    const wrong = cartTotal_WRONG(attackerCart, 0, 0);

    assert.equal(money(wrong), "3.00"); // totally wrong in real life

    const safe = cartTotal(attackerCart, 0, 0);

    assert.equal(money(safe.totalCents), "52.50"); // correct, ignores user price

    // Edge cases

    assert.throws(() => cartTotal(({ productId: "unknown", qty: 1 }), 0, 0));

    assert.throws(() => cartTotal(({ productId: "tshirt", qty: 0 }), 0, 0));

    assert.throws(() => cartTotal(cart, -1, 0));

    assert.throws(() => cartTotal(cart, 0, -1));
}

runTests();

console.log("All tests passed.");

const example = cartTotal(
    (
        { productId: "tshirt", qty: 1 },

        { productId: "book", qty: 2 },
    ),

    15,

    5,
);

console.log("Example subtotal:", money(example.subtotalCents));

console.log("Example discount:", money(example.discountCents));

console.log("Example tax:", money(example.taxCents));

console.log("Example total:", money(example.totalCents));

In this code, we didn’t do any magic tricks. We did some engineering:

  • We took a big problem and broke it down into smaller pieces.

  • We wrote the rules so the AI ​​couldn’t guess.

  • We wrote examples so the AI ​​could understand.

  • We asked for a test so we could prove it

  • We ran tests so we could trust it

This is a loop that you can reuse for any project.

How to Use the Falling Test as a Flashlight

This is the part that many developers skip. They ask for code, but not proof. When you run a test, one of two things happens:

  • Test Pass: Great, you’ve gained confidence.

  • Tests Failed: Better yet, you get clarification.

A failed test is a flashlight. It shows you exactly where your thinking (or your prompt) needs improvement. Instead of “AI is wrong” you get a real question:

Which rule was unclear, missing, or inconsistent?

Then you adjust:

  • Add a hard rule

  • Add an example that clears up the ambiguity.

  • Add an edge case that forces the correct behavior

  • Regenerate only a small fragment, not the entire codebase.

Copy Paste Prompt Template

Here’s a copy-paste prompt template you can reuse today (see image below):

Copy Paste Prompt Template


Build ONE small piece, not the full app.

Goal:

(One sentence)

Rules:

(3 to 7 bullets)

Examples:

(2 examples: input -> output)

Edge cases:

(2 cases that can break it)

Deliver:

- one runnable file

- include tests using Node assert

- print one example output

Then ask:

Before giving code, list the possible mistakes and confirm the rules.

That last line is powerful. This forces AI to think about failure before writing code.

A Quiet Hype Check: Why Fundamentals Matter Now

A lot of content online makes it sound like this: “AI codes now, so you don’t have to learn coding.” That idea is a trap. Because yes, AI can type code. But AI cannot replace your responsibilities as a developer and engineer.

If you send a damaged basket, you could lose money. If you send unsecured code, you might get hacked. If you ship unreliable software, customers leave. And in real life, no one will accept the excuse: “AI wrote it.”

In the AI ​​age, learning to code is no less important. It’s more important, just in a different way. The goal is not to become a fast typist. The goal is to become a strong thinker.

The basics are more important than ever:

  • How data flows through the system.

  • How to break big problems into smaller parts.

  • How to write clear rules and requirements

  • Method of testing and verification

  • How to view edge cases

  • A way of thinking about security

  • How to understand the tools you use, not just copy answers.

Average software will be everywhere. It will be cheap. It will be copied. It will be easy to make. So the only software that matters will be software that is truly valuable: secure, reliable, high quality, and built with real understanding.

This is good news for serious learners. Because the best engineers will become more valuable, not less.

A simple exercise (do it once and you’ll feel the mastery)

Add another rule to the cart, such as:

  • Quantity cannot exceed 10

  • Write the test first. Then ask the AI ​​to update the function. Run the test.

  • That’s how you train true AI skills: not pointing, but guiding and confirming.

  • Let AI type the code.

  • Do it thoughtfully.

  • You vandalize.

  • You prove it.

Recap

  • Don’t ask AI to build an entire app.

  • Break the problem into smaller pieces.

  • Write rules, examples and edge cases so that the AI ​​doesn’t have to guess.

  • Always ask for tests and run them.

  • Think of failed tests as a flashlight.

  • Repeat the loop until you trust what you send.

Now that’s the game. And if you play it well, you’re not behind, you’re ahead.

Last words

If you find the information here valuable, feel free to share it with others who might benefit from it.

I would really appreciate your thoughts – mention me on X. @sumit_analyzen Or on Facebook @sumit.analyzen, Check out my coding tutorialsor just Connect with me on LinkedIn..

You can also check out my official website. sumitsaha.me For details about me.

You may also like

Leave a Comment

At Skillainest, we believe the future belongs to those who embrace AI, upgrade their skills, and stay ahead of the curve.

Get latest news

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

@2025 Skillainest.Designed and Developed by Pro