Effective Testing with RSpec 3, Getting Started

Notes from Effective Testing with RSpec 3, chapter 1.

Effective Testing opens with explaining that Behavior & Test Driven Development provide us with design guidance, a safety net, and documentation. All of these are great reasons but my favorite is something I heard from the Ruby Rouges podcast,

“You are not paying me to write tests. You are paying to guarantee my code is doing what you are paying for.”

A part of Getting Started is installing Ruby & the RSpec libary, which you would expect is a single gem. RSpec has separated it’s behavior into 3 gems: Core, Expectations, & Mocks. The idea is that you can mix and match libraries with other test frameworks and mocking tools. I was curios if anyone had taken advantage of this and found ‘Zverok with Ruby’ who wrote about using RSpec libraries for easier to read conditionals, exploring a code base, method validations, and more.

By the end of Getting Started we will have coded out a spec to describe the Sandwich class. We will also have explored three different ways to condense our code and make our tests easier to read:

Hooks are a way to run setup code before, after, and around a test block. The idea is to create a standard environment where each example, context, description, etc. runs with the same values and state. One thing I didn’t see in this chapter was filtering hooks, which seems really useful.

Helper methods, the second way of condensing our code, is just plain ruby. The authors remind us that we’re not forced into RSpec and if it’s easier to hack something out we should just do that.

This section then ends on let. A useful way to initiate and reuse an instance variable: let(:sandwich) { Sandwich.new("delicous', []) }. This is the most common way to condense code. It protects us from misspelling the sandwich variable in our examples, it’s only run when called, and easy to refactor.

Getting Started concludes by suggesting we look at rspec --help to discover available options. Here are a few things I explored:

  • dry-run: We can dry-run tests to print out expectations. This is really useful for documentation. If I’m curios about a service or object I can run it’s specs dry and read them as the intended use without waiting for tests to run.
  • formats: Results can be printed in a variety of ways. Not just for communicating to me, the developer, but to another audience viewing them through a browser or JSON API.
  • filter: Tests can be filtered when run. This is essential for rapid testing. When I’m working on a section of code, I only want to run the relevant tests. I won’t run the entire suite until after I’ve completed a task.