Use RSpec to test for more than just correctness

RSpec is typically used to test the correctness of our Ruby on Rails code, but did you know that we can use it to maintain the readability of our application’s configuration files?

Suppose we have a YAML file containing an alphabetized list of all of our application’s feature flags. It might look something like so:

While our application may function correctly if feature_flags.yml stores these flags in a random order, we usually prefer an alphabetized list of flags for the sake of readability. One approach is to leave a comment for the next developer who modifies this file:

This is adequate, and hopefully our code review process would prevent a developer from adding an adding an unalphabetized flag. But, through the power of RSpec, we can actually enforce this alphabetization (rather than just suggest it with a comment!) Consider the following RSpec test that we could add to our codebase:

If another developer tried to submit a pull request containing a non-alphabetized YAML property, this test would fail the next time our tests ran in our continuous integration system. This allows us to preserve the alphabetization of this configuration file – even if the next developer to add a feature flag doesn’t read our comment!

Note that this test executes none of our actual Ruby application code – this is purely testing properties of our YAML file, and doesn’t deal with any of our classes that we expect to see at runtime.

Let’s look at another example! Suppose we have a configuration file that stores a list of UI elements to display, and we associate a position integer with each element (think of something akin to the acts_as_list library):

Again, our application may run correctly if our YAML file stores these elements in a random order, but we (and other developers) will have a far easier time understanding this file if these items are ordered by position. To keep these items ordered, we can add the following test:

If we try to add an element to this file that is out of order, this test will fail until we place it in the correct position.

It’s easy to think of a linter as our sole tool to ensure code quality, and that RSpec’s only role is to test correctness of our application – since this is usually the case! But, in occasional cases like this, we can use RSpec for more than just correctness, and leverage it to ensure high code quality in our codebase.

Start your journey towards writing better software, and watch this space for new content.