Skip to content

Instantly share code, notes, and snippets.

@mkb
Created December 25, 2012 20:25
Show Gist options
  • Select an option

  • Save mkb/4375249 to your computer and use it in GitHub Desktop.

Select an option

Save mkb/4375249 to your computer and use it in GitHub Desktop.
How I use RSpec

After writing tests with a lot of different pairs, hacking on a lot of existing tests, and reading various blog posts, I've settled on a set of RSpec practices which work well for me:

  1. Keep "it" blocks as small as practical. Strive for one assertion each.
  2. Invert dependencies as if your life depends on it.
  3. Nested describe blocks are your friends.
  4. Using "context" is sometimes more descriptive than "describe."
  5. A describe block for each method annoys the crap out of some people, but works well for me. Try it and let me know what you think.
  6. Don't retest behavior which is already verified in another nearby test.
  7. There's a matcher for that.
  8. Go ahead and say "test" instead of "spec" if you feel like it. The world won't end.
  9. Mercilessly refactor your tests for clarity, especially by extracting methods.
  10. Testing small pieces makes test-first easier.
  11. Brevity is the essence of wit.
  12. "let" will make your life easier, but not always.
  13. Don't fear mocks or stubs. If mocking/stubbing becomes hard, that's a code smell.
  14. If your tests are ugly, consider how changing the design of your code might make the tests cleaner. This almost always yields better code.
  15. In particular, your tests may tell you when it's time to split a class in two.
  16. Rails test fixtures will get you into trouble.
  17. The "pending" feature is a thing of beauty. It helps test-first to play nicely with CI.
  18. Stop guessing. Take a little time to learn ruby-debug, Pry, or something comparable.
  19. Prefer logging to puts when debugging.
  20. Writing custom matchers isn't so bad.
  21. Require individual classes as needed in your spec files rather than requiring everything in spec_helper.
  22. Order-dependent test failures? Look for global state and crush it like a bug.
  23. Use Guard. It's easy to set up and saves you time.
  24. Stub out external services with realweb or rack-client.
  25. Prefer options in .rspec to explicit configuration in your spec helper—other developers might not like the same options as you.
  26. -cfs works well for me.
  27. Explicit use of "subject" makes your tests less readable.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment