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

Simple Rack authentication middleware

Now that we've built an API, we can start thinking about securing it. Both for the users of our web UI and other users that directly hit the API from other sites, authentication is a critical feature that we're missing. We won't build a complete authentication solution, but we'll add the critical authentication middleware that will be the main component in an authentication system. We'll see that it won't be much more work.

We briefly mentioned Rack middleware in Chapter 7, Building an App from the Outside In with Behavior-Driven Development, when we used Rack::Static to serve static assets. Now we're going to add middleware that will authenticate every request before it hits our app.

First, let's start with a simple example with a file called auth_middleware.rb:

class AuthMiddleware
  def initialize(app, opts={})
    if ! opts[:secret].is_a?(String)
      raise ':secret is required'
    @app    = app
    @secret = opts[:secret]