00:00:08.719
Hello everyone, I am Dan Sharp, a senior software architect and the founder of Grug. I've been coding for over 20 years and working with Ruby and Ruby on Rails for about 8 years. However, I've only been seriously focusing on testing for the past few years. Today, I want to talk about why we should 'dry up' our tests. As the saying goes, 'duplicated code makes DHH cry'. This talk will be brief, only lasting about 3 minutes, and I'll cover a few strategies for making your tests DRY, including using shared examples, shared contexts, helper methods, including modules, looping constructs, custom matchers, and some fancy Ruby tricks.
00:00:43.120
There are some quick rules of thumb when it comes to drying up your tests. First, don't try to dry things up too early. Wait for duplication to arise before trying to eliminate it. Second, don't sacrifice readability for DRYness; your tests should not only exercise code but also describe intent. I find it easiest to place shared examples in a support folder. One of the great things about Ruby is that if you don't like something, you can change it. A shared example serves as a quick way to define a test template, allowing you to store a test scenario that can be reused in other tests.
00:01:13.720
A good way to clean up your tests is by using shared examples, especially when the tests share a common structure. Take, for instance, your typical Rails controller specs; if you have a PostsController and a CommentsController, you could dry them up by using a shared example that captures the similarities between them. This approach results in code that simplifies your tests and improves readability.
00:01:36.640
Here are a few fast tips: First, name your shared examples so they read well. For example, you could call one 'shared example a Fibonacci calculator'. This makes your tests much easier for others to understand; it should behave like a Fibonacci calculator. Poorly named examples can lead to confusion. Second, use the 'describe' method to detail the class you are testing, which will allow you to take advantage of Ruby's functionalities like pluralization and singularization.
00:02:01.680
The third tip is to pass in variables to shared examples. For instance, if your controller test needs to redirect to a different place than usual, you can pass this variable into the shared example. The fourth tip is to create multiple variants of the shared example; two can exist in their current context while the others can create their own nested context. Just be mindful of the structure.
00:02:35.480
Finally, tip five is to ensure your tests go green first before employing shared examples. Start with tests that pass and then refactor them to be DRY using one of these techniques. Always strive to maintain readability and clarity in your tests even after making them DRY. That's all I have for today; thank you for your attention!