O'Reilly logo

Effective Testing with RSpec 3 by Myron Marston, Ian Dees

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required