Today I was working on a project and made a one-line change that updated a single value within an API response.
Unexpectedly, it caused a test to fail. The API response returned a 500 status code instead of the expected 201 code.
I reverted the change locally and ensured that the test passed again, so I knew it was causing the failure.
Fixing the failure
The change was removing a hard-coded part of a URL to a dynamic one, using Drupal's Settings class.
I was retrieving a value from it, but as there was no value being set within the test, it was returning a null value and causing the 500 error code.
How does the Settings class work?
To fix the test failure, I needed to learn how to set a Settings value within a test.
To do this, I looked for and found the test for the Settings class itself. I saw how it was being set there, did the same in my test, fixed the failure and got my test passing again.
Tests are living documentation
As well as verifying things work when they are written, tests also act as long-term documentation. They can be run at any point to ensure that they still pass and are a reference to other developers on how the code should work.
Rather than a Confluence page, a README file or code comments which can become out of date, if a test becomes outdated, it will fail and make developers aware, as well as break any CI pipeline that it runs in.
By writing tests, you're ensuring that your code works as expected and documenting it at the same time.
- Oliver
Was this interesting?
About me
I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.