Rspec Essentials Develop Testable, Modular, An
Total Page:16
File Type:pdf, Size:1020Kb
RSpec Essentials Develop testable, modular, and maintainable Ruby software for the real world using RSpec Mani Tadayon BIRMINGHAM - MUMBAI RSpec Essentials Copyright © 2016 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: April 2016 Production reference: 1130416 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78439-590-2 www.packtpub.com Credits Author Project Coordinator Mani Tadayon Judie Jose Reviewers Proofreader Stefan Daschek Safis Editing Nola Stowe Indexer Commissioning Editor Rekha Nair Amarabha Banerjee Graphics Acquisition Editor Abhinash Sahu Reshma Raman Production Coordinator Content Development Editor Manu Joseph Rashmi Suvarna Cover Work Technical Editor Manu Joseph Anushree Arun Tendulkar Copy Editor Safis Editing About the Author Mani Tadayon first learned to program as a shy 7th grader on an Apple IIe using BASIC. He went on to learn Pascal, C++, Java, JavaScript, Visual Basic, and PHP before becoming a Ruby developer in 2008. With 15 years of experience in the software industry, he has developed expertise in web development, infrastructure, and testing. Mani's interests and education are broad, with degrees in foreign languages, computer science, and geography. He lives just far enough from Silicon Valley with his family and their many, many Shiba Inus. About the Reviewers Stefan Daschek started hacking on computers back in the days of the Commodore 64/128. Since then, he has studied computer sciences at TU Vienna and founded his own company, Büro DIE ANTWORT. Currently, he is mainly developing and maintaining complex web applications written in Ruby on Rails, and sometimes soldering stuff and building small robots. His original Commodore 128 is still working and used for a collective session of Summer Games every so often. Nola Stowe has been programming with Ruby since Rails 0.8 and testing with RSpec since its early days. She is an independent consultant, helping to augment teams of Ruby and Clojure developers. She has also been a technical reviewer for Instant RSpec Test-Driven Development, Packt Publishing and The Rails Way, First Edition. Nola blogs at http://blog.rubygeek.com and http://www.clojuregeek.com. Thanks to my husband Nick for doing the mundane things in life to allow me time do what I love doing. You are the greatest! www.PacktPub.com eBooks, discount offers, and more Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM https://www2.packtpub.com/books/subscription/packtlib Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books. Why subscribe? • Fully searchable across every book published by Packt • Copy and paste, print, and bookmark content • On demand and accessible via a web browser Table of Contents Preface v Chapter 1: Exploring Testability from Unit Tests to Behavior-Driven Development 1 The promise of testing 1 Testability 3 Technical assumptions 4 Running our first spec 5 Understanding the unit test 9 Writing specs with RSpec 12 Test-driven development 14 Behavior-driven development 15 Summary 16 Chapter 2: Specifying Behavior with Examples and Matchers 17 Structure of a spec file 17 Using let and context 20 Matchers 23 Built-in matchers 23 Custom matchers 24 Enhanced context in matcher output 26 Creating a good custom error message 29 Improving application code 31 Testing for errors 35 Summary 40 [ i ] Table of Contents Chapter 3: Taking Control of State with Doubles and Hooks 41 Why mock? 41 Mocks, stubs, and doubles 45 Using hooks 46 Controlling when hooks are executed 52 Advanced state control with hooks and mocks 53 Summary 58 Chapter 4: Setting Up and Cleaning Up 59 Configuring RSpec with spec_helper.rb 59 Initialization and configuration of resources 62 A case study of test simplicity with an external service 63 A case study of production faithfulness with a test resource instance 76 Summary 83 Chapter 5: Simulating External Services 85 The importance of external web services 85 Mock HTTP responses with custom helpers 86 Using real-world requests for mock responses 87 Using WebMock for mock HTTP requests 93 Using VCR for mock requests 94 Summary 98 Chapter 6: Driving a Web Browser with Capybara 99 Getting started with Capybara and Selenium 100 Integrating Capybara with RSpec 103 Why Capybara? 106 Black-box JavaScript tests with a real browser 107 Summary 108 Chapter 7: Building an App from the Outside In with Behavior-Driven Development 109 Exploring BDD 110 MMFs by example 111 Using TodoMVC 113 Specifying the MMF 114 Configuring RSpec to run a feature file 116 The BDD process begins 119 Building web apps with Rack 120 Serving static files using Rack middleware 123 Summary 125 [ ii ] Table of Contents Chapter 8: Tackling the Challenges of End-to-end Testing 127 Step 1 – building the view 127 Step 2 – defining the API 133 Step 3 – finishing the view 157 The pros and cons of BDD 160 Simple Rack authentication middleware 161 JSON Web Token 164 Summary 166 Chapter 9: Configurability 167 Configuration and testability 168 What is so important about configuration? 168 What does all this have to do with testing? 169 File-based configuration management 169 A better configuration manager 173 Summary 184 Chapter 10: Odds and Ends 185 Reducing duplication with shared example groups 185 Mocking time 193 Detecting false negatives and false positives 196 Testing mixins with dummy containers 200 Summary 202 Index 203 [ iii ] Preface 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. [ v ] Preface 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.