Lesson 982 of 1455
Asking ChatGPT to Write the Tests Before the Function
Generating tests with AI before the function makes the AI's actual code much easier to trust.
Builders · AI-Assisted Coding · ~4 min read
The big idea
If you ask ChatGPT 'write me a function that does X' you get code you have to trust. If you first ask 'write me 5 tests for a function that does X' and then 'now write the function to pass these tests' — you can run the tests and *see* it works. Same AI, way more trustworthy.
Some examples
- You ask Claude for tests for a 'parse a date string' function — the tests reveal you never decided about empty strings.
- ChatGPT writes tests for a leap-year checker that catch year 1900 (not a leap year, despite divisible by 4).
- Cursor writes tests for a username validator that include emoji — you decide your policy on the spot.
- Copilot tests a sort function with already-sorted, reverse-sorted, and one-element arrays — pro-grade coverage you'd skip alone.
Try it!
Pick a tiny function (max 10 lines) you need this week. Ask an AI for 5 tests first. Read them, fix any wrong ones, then ask for the function. Run the tests.
Key terms in this lesson
End-of-lesson quiz
Check what stuck
8 questions · Score saves to your progress.
Lesson help
Questions are best handled with a grown-up here.
For this age range, Tendril keeps freeform AI chat paused until parent/guardian consent and child-safe moderation are fully verified. Use the quiz, notes, and related lessons below, or ask a parent, guardian, teacher, or librarian to work through the question with you.
Progress saved locally in this browser. Sign in to sync across devices.
Related lessons
Keep going
Builders · 35 min
Tests as Prompts — an Unexpected Superpower
Writing a test first is not just good engineering. It is the clearest possible prompt for an AI. Let's use tests to make AI code reliable.
Creators · 11 min
Writing Failing Tests First, Then Asking AI to Implement
Drive AI implementation with tests you write yourself.
Builders · 35 min
When AI Writes Buggy Code — How to Read It Critically
The AI will hand you code that looks right but isn't. Here are the most common bugs and the habits that catch them before they bite.
