Describe “why” you are testing, not “what“

Claudio B.
Clutter Developers
Published in
2 min readOct 17, 2018

There are three basic techniques that you can apply to make your RSpec tests more readable and understandable to your co-workers:

  1. Use meaningful variable names.
  2. Write all the preconditions inside a context block
  3. Provide an explicit description of each expectation

Let me show you with an example what this means.

Say you have a blog powered by Ruby on Rails and you want to know which posts were the most popular in 2017. A quick method can look like this:

For each post, take all the online posts published in the same year, rank them by number of views, and assign a yearly rank to each one: #1, #2, and so on.

Here is a first pass at writing tests in RSpec to validate that the code works:

$ rspec --format documentation
Post#yearly_rank
given two posts published the same year
1 example, 0 failures

Although the test passes, it’s unclear why. Is the rank of post_a lower because it was created first? Or because of the view count? It’s not easy to tell.

To improve the readability of the tests, follow these three techniques:

  1. Use meaningful variable names. We intend post_a to be the most popular post and post_b to be any other post, so we rename the variables to popular and another makes your intentions clear.
  2. Move all the preconditions (such as creating test posts) inside a context block, rather than stuffing them inside the it block.
  3. Provide an explicit description of the expectations.

The result looks more readable both in the code and in its execution:

$ rspec --format documentation
Post#yearly_rank
given two posts published the same year
ranks them from most to least views
1 example, 0 failures

With this structure in place, adding new tests to the file is straightforward. Here is what a new context would look like to check that the method never raise an error, not even when called on deleted posts:

$ rspec --format documentation
Post#yearly_rank
given two posts published the same year
ranks them from most to least views
given a deleted post
should not raise Exception (FAILED - 1)
2 examples, 1 failure

Looks like we found an error, and the output is pretty clear at explaining what is the condition that we need to fix. Can you edit the code and make it pass?

If you enjoyed this article, please share with your friends. If you are looking to join an amazing team of Ruby developers, check our current openings at Clutter.

--

--