Knowledge card L2 · Context engineering informational

Refactor in Cursor With the Tests in View

What it is

Refactoring in Cursor with the relevant tests included in context, so the model changes structure while the tests hold behaviour fixed — and you can confirm nothing broke after each step.

green before and afterTests greenRefactorTests green
Keep the tests in context so Cursor refactors without drifting.

Why it works

A refactor must preserve behaviour. Keeping the tests in view gives Cursor a concrete definition of 'still correct' to refactor against, and gives you an instant check. Without them, 'refactor' quietly becomes 'rewrite', and regressions slip in unnoticed.

When to use it

Improving existing code you'll keep — deduplication, clearer names, breaking up a long function — where tests exist or can be added first.

When not to use it

When you actually intend to change behaviour; that's not a refactor and shouldn't be framed as one.

Prompt

Refactor <target> for <goal: readability / dedupe / smaller functions>. The relevant tests are in <test file> and must keep passing unchanged. Make the smallest structural change that achieves the goal, then tell me which tests to run.

Example

Cursor extracts three helpers from a tangled service, leaves the test file untouched, and the suite stays green — a structural win with proof it changed nothing observable.

Advanced version

If no tests exist, ask Cursor to write characterization tests that capture current behaviour first, then refactor against them. It's the same safety net Claude users get from named, behaviour-preserving steps.

Common mistakes

  • Refactoring without tests and calling the result 'behaviour-preserving' on faith.
  • Letting Cursor bundle a behaviour change into the refactor diff.
  • Making one giant refactor instead of small steps you can verify along the way.

Related