I just watched the TDD fundamentals video and they kind of discouraged the use of before blocks and lets. If I need to use quite a few mocks and doubles across different examples, what’s the best way to DRY these out?
Two main suggestions here:
- Use local methods in place of
before. This still allows for plenty of freedom to clean up and extract noisy setup from your spec, but makes this extracted setup explicit when you call those extracted setup methods rather than implicit as it is with
beforeand the like.
- If the setup is overly burdensome, consider extracting a class to abstract / hide some of that complexity, such that your spec will only need to mock 1-2 methods on that class. Test pain tends to highlight complexity and highly coupled code, so they present a great opportunity to refactor and simplify.
I highly recommend checking out our Let’s Not blog post which discusses this in more detail, and walks through the process of refactoring a spec with
befores to one using local helper methods for setup.