← Back to Upcase

What's the best way to DRY out mocks and doubles setup?


(O. Bucao) #1

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?


(Chris Toomey) #2

Two main suggestions here:

  1. Use local methods in place of let and 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 let and before and the like.
  2. 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 let and befores to one using local helper methods for setup.