After a year using RSpec, I’m happy to share “(My) RSpec Best Practices and Tips”. Let’s make your specs easier to maintain, less verbose, more structured and covering more cases!
Use shortcuts specify {}, it {} and subject {}
You think RSpec is verbose? In case your code doesn’t need any description, use a specify block!
1 2 3 |
|
can be replaced with
1
|
|
RSpec will generate a nice description text for you when running this expectation. Even better, you can use the it block!
1 2 3 4 |
|
In case the subject is the not the class described, just set it with the subject method:
1 2 |
|
Start context with ‘when’/‘with’ and methods description with ‘#’
Have you ever get a failed test with an incomprehensible error message like:
1
|
|
Start your contexts with when and get nice messages like:
1
|
|
Use RSpec matchers to get meaningful messages
In case of failure
1
|
|
displays:
1 2 3 |
|
While
1
|
|
displays:
1 2 |
|
Nice eh?
Only one expectation per it block
I often see specs where it blocks contain several expectations. This makes your tests harder to read and maintain.
So instead of that…
1 2 3 4 5 6 7 8 |
|
… do this:
1 2 3 4 5 6 7 8 9 10 11 |
|
(Over)use describe and context
Big specs can be a joy to play with as long as they are ordered and DRY. Use nested describe and context blocks as much as you can, each level adding its own specificity in the before block.
To check your specs are well organized, run them in ‘nested’ mode (spec spec/my_spec.rb -cf nested
).
Using before(:each)
in each context and describe blocks will help you set up the environment without repeating yourself. It also enables you to use it {} blocks.
Bad:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
Good:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
Test Valid, Edge and Invalid cases
This is called Boundary value analysis, it’s simple and it will help you to cover the most important cases. Just split-up method’s input or object’s attributes into valid and invalid partitions and test both of them and there boundaries. A method specification might look like that:
1 2 3 4 5 6 7 8 9 10 |
|
I hope this will help you improve your specs. Let me know if I missed anything! :)
You could also be interested in (My) Cucumber best practices and tips or rspec-set a little gem that helps you speeding up your model specs.