Describe “why” you are testing, not “what“
There are three basic techniques that you can apply to make your RSpec tests more readable and understandable to your co-workers:
- Use meaningful variable names.
- Write all the preconditions inside a
context
block - 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 year1 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:
- Use meaningful variable names. We intend
post_a
to be the most popular post andpost_b
to be any other post, so we rename the variables topopular
andanother
makes your intentions clear. - Move all the preconditions (such as creating test posts) inside a
context
block, rather than stuffing them inside theit
block. - 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 views1 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.