Pivotal Labs

Alex Chaffee's blog



doing it again and again

edit Posted by Alex Chaffee on Wednesday August 08, 2007 at 04:23PM

Here's an RSpec trick I discovered yesterday. Sometimes when you're writing a test you want to loop over some precondition data. But if you do a loop inside your test (or spec), then all the cases will be subsumed in a single test method (or "it" block). This means you'll have the following problems:

  • The first case to fail will cause the rest of the cases not to run. It'd be nice to see them all in a single test run.
  • You won't take advantage of RSpec's cool self-documenting trick of labeling each it block with a full description of the failure, and it'll be harder to debug which case failed.
  • If you're calling into Rails (e.g. in a View spec), you'll only be able to call certain methods -- especially render -- once per test method. That means that you simply can't use a loop inside a method to collapse redundant tests into a single block.

Ruby to the rescue! Instead of looping inside your it block, loop outside your it block.