rSpec best practices
Most of rSpec best practices are found here:
Here are some I learned while working on algorithms.
- Use symbolic constants whenever possible.
When you decide to change the name of something or rename your class, you don’t want to hunt down every occurance of it. This happens way more often in specs when using bdd.
let is great for that purpose.
let(:one_array) do ['one'] end
- Use
subject
For the same reason above. You define it once, and use it through in your specs.
subject do list = described_class.new list << 'one' list end it 'returns size' do subject.size.should == 1 end
- Define
subjectexplicityly.
rSpec is smart enough to detect it most of the time from describe, but you should define it anyway. Makes for easier reading.
- Use
described_class
It refers to the argument passed in to describe. Again, same principle.
describe Algorithm::DoubleLinkedList do subject do described_class.new end end
- Use
contextto organize specs related to a method
For the above project, I had three contexts based on the size of the list:
- zero_nodes
- one_node
- multiple_nodes
But, I had to jump too much to find the related specs, so now they’re organized by methods instead. Now after adding/changing a method, I can just jump to the appropriate context and change the specs.
In the above project I probably reorganized the specs at least three times to make it easier to deal with the complexity. A good indicator about the health of your specs is how confident you feel changing something in the project. And also how much you dread having to work with the specs.