[rspec-users] Eliminating duplication from tests

Phlip phlip2005 at gmail.com
Fri Apr 10 08:38:35 EDT 2009


Brandon Olivares wrote:

> So is this necessarily bad? I've heard it's not always good to reduce
> duplication in tests, but it just seems much preferable than copy/paste.

Refactor production code (while passing the tests after each edit) to make it as 
DRY as possible. This _typically_ means duplicate the behavior you need to 
change, make the new method pass the new test, and only then merge the new 
behavior back in with the old code. Merge following the rule "refactor low 
hanging fruit". Don't jam two big methods back together; use Extract Method 
Refactor on the smallest common lines within them, until only the differences 
are left.

This implies clone-and-modify is part of the process. In test code, the best way 
to write a new test is clone the best example and change the assertions in the 
clone. (Ripping all the old assertions out, and changing the sample data on 
principle, are both best practices here.)

Refactor test code with two further constraints: Unlike production code, each 
test case should tell a little story. And squeezing that last bit of duplication 
out of the test cases is not likely to improve the tests' designs.

New tests should always be easy to write. If you get that, then the refactoring 
is working.



More information about the rspec-users mailing list