Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
₹799 | ALL EBOOKS & VIDEOS
Save more on purchases! Buy 2 and save 10%, Buy 3 and save 15%, Buy 5 and save 20%
Rspec Essentials
Rspec Essentials

Rspec Essentials: Develop testable, modular, and maintainable Ruby software for the real world using RSpec

eBook
₹700 ₹2621.99
Paperback
₹3276.99
Subscription
Free Trial
Renews at ₹400p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Rspec Essentials

Chapter 2. Specifying Behavior with Examples and Matchers

In this chapter, we'll see how RSpec's examples and matchers implement the general testing concepts of units and assertions. An example is the base unit for a set of RSpec specs and, within it, you must have a matcher to assert something, otherwise it would serve no purpose.

In this chapter, we will cover the following topics:

  • Structure of a spec file

  • RSpec output

  • Matchers

  • The let helper

  • Testing for errors

Structure of a spec file


Let's look again at the AddressValidator module we introduced in Chapter 1, Exploring Testability from Unit Tests to Behavior-Driven Development, so we can understand its structure better. We'll also use some basic RSpec features to improve the tests. Let's look at the spec code:

require 'rspec'
require_relative 'address_validator'

describe AddressValidator do
  it "returns false for incomplete address" do
    address = { street: "123 Any Street", city: "Anytown" }
    expect(
      AddressValidator.valid?(address)
    ).to eq(false)
  end

  it "missing_parts returns an array of missing required parts" do
    address = { street: "123 Any Street", city: "Anytown" }
    expect(
      AddressValidator.missing_parts(address)
    ).to eq([:region, :postal_code, :country])
  end
end

We defined a local variable address in each example. This is fine for simple, one-off values. We could get the same functionality shared across multiple tests with a local function defined...

Using let and context


This scenario is very common, and inevitably will make the test harder to read, increasing the potential for misunderstanding the intent, which in turn will increase the likelihood of mistakes being made when the test or related code is changed. Before we see how to improve the test, we will learn about the let helper:

describe AddressValidator do
  let(:address) { {street: "123 Any Street", city: "Anytown"} }

  it "valid? returns false for incomplete address" do
    expect(AddressValidator.valid?(address)).to eq(false)
  end

  it "missing_parts returns an array of missing required parts" do
    expect(
      AddressValidator.missing_parts(address)
    ).to eq([:region, :postal_code, :country])
  end

  context "invalid characters in value" do

    let(:address){ {street: "123 Any Street", city: "Any$town%"} }
      
    it "invalid_parts returns keys with invalid values" do
      expect(
        AddressValidator.invalid_parts(address)
       ).to eq([:city])
    ...

Matchers


We've been using RSpec's eq matcher to make assertions so far. We don't absolutely need this or any of RSpec's other matchers. We could use standard Ruby or define our own helper methods, like so:

describe 'no matchers' do
  it "valid? returns false for incomplete address" do
    expected = AddressValidator.valid?(address)
    if expected != false
      # RSpec's fail method allows us to manually fail an example 
      fail "Expected #{expected} to have value of false"
    end
  end
end

There are a few problems with this approach. First, it is clumsy to write and read. Second, without a standard way of handling assertions, we're likely to wind up with a bunch of variations on the code above, making our output confusing. Finally, it is very easy to make mistakes with this kind of code, leading to invalid test results.

RSpec's matchers offer a simple and elegant syntax for making assertions. This makes it easy to write tests and also makes the intent of the test much clearer, allowing...

Testing for errors


Tests are written to prevent errors from happening. The experienced programmer knows that errors are inevitable, and seeks to anticipate them by writing tests that deal specifically with errors.

There are three basic cases to deal with when testing errors:

  • no error is raised

  • an external error (an error class not in the code under test) is raised

  • an internal error (a custom error class in the code under test) is raised

There are two basic decisions to make when writing code that raises an error.

The first is whether to allow an error to be raised or to attempt to recover from it with defensive practices, such as using a rescue block or fixing inputs that could cause an error to be raised. In general, lower-level, library code should expose errors without trying to recover from them, allowing the consumer of the code to handle error cases on their own. Higher-level application code should strive to recover from errors more aggressively, allowing only truly unrecoverable errors...

Summary


In this chapter, we've covered a lot of material. We are ready now to use RSpec for all kinds of testing and to help improve the quality of our code. Let's recall the topics we discussed:

  • Structure of a spec file

  • RSpec output

  • Matchers

  • The let helper

  • Testing for errors

In our last section, on errors, we used a mock to generate an error. In the next chapter, we'll go into great detail about how to set up our testing environment using mocks and hooks to simulate various test scenarios.

Left arrow icon Right arrow icon

Key benefits

  • Explore the concept of testability and how to implement tests that deliver the most value
  • Maximize the quality of your Ruby code through a wide variety of tests
  • Master the real-world tradeoffs of testing through detailed examples supported by in-depth discussion

Description

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.

Who is this book for?

This book is aimed at the software engineer who wants to make their code more reliable and their development process easier. It is also aimed at test engineers who need to automate the testing of complex systems. Knowledge of Ruby is helpful, but even someone new to the language should find it easy to follow the code and tests.

What you will learn

  • * Identify a unit of software for the purposes
  • of testing
  • * Manage test states with hooks, fixtures,
  • and mocks
  • * Handle external web services in tests
  • using various techniques
  • * Configure RSpec flexibly and cleanly using
  • support code and environment variables
  • * Interact with rich web apps in tests
  • using Capybara
  • * Build the right feature with behavior-driven
  • development
  • * Customize matchers and failure messages
  • * Verify correct development and production
  • environments

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 21, 2016
Length: 222 pages
Edition : 1st
Language : English
ISBN-13 : 9781784392956
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Apr 21, 2016
Length: 222 pages
Edition : 1st
Language : English
ISBN-13 : 9781784392956
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹400 billed monthly
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
₹4000 billed annually
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts
₹5000 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 6,553.98
Comprehensive Ruby Programming
₹3276.99
Rspec Essentials
₹3276.99
Total 6,553.98 Stars icon

Table of Contents

10 Chapters
Exploring Testability from Unit Tests to Behavior-Driven Development Chevron down icon Chevron up icon
Specifying Behavior with Examples and Matchers Chevron down icon Chevron up icon
Taking Control of State with Doubles and Hooks Chevron down icon Chevron up icon
Setting Up and Cleaning Up Chevron down icon Chevron up icon
Simulating External Services Chevron down icon Chevron up icon
Driving a Web Browser with Capybara Chevron down icon Chevron up icon
Building an App from the Outside In with Behavior-Driven Development Chevron down icon Chevron up icon
Tackling the Challenges of End-to-end Testing Chevron down icon Chevron up icon
Configurability Chevron down icon Chevron up icon
Odds and Ends Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.3
(3 Ratings)
5 star 33.3%
4 star 0%
3 star 33.3%
2 star 33.3%
1 star 0%
J S Apr 28, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As one of the technical editors on this project, I can say this is a great book for people who already know some ruby and would like to dive into testing with RSpec. It covers all aspects of testing including mocking external services, integration tests with capybara, selenium and complete end-to-end examples. It covers some of the tricky parts of testing like testing time, testing mixins, and how to find false positives. Some of these things you only learn by experience and you can learn on the experience of this author to advance your RSpec skills quickly.
Amazon Verified review Amazon
Jeff Nyman Aug 14, 2016
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
I'm very torn on this book. I think the author has a good writing style and means of presentation. I like how the examples in the book are built up and how the explanations around those examples provide an incremental increase in context. The conversational tone of the book is also very welcome, as I believe it lends itself well to this kind of subject.However, all that being said, this book is plagued by what plagues many other Packt books: poor quality of the examples. Going through Chapter 2 alone, for example, you will find many mistakes not just in the text, but in the code as well.For the text problems, the issue seems to be that code was changed after the text was written but the text was not changed to reflect that. Ironic in a book that is ultimately about testing: you always make sure to test the final product.For the code, the issue is that some of it simply doesn't work as it is provided. Further, if you look at the code download that Packt makes available for the site, you will often find that the code there differs from what is in the book. And sometimes both of those differ from what the text itself describes.There is apparently one of the "technical editors" who wrote a review for this book. I'm not sure I would necessarily admit to that, given some of these issues. (Technical editors are responsible for technical accuracy.) As one of the more obvious lacks of accuracy -- and you literally cannot miss it, there is an AddressValidator class created at one point. The book itself has you call an invalid_parts() method as part of the RSpec tests for that class. Yet the AddressValidator class shown in the book has no invalid_parts() method. Nor -- at the time of writing this review -- did the code download from the Packt site. This is but one of many other issues.This happens just enough that -- depending on your time, patience, and tolerance -- you run up against a trust barrier. This is the killer problem for technical books. If readers start to feel they can't trust what the book is showing them, they are likely to go somewhere else for the information. Most likely to the numerous blogs that document tools like RSpec and can be updated on the fly if errors are found.I do want to stress that, depending on your overall experience and skill level, you absolutely can get useful information out of this book, which is why I rate this book with three stars. But there can be a lot of overhead to getting that useful information. It really is up to each reader whether the overhead is worth the effort. The best a reviewer like myself can do is at least provide you with the cautionary aspect.RSpec is a fantastic tool and Ruby is a fantastic language. It pains me to see what should be a excellent resource like this not pass muster. There is no way, for example, that I could recommend this book to any company I do consulting for. Even though I really, really want to.
Amazon Verified review Amazon
Beverly Jul 26, 2016
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I've been going through the book, doing the examples on each page. I'm currently on page 57, and I've found 5 errors that make the examples incorrect. Unless you correct the syntax errors and add missing methods to the example classes, you won't be able to follow the examples. So far, I also haven't seen good organization of thoughts. Lots of examples, and many of them don't work.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.

Modal Close icon
Modal Close icon