Refactor away duplication in your RSpec tests using the Parameterized Test Method
What do you do when you need to run the same test multiple times, but with different parameters? If you copy and paste the test, you end up with a hard-to-read test file. You can’t easily tell how the tests differ from one another. Worse, when you need to change one, you need to change them all. Take the following simple test file:
There are a few ways we could reduce the duplication here. My favorite is to use a Parameterized Test Method.
Reducing duplication with a Parameterized Test Method
Parameterized Test Method is a fancy-sounding name for a simple idea: a method, that takes parameters, and generates a test. Here’s how you use it:
- Take one of the tests and wrap it in a method. Then call the method in place of the test.
- Extract the unique test data to method arguments, and pass them in via the method call.
- Replace the remaining tests with calls to the new test method.
I’ll walk you through the refactoring, step-by-step:
1. Wrap the first example in a method and call it
2. Extract the unique test data to method arguments
3. Replace the remaining tests with calls to the new test method
Why use the Parameterized Test Method
You might wonder why I didn’t just iterate over the expectation, or even over the entire it block. There are a few reasons:
- It’s more readable – I don’t like to use iteration in my tests, I find it complex and less readable when setting up tests.
- Documentation – you get the exact same documentation format as before, with one line of documentation per example.
- Test failures are easier to understand – when a test fails, you know the exact test and line number that it failed on.
The next time you find yourself writing the same test over and over again, try refactoring the duplication away using a parameterized test method!