Book Image

RSpec Essentials

By : Mani Tadayon
Book Image

RSpec Essentials

By: Mani Tadayon

Overview of this book

This book will teach you how to use RSpec to write high-value tests for real-world code. We start with the key concepts of the unit and testability, followed by hands-on exploration of key features. From the beginning, we learn how to integrate tests into the overall development process to help create high-quality code, avoiding the dangers of testing for its own sake. We build up sample applications and their corresponding tests step by step, from simple beginnings to more sophisticated versions that include databases and external web services. We devote three chapters to web applications with rich JavaScript user interfaces, building one from the ground up using behavior-driven development (BDD) and test-driven development (TDD). The code examples are detailed enough to be realistic while simple enough to be easily understood. Testing concepts, development methodologies, and engineering tradeoffs are discussed in detail as they arise. This approach is designed to foster the reader’s ability to make well-informed decisions on their own.
Table of Contents (17 chapters)
RSpec Essentials
About the Author
About the Reviewers


RSpec is one of the reasons why the Ruby programming language has become so popular. There is a strong emphasis on testing, documentation, and iterative development in the Ruby community. With RSpec, it is easy to create excellent tests that specify behavior and improve the development process.

In this book, we'll learn how to use RSpec in a real-world setting. We'll also learn about the concept of testability, which relates to our application code as well as to our tests. Throughout, we'll focus on writing tests that are valuable and stay away from testing for its own sake.

RSpec offers a variety of tools for creating test scenarios, assertions, and error messages. We can create the tests we need and get the exact output we want using RSpec without having to do too much work. RSpec has been under development for almost 10 years, so it has evolved significantly. Many ways of writing tests have developed due to the flexibility of RSpec and the underlying Ruby language. Some of these are clever but some others are too clever. We'll learn about a solid subset of RSpec's features that are reliable and avoid some of the trickier features.

Today, professional software development must include automated testing. However, testing presents many challenges in the real world. There is a danger of learning about testing tools without knowing how to use them effectively. In this book, we will always keep an eye on the real world, even in our simple examples. We'll cover a range of application types, from libraries to rich web UIs, and a range of approaches to testing, from unit tests to behavior-driven development. Along the way, we'll discuss potential pitfalls and develop production-grade solutions to avoid them.

As you progress through this book, you will learn about many RSpec features, my recommended approach to using them, and their relation to testability. I hope that you can use this book both as a handbook for simple tasks and as a guide to developing a sophisticated understanding of automated software testing.

What this book covers

Chapter 1, Exploring Testability from Unit Tests to Behavior-Driven Development, defines the basic concepts of unit, test, and testability, and puts them in context.

Chapter 2, Specifying Behavior with Examples and Matchers, shows how RSpec's basic features implement units and assertions.

Chapter 3, Taking Control of State with Doubles and Hooks, discusses how RSpec implements mocks and hooks to allow us to set up a test scenario.

Chapter 4, Setting Up and Cleaning Up, delves further into how we can simulate external resources such as databases and web servers while keeping our test environment clean using RSpec support code.

Chapter 5, Simulating External Services, extends our discussion of handling external web services by using the VCR gem.

Chapter 6, Driving a Web Browser with Capybara, introduces the Capybara library, and shows how to use it to test rich web UIs.

Chapter 7, Building an App from the Outside In with Behavior-Driven Development, explains BDD and how RSpec can be used to define high-level features.

Chapter 8, Tackling the Challenges of End-to-end Testing, continues with the development of the app built in the previous chapter, focusing on common testing pain points, such as authentication.

Chapter 9, Configurability, introduces a concept that is related to testability and an implementation of a real-world configuration system.

Chapter 10, Odds and Ends, wraps up the book by covering a few advanced topics that didn't quite fit into the previous chapters, but which were too important to leave out.

What you need for this book

You'll need two basic pieces of software for this book: Ruby and RSpec.

You can install the Ruby programming language from its web site:

The latest version at the time of writing is 2.3.0. Any version of Ruby greater than 2.0 should be fine.

I recommend that you use rbenv to install Ruby. This tool will make it easier to keep a clean Ruby environment. Professional Ruby developers rely on rbenv or similar tools to install and manage Ruby on their systems. You can find more info on rbenv on its GitHub page:

You can install RSpec using the rubygems installer (gem install rspec). The latest version of RSpec at the time of writing is 3.4.0, but any version greater than 3.0 should work fine. More details on RSpec can be found on its GitHub repo:

Who this book is for

This book is for the programmer who has some experience with Ruby. If you have written some small programs and are familiar with defining basic functions, modules, and classes, then you should be fine. If you have no background in Ruby, you will still be able to follow along, but will need to do a little extra work to follow the more complicated sections. I've done my best to build up complex examples step by step and clearly explain every aspect of the code samples with comments.


In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

require 'rspec'

describe 'new RSpec syntax' do
  it "uses the new assertion syntax" do
    # new                           # deprecated
    expect(1 + 1).to eq(2)          # (1 + 1).should == 2

Any command-line input or output is written as follows:

# comments to clarify the command
$ echo 'Hello'
# => Hello

Often, command-line output will be displayed in screenshots to show output more clearly and to discourage cut-and-paste without thinking through the commands. The screenshots will like look the following:


Warnings or important notes appear in a box like this.


Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.

  2. Hover the mouse pointer on the SUPPORT tab at the top.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box.

  5. Select the book for which you're looking to download the code files.

  6. Choose from the drop-down menu where you purchased this book from.

  7. Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from


Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to and enter the name of the book in the search field. The required information will appear under the Errata section.


Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.


If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.