Test the sad path

August 13, 2024

Key takeaway: Before calling a feature done, list every path through it and give each one a test or a reason to delete it.

The bugs that reach production live in the branches your tests never ran. Test the sad path: the other side of the conditional, the default case, and the error handler.

def shipping_cost_cents(order)
  order.total_cents >= 5_000 ? 0 : 799
end

One test with a $100 order runs this line, and line coverage marks it green. The $7.99 side has never executed. Turn on branch coverage, which counts each side separately. SimpleCov does it with enable_coverage :branch. Then test the boundary. An order of exactly $50.00 tells you whether the code says >= or >.

Now take a case with two statuses:

case payment.status
when "succeeded" then fulfill(order)
when "failed"    then notify_customer(order)
end

The payment provider adds "disputed". This returns nil, nothing gets fulfilled, nobody gets notified, and no error shows up until a customer emails support. Write the default case even when you think it can’t happen, make it raise, and test that it raises. An exception on the first disputed payment beats a silent nil you find weeks later.

Error handling runs at the worst time, when something else already broke. Don’t leave it to production to exercise it. Make the dependency fail in a test, with a timeout, a 500, an empty body, or a record deleted between the read and the write. If you didn’t write handling for one of those, the branch still exists, and you shipped the language’s default behavior.

Every branch is a test you owe, and nested conditionals multiply them. That’s one argument for flat code. If a branch is awkward to test, ask whether anything reaches it. Deleting it is often cheaper than covering it.