Sharing Setup (But Not Sandwiches)

As you write more specs, you’ll find yourself repeating setup code from example to example. This repetition clutters up your tests and makes changing the setup code harder.

Fortunately, RSpec provides ways to share common setup across several examples. Let’s begin by adding a second example after the first it block:

 it​ ​'lets me add toppings'​ ​do
  sandwich = Sandwich.new(​'delicious'​, [])
  sandwich.toppings << ​'cheese'
  toppings = sandwich.toppings
 
 expect​(toppings).not_to be_empty
 end

The expectation for this example introduces two new twists. First, you can negate your expectation—that is, check for falsehood—by using not_to instead of to. Second, ...

Get Effective Testing with RSpec 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.