DEV Community

Jonathan Hall
Jonathan Hall

Posted on • Originally published at jhall.io on

 

The importance of seeing red

Today I was working on a small REST service for a client. As I follow Test-Driven Development, the first thing I wanted to do when adding a new endpoint was add a function to test it. Of course I already have several test functions, so I copied one to modify for my new endpoint.

I renamed the test function, and deleted all the specific test cases. Then I copied the first test case from another endpoint into the new endpoint. It was just a test to ensure that I’d get a 415 Unsupported Media Type response if I sent a non-JSON payload.

I also copied the content-type check logic from another function into the new one, then ran the test. It passed. Obviously. So I went on to the next step.

I added a new test, this time to return a 400 Bad Request if I sent invalid JSON to the endpoint.

And I ran the test… and it passed.

Wait, what?

I hadn’t added yet told the new endpoint to parse JSON. What’s going on?


It turns out I had cheated a bit above. When I wrote my first test case, I didn’t actually validate that it failed before I added the code to make it pass. So when it did pass, I wasn’t surprised… even though it was a completely invalid test.

You see, I had forgotten to update the copy-pasted test code to call the new endpoint. It was still calling the old endpoint, which also had a content-type check. And it also did JSON parsing.

This isn’t the only time I’ve tried to take a TDD shortcut. These shortcuts always bite me in the rear end.

There’s a reason for the “Red - Green - Refactor” cycle of TDD. Every one of those steps is there for a reason. Skipping Red invalidates the TDD cycle!


If you enjoyed this message, subscribe to The Daily Commit to get future messages to your inbox.

Top comments (0)

An Animated Guide to Node.js Event Loop

>> Check out this classic DEV post <<