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
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Mock HTTP responses with custom helpers


In the specs for the RedisWeatherQuery module that we worked with in Chapter 4, Setting Up and Cleaning Up, we mocked HTTP responses to prevent actual requests being sent during test runs. The code that accomplished this was simple:

let(:json_response) { '{}' }

before do
  allow(weather_query).to receive(:http).and_return(json_response)
end

For most specs, we actually don't need any mock response data, so an empty Hash is good enough. But this approach has some problems. First, we may want to validate the response we receive from the API to ensure it meets our expectations of how it is formatted. Second, we may have mocks in our specs that do not look like anything that the API returns. Third, we are treating the response imprecisely, ignoring the HTTP status code, assuming the body is valid JSON, and caching all responses regardless of success or failure status.

All these shortcomings will lead to bugs in our real-world code. Also, debugging will...