Be More GARY: Upping your RSpec game

Improve your test code by moving away from the DRY principle

Scott Matthewman
11 min readFeb 19, 2024

This article is based on a lightning talk given at LRUG’s February 2024 meetup.

In the Ruby community, the same acronyms have a tendency to pop up frequently. There’s MINASWAN (Matz Is Nice And So We Are Nice) and YAGNI (You Ain’t Gonna Need It), of course. But perhaps the one we encounter most is DRY, or Don’t Repeat Yourself.

“Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.”

http://wiki.c2.com/?DontRepeatYourself

And so we often find ourself talking about “DRYing” our code, avoiding repetitive code blocks and using that to drive our refactoring processes.

And that’s a good thing. Our executable code is where our system knowledge resides, so unnecessary duplication risks violating that “single representation” principle. We often talk about a “single source of truth” in terms of data, and that’s true for executable code too.

But what about tests?

It’s easy to fall into the same practice when writing tests, especially with RSpec. If the same lines appear in multiple tests, there’s a tendency to extract the repetition. RSpec gives us plenty of tools to do so, from let statements to before blocks, shared examples, conditional meta tagging and more.

--

--

Scott Matthewman

Scott is a software developer during the day and a theatre critic & director of an evening. Which is the worst superhero identity ever.