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

Advanced state control with hooks and mocks

Let's delve deeper into hooks and mocks. There are at least two related features that would be nice to have in WeatherQuery:

  • Store and retrieve a history of weather queries

  • Keep a count of the total number of API requests sent so we can throttle usage to avoid flooding the API with too many requests

As you can see, both of these features require us to set up a certain state before we can test them. In this case, we want to avoid mocking the actual state changes, because we would then have little or nothing to test. We can mock HTTP requests and other details not related to the state change, but we want to actually perform multiple queries and then make an assertion, rather than mock a state when multiple queries have been made. For example, if we are testing a method such as WeatherQuery.api_request_count without actually making requests, we would mock an instance variable (or other internal counter store) and check that the method returned the mock...