Rails Test Prescriptions

Total Page:16

File Type:pdf, Size:1020Kb

Rails Test Prescriptions What readers are saying about Rails Test Prescriptions This a must-have book for those new to testing on a team that thinks, "We don’t have time for testing," and for experienced developers look- ing to round out their testing skills. If you want to write better code, deploy with confidence, and accelerate your team’s velocity, you should read this book! John McCaffrey Rails Developer/Project Manager, Railsperformance.blogspot.com Rails Test Prescriptions presents a nuanced and unbiased overview of the tools and techniques professionals use to test their Rails apps every day. A must-read for any Rails developer, whether you’ve never written a single test or you’ve written thousands. David Chelimsky Senior Software Engineer, DRW Trading Rails Test Prescriptions is a great resource for anyone interested in getting better at testing Rails applications. New readers will find many helpful guides, and experienced readers will discover many lesser- known tips and tricks. Nick Gauthier Developer, SmartLogic Solutions If you are comfortable working with Rails, yet have no experience writ- ing tests for it, this book is an excellent resource for getting up to speed on the most successful tools used to test drive your develop- ment. Adam Williams (@aiwilliams) Noel has dispensed a fantastic collection of prescriptions for all kind of testing maladies. Whether you are a budding intern, or a highly specialized surgeon, this book will provide you with the information you need to improve your testing health. Christopher Redinger Principal, Relevance, Inc. Testing is a given in the Rails world, but the varied options can be daunting if you are just starting to learn the framework. Noel provides a solid tour of the options and techniques for testing a Rails applica- tion that will help guide you past some of the initial dark corners. If you are entering the world of Ruby on Rails, I’d recommend keeping a copy of Rails Test Prescriptions at hand. Corey Haines Software Journeyman Rails TestPrescriptions Keeping Y o u r Application Healthy Noel Rappin The Pragmatic Bookshelf Raleigh, North Carolina Dallas, Texas Many of the designations used by manufacturers and sellers to distinguish their prod- ucts are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g device are trademarks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at http://www.pragprog.com. The team that produced this book includes: Editor: Colleen Toporek Indexing: Potomac Indexing, LLC Copy edit: Kim W i m p s e t t Production: Janet Furlow Customer support: Ellie Callahan International: Juliet Benda Copyright © 2010 Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmit- ted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-10: 1-934356-64-6 ISBN-13: 978-1-934356-64-7 Printed on acid-free paper. P1.0 printing, February 2011 V e r s i o n : 2011-2-14 Contents I Getting Started with T e s t i n g in Rails 12 1 The Goals of Automated Developer T e s t i n g 13 1.1 A Testing Fable . 13 1.2 Who Are Y o u ? . 15 1.3 The Power of Testing First . 16 1.4 What Is TDD Good For? . 17 1.5 When TDD Needs Some Help . 19 1.6 Coming Up Next... 20 1.7 Acknowledgments . 22 2 The Basics of Rails T e s t i n g 24 2.1 What’s a Test? . 24 2.2 What Goes in a Test? . 26 2.3 Setup and Teardown . 29 2.4 What Can Y o u Test in Rails? . 32 2.5 What Happens When Tests Run? . 34 2.6 Running the Rails Tests . 36 2.7 More Info: Getting Data into the Test . 38 2.8 Beyond the Basics . 41 3 W r i t i n g Y o u r First T e s t s 42 3.1 The First Test-First . 44 3.2 The First Refactor . 47 3.3 More Validations . 49 3.4 Security Now! . 53 3.5 Applying Security . 55 3.6 Punishing Miscreants . 56 3.7 Road Map . 60 CONTENTS 8 4 TDD, Rails Style 61 4.1 Now for a V i e w Test . 61 4.2 Testing the Project V i e w : A Cascade of Tests . 64 4.3 So Far, So Good . 70 II T e s t i n g Application Data 71 5 T e s t i n g Models with Rails Unit T e s t s 72 5.1 What’s Available in a Model Test . 72 5.2 What to Test in a Model Test . 74 5.3 OK, Funny Man, What Is a Good Model Test Class? 74 5.4 Asserting a Difference, or Not . 76 5.5 Testing Active Record Finders . 77 5.6 Coming Up Next . 80 6 Creating Model T e s t Data with Fixtures and Factories 81 6.1 Defining Fixture Data . 81 6.2 Loading Fixture Data . 84 6.3 Why Fixtures Are a Pain . 85 6.4 Using Factories to Fix Fixtures . 86 6.5 Data Factories . 87 6.6 Installing factory_girl . 87 6.7 Creating and Using Simple Factories . 88 6.8 Sequencing for Unique Attributes . 90 6.9 Freedom of Association . 91 6.10 Factories of the W o r l d Unite . 93 6.11 Managing Date and TimeData . 95 6.12 Model Data Summary . 99 7 Using Mock Objects 101 7.1 What’s a Mock Object? . 101 7.2 Stubs . 103 7.3 Stubs with Parameters . 108 7.4 Mock, Mock, Mock . 112 7.5 Mock Objects and Behavior-Driven Development . 114 7.6 Mock Dos and Mock Don’ts . 117 7.7 Comparing Mock Object Libraries . 118 7.8 Mock Object Summary . 126 Report erratum this copy is (P1.0 printing, Febr uar y 2011) CONTENTS 9 III T e s t i n g User-Facing Layers 127 8 T e s t i n g Controllers with Functional T e s t s 128 8.1 What’s Available in a Controller Test? . 128 8.2 What to Test . 129 8.3 Simulating a Controller Call . 130 8.4 Testing Controller Response . 133 8.5 Testing Returned Data . 134 8.6 Testing Routes . 137 8.7 Coming Up . 138 9 T e s t i n g Views 139 9.1 The Goals of V i e w Testing . 139 9.2 Keys to Successful V i e w Testing . 140 9.3 Using assert_select . 141 9.4 Testing Outgoing Email . 146 9.5 Testing Helpers . 148 9.6 Testing Block Helpers . 150 9.7 Using assert_select in Helper Tests . 151 9.8 How Much TimeShould Y o u Spend on Helpers? . 153 9.9 When to V i e w Test . 153 10 T e s t i n g JavaScript and Ajax 155 10.1 First Off, RJS . 156 10.2 Testing JavaScript from Rails with Jasmine . 158 10.3 Getting Started with Jasmine . 158 10.4 Running Jasmine Tests . 159 10.5 W r i t i n g Jasmine Tests . 161 10.6 Integrating Jasmine with Dynamic Rails . 165 IV T e s t i n g Framework Extensions 168 11 W r i t e Cleaner T e s t s with Shoulda and Contexts 169 11.1 Contexts . 170 11.2 Basics of Shoulda . 173 11.3 Single Assertion Testing . 173 11.4 Shoulda Assertions . 175 11.5 Shoulda One-Liners . 176 11.6 W r i t i n g Y o u r Own Shoulda Matcher . 179 11.7 Single-Line Test Tools . 183 11.8 When to Use Shoulda . 185 Report erratum this copy is (P1.0 printing, Febr uar y 2011) CONTENTS 10 12 RSpec 186 12.1 Getting Started with RSpec . 187 12.2 RSpec in Ten Minutes . 189 12.3 RSpec and Rails . 199 12.4 Running RSpec . 209 12.5 RSpec in Practice . 209 12.6 Creating Y o u r Own Matchers . 211 12.7 Summarizing RSpec . 213 V T e s t i n g Everything All T o g e t h e r 214 13 T e s t i n g W o r k fl o w with Integration T e s t s 215 13.1 What to Test in an Integration Test . 216 13.2 What’s Available in an Integration Test? . 216 13.3 Simulating Multipart Interaction . 218 13.4 Simulating a Multiuser Interaction . 220 13.5 When to Use Integration Tests . 223 14 W r i t e Better Integration T e s t s with W e b r a t and Capybara 224 14.1 Installing W e b r a t and Capybara . 225 14.2 Using the Acceptance Testing Rodents .
Recommended publications
  • Python Guide Documentation 0.0.1
    Python Guide Documentation 0.0.1 Kenneth Reitz 2015 09 13 Contents 1 Getting Started 3 1.1 Picking an Interpreter..........................................3 1.2 Installing Python on Mac OS X.....................................5 1.3 Installing Python on Windows......................................6 1.4 Installing Python on Linux........................................7 2 Writing Great Code 9 2.1 Structuring Your Project.........................................9 2.2 Code Style................................................ 15 2.3 Reading Great Code........................................... 24 2.4 Documentation.............................................. 24 2.5 Testing Your Code............................................ 26 2.6 Common Gotchas............................................ 30 2.7 Choosing a License............................................ 33 3 Scenario Guide 35 3.1 Network Applications.......................................... 35 3.2 Web Applications............................................ 36 3.3 HTML Scraping............................................. 41 3.4 Command Line Applications....................................... 42 3.5 GUI Applications............................................. 43 3.6 Databases................................................. 45 3.7 Networking................................................ 45 3.8 Systems Administration......................................... 46 3.9 Continuous Integration.......................................... 49 3.10 Speed..................................................
    [Show full text]
  • Specialising Dynamic Techniques for Implementing the Ruby Programming Language
    SPECIALISING DYNAMIC TECHNIQUES FOR IMPLEMENTING THE RUBY PROGRAMMING LANGUAGE A thesis submitted to the University of Manchester for the degree of Doctor of Philosophy in the Faculty of Engineering and Physical Sciences 2015 By Chris Seaton School of Computer Science This published copy of the thesis contains a couple of minor typographical corrections from the version deposited in the University of Manchester Library. [email protected] chrisseaton.com/phd 2 Contents List of Listings7 List of Tables9 List of Figures 11 Abstract 15 Declaration 17 Copyright 19 Acknowledgements 21 1 Introduction 23 1.1 Dynamic Programming Languages.................. 23 1.2 Idiomatic Ruby............................ 25 1.3 Research Questions.......................... 27 1.4 Implementation Work......................... 27 1.5 Contributions............................. 28 1.6 Publications.............................. 29 1.7 Thesis Structure............................ 31 2 Characteristics of Dynamic Languages 35 2.1 Ruby.................................. 35 2.2 Ruby on Rails............................. 36 2.3 Case Study: Idiomatic Ruby..................... 37 2.4 Summary............................... 49 3 3 Implementation of Dynamic Languages 51 3.1 Foundational Techniques....................... 51 3.2 Applied Techniques.......................... 59 3.3 Implementations of Ruby....................... 65 3.4 Parallelism and Concurrency..................... 72 3.5 Summary............................... 73 4 Evaluation Methodology 75 4.1 Evaluation Philosophy
    [Show full text]
  • Brian Ray Hi, I’M Brian Ray
    Python Hype? Brian Ray Hi, I’m Brian Ray • Indy Consulting Years • Directive Years 2010-2013 1998-2003 • Leadership Years 2009-2010 • Engineering Years • Big Four Consulting 2003-2006 2013-current Taken in China May 20th, 2016 Why “Python Hype”? In the last 10 years, we are seeing Python having (select one): A. Slow and steady growth. B. Spiked and now on decline. C. Spiked + Declined now stabilized. D. Lives in independent domain. E. We (Python fans) live in a bubble. What measure? • Hype Cycle • TIOBE Index • On Github • PYPL • Some other Don’t tell me there aren’t trends Programming language “popularity” is hard to measure. Lenses to help measure: 1. Learned: was taught Python in course 2. Migrated: from language to language 3. Addressed: problem class to solve 4. Platform-ed: ecosystem of tools 5. Retained: sticking with Python 6. Promoted: Promoted 236 respondents broken up into 3 groups OUR SURVEY Who Groups 1 2 3 The missing group 4: Those who didn’t take the survey User Distribution 1 2 3 29% 49 % 22% Treatment of groups • Learned • Addressed • Migrated • Platform-ed 1 2 3 all • Retained • Curve • Promoted Questions Group 1: Learned/Migrated • 60% heard of python Word of mouth • 56% had very positive first impression, 31% had positive, less than 13% neutral or less. • Net-promoter to recommend Group 1: Learned/Migrated Group 1: Learned/Migrated “Python is Now the Most Popular Introductory Teaching Language at Top U.S. Universities” By Philip Guo July 7, 2014 Group 2: addressed / platformed • 63% very positive 1st impression (3%
    [Show full text]
  • RUBY for PENETRATION TESTERS RUBY for PENETRATION Ruby for Penetration Testers
    1 RUBY FOR PENETRATION TESTERS RUBY FOR PENETRATION ruby for penetration testers When you're down deep reversing a protocol • Getting up close and personal with or picking apart a binary, getting up to speed proprietary file formats quickly can be challenging in the best of circumstances. Over the past few years, we've • Becoming the puppet-master of both native figured out a tool that we can rely on every and Java applications atruntime time: the Ruby programming language. We'd like to highlight our use of Ruby to solve the • Exposing the most intimate parts of exotic security testing problems we're faced with network services like JRMI and Web services every day. • Trimming the time you spend decoding proprietary protocols and cutting directly to We use Ruby because it’s easy, flexible, and powerful. It works for everything from reverse fuzzing them engineering firmware bus protocols to fuzzing file formats to static and dynamic binary As if all that wasn’t enough, we'll show you analysis. We've used it to beat up web apps, how to make Ruby mash-ups of the stuff you and we've stuck with it all the way to attacking already love. Make the tools you already rely exotic proprietary hardware applications. on new again by getting them to work Having a great set of tools available to meet together, harder and smarter. When you're your needs might be the difference between a asked to get twice as much done in half the successful result for your customer and time, smile confidently knowing you have a updating your resume with the details of your secret weapon and the job will get done.
    [Show full text]
  • From the Library of Andrew Heck
    ptg6929616 From the Library of Andrew Heck Praise for Eloquent Ruby “Reading Eloquent Ruby is like programming in Ruby itself: fun, surprisingly deep, and you’ll find yourself wishing it was always done this way. Wherever you are in your Ruby experience from novice to Rails developer, this book is a must read.” —Ethan Roberts Owner, Monkey Mind LLC “Eloquent Ruby lives up to its name. It’s a smooth introduction to Ruby that’s both well organized and enjoyable to read, as it covers all the essential topics in the right order. This is the book I wish I’d learned Ruby from.” —James Kebinger Senior Software Engineer, PatientsLikeMe www.monkeyatlarge.com “Ruby’s syntactic and logical aesthetics represent the pinnacle for elegance and beauty ptg6929616 in the ALGOL family of programming languages. Eloquent Ruby is the perfect book to highlight this masterful language and Russ’s blend of wit and wisdom is certain to entertain and inform.” —Michael Fogus Contributor to the Clojure programming language and author of The Joy of Clojure From the Library of Andrew Heck This page intentionally left blank ptg6929616 From the Library of Andrew Heck ELOQUENT RUBY ptg6929616 From the Library of Andrew Heck Addison-Wesley Professional Ruby Series Obie Fernandez, Series Editor Visit informit.com/ruby for a complete list of available products. ptg6929616 he Addison-Wesley Professional Ruby Series provides readers Twith practical, people-oriented, and in-depth information about applying the Ruby platform to create dynamic technology solutions. The series is based on the premise that the need for expert reference books, written by experienced practitioners, will never be satisfied solely by blogs and the Internet.
    [Show full text]
  • ABSTRACT Combining Static and Dynamic Typing in Ruby Michael
    ABSTRACT Title of dissertation: Combining Static and Dynamic Typing in Ruby Michael Furr Doctor of Philosophy, 2009 Dissertation directed by: Professor Jeffrey S. Foster Department of Computer Science Many popular scripting languages such as Ruby, Python, and Perl are dynam- ically typed. Dynamic typing provides many advantages such as terse, flexible code and the ability to use highly dynamic language constructs, such as an eval method that evaluates a string as program text. However these dynamic features have tra- ditionally obstructed static analyses leaving the programmer without the benefits of static typing, including early error detection and the documentation provided by type annotations. In this dissertation, we present Diamondback Ruby (DRuby), a tool that blends static and dynamic typing for Ruby. DRuby provides a type language that is rich enough to precisely type Ruby code, without unneeded complexity. DRuby uses static type inference to automatically discover type errors in Ruby programs and provides a type annotation language that serves as verified documentation of a method's behavior. When necessary, these annotations can be checked dynamically using runtime contracts. This allows statically and dynamically checked code to safely coexist, and any runtime errors are properly blamed on dynamic code. To handle dynamic features such as eval, DRuby includes a novel dynamic analysis and transformation that gathers per-application profiles of dynamic feature usage via a program's test suite. Based on these profiles, DRuby transforms the program before applying its type inference algorithm, enforcing type safety for dynamic constructs. By leveraging a program's test suite, our technique gives the programmer an easy to understand trade-off: the more dynamic features covered by their tests, the more static checking is achieved.
    [Show full text]
  • The Art of Rails (2008).Pdf
    The Art of Rails® Edward Benson Wiley Publishing, Inc. The Art of Rails® Acknowledgments .................................................................. xi Introduction ...................................................................... xix Chapter 1: Emergence(y) of the New Web ..............................................1 Chapter 2: The Rails Concept ....................................................... 21 Chapter 3: The Server as an Application .............................................. 45 Chapter 4: Getting the Most from M, V, and C ........................................ 59 Chapter 5: Beautiful Web APIs ...................................................... 89 Chapter 6: Resources and REST .................................................... 115 Chapter 7: The Five Styles of AJAX ................................................. 139 Chapter 8: Playing with Blocks..................................................... 167 Chapter 9: Mixins and Monkey Patching ............................................ 197 Chapter 10: Code That Writes Code (That Writes Code)............................... 225 Chapter 11: How I Learned to Stop Worrying and Love the Schema ..................... 253 Chapter 12: Behavior-Driven Development and RSpec ................................ 275 Index ........................................................................... 297 The Art of Rails® Edward Benson Wiley Publishing, Inc. The Art of Rails® Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com
    [Show full text]
  • Pyconsg 2013 Documentation Release 0.1.0
    PyconSG 2013 Documentation Release 0.1.0 Calvin Cheng April 20, 2015 Contents 1 General concepts: concurrency, parallelism, threads and processes3 1.1 What’s the difference between concurrency and parallelism?......................3 1.2 What’s a coroutine?...........................................3 1.3 What is a thread?.............................................3 1.4 What is a process?............................................4 1.5 What’s the difference between threads and processes?.........................4 1.6 What does that mean in the context of a python application?......................5 1.7 If CPython python has GIL, why do we still use it?...........................5 1.8 So we cannot execute in parallel with python?.............................5 1.9 Advanced distributed, parallel computing with python.........................6 2 What is gevent? 7 2.1 libevent..................................................7 2.2 libev...................................................8 2.3 greenlets.................................................9 2.4 gevent API design............................................9 2.5 gevent with other python extensions...................................9 2.6 gevent’s monkey patch..........................................9 2.7 gevent with webservers.......................................... 10 2.8 gevent with databases.......................................... 11 2.9 gevent with I/O operations........................................ 11 2.10 gevent code example........................................... 12
    [Show full text]
  • Macruby on Ios – Rubymotion Review What I Like About Rubymotion
    MacRuby on iOS – RubyMotion review Posted by Matt Aimonetti in ruby on May 4th, 2012 Yesterday, RubyMotion was released and let’s be honest, it is one the best alternatives to Objective-C out there (if not the best). RubyMotion is a commercial, proprietary fork of MacRuby that targets iOS. This is not a small achievement, MacRuby relies on Objective C’s Garbage Collector (libauto) which is not available on iOS. Static compilation and new memory management solution was required to target the iOS platform . The new runtime had to be small and efficient. Furthermore, being able to run code on iOS isn’t enough, you need tools to interact with the compiler, to debug, to packages applications etc… I don’t think anyone will contest the fact that RubyMotion is a well done product. The question however is, “is it worth for you to invest some money, time and energy in this product instead of using Apple’s language and tools“. In this article, I’ll try to balance the pros and cons of RubyMotion so you can have a better understanding of what RubyMotion could mean for you. As a disclaimer I should say that I was beta testing RubyMotion, that they are strong ties between RubyMotion and the MacRuby project I’m part of and finally that having MacRuby on iOS has been something I’ve been looking forward for a very long time. Over the last few months I’ve seen RubyMotion take shape and finally hit the big 1.0. As you can see from Twitter and HackerNews, the Ruby community is excited about being able to use their language to write statically compiled, native iOS apps.
    [Show full text]