The Complete Guide to Rails Testing

If you've tried to learn Rails testing, maybe you've been stuck on these common testing questions...

"What should I write tests for?"

You know you should be testing but you're not sure exactly what to test. The advice you've read doesn't seem to apply when the rubber meets the road.

How can I make testing a habitual part of my development workflow?

Maybe you conceptually understand how to write tests but you still aren't actually doing it. What's the difference between you and the people who write tests for all their code? Do they just have more discipline? What's the secret?

"What test framework should I use, MiniTest or RSpec?"

You know that MiniTest and RSpec are the two most popular testing frameworks for Rails, but you're not sure how to decide which one to use. There seem to be good (and strongly expressed!) arguments on both sides. How do you pick?

What level of test coverage do I need?

You've seen the tools that measure code coverage but you're not sure how much is really needed. 100%? 60%? 80%? Is there such a thing as too much testing?

Do I need to be doing TDD 100% of the time in order to be doing it "right"?

You've heard about test-driven development, and maybe you've even done a little TDD, but it's not clear how to do TDD all the time. Do you have to do TDD all the time in order to be a "real" tester? Is TDD even a good thing?

What are the various Rails testing tools and how do I use them?

Factory Bot, Faker, RSpec, VCR, WebMock...there are so many testing tools. What are they all for? Do you need them all?

Imagine what it would feel like to have really strong testing skills

You'd write tests as easily as you write regular code.

When you're comfortable with testing, you don't have to think hard about it. The tests just flow out. In fact, all your coding gets easier, because the tests you write help guide you forward.

You wouldn't have to force yourself to write tests because testing is just a habit.

To developers who are good at testing, writing tests isn't an extra chore. Writing tests isn't something they have to remember to do. It's just a normal part of the coding process. Furthermore, it's a fun and enjoyable part of the coding process.

You would choose your testing tools with confidence.

When you understand what the available testing tools are and why different teams choose different tools, it becomes easy to make the right choice for yourself. You can make the decision once and never worry about it again.

You would know how to do TDD and when to use it.

It would be 100% clear to you how to TDD any feature—IF you wanted to. And when you don't want to TDD a feature, you'll know why you're making that choice.

Introducing: the Complete Guide to Rails Testing

229 Pages, E-book Format

The Complete Guide to Rails Testing

Contains the solutions to your testing problems

  • What are the different kinds of Rails tests?
  • What are all the Rails testing tools and how do I use them?
  • Which testing framework should I use (RSpec or Minitest)?
  • How can I make testing a habitual part of my development work?
  • What level of test coverage should I shoot for?
  • How do I add tests to an existing Rails project?
  • Much more

What's in the book

The different kinds of Rails tests
There are several different types of RSpec tests you can use. I show which ones to use and which ones to skip.
The various Rails testing tools and how to use them
Covers RSpec, Factory Bot, Capybara, VCR and WebMock.
How to decide which testing framework to use
Explains how to decide between the two big testing frameworks, RSpec and MiniTest.
How to make testing a habit
It's not enough to know how to write tests, you actually have to do it. I show you how to make testing a habit.
What level of test coverage to shoot for
Shows what level of test coverage to shoot for (hint: it's not a number).
How to add tests to an existing Rails project
Adding tests to an existing Rails project is a whole different ballgame from testing a greenfield app. I show you how.
How to set up a new Rails project for testing
I show you exactly how I set up all my new Rails projects.
How to decide when to do test-driven development
Are you testing "wrong" if you don't do TDD? I show you my approach to test-driven development.
Ruby DSLs (domain-specific languages)
Gain a solid understanding of how DSLs (domain-specific languages) work so you can understand the DSLs of RSpec, Factory Bot and Capybara.
Factory Bot
Installation, configuration, factory definitions, nested factories, traits, callbacks and transient attributes.
RSpec Syntax
Ruby blocks, let and let! vs. instance variables, describe and context, RSpec's DSL.
System Specs
When to write system specs, how to write system specs, a formula for writing system specs for most features.
Model Specs
What kinds of model specs to write and what kinds not to, the difference between testing implementation and behavior, much more.
Request Specs
What request specs are, the scenarios where request specs are useful vs. where they're not.
Mocks and Stubs
Test doubles, the difference between mocks and stubs, when to use mocks and stubs.
VCR and WebMock
Why to use VCR and WebMock, installation and configuration, how to use VCR and WebMock.

Video Course: Ruby DSLs Demystified

The Complete Guide to Rails Testing optionally comes with a video course called Ruby DSLs Demystified.

You can think of Ruby DSLs Demystified as a prerequisite to deeply understanding RSpec, Factory Bot, Capybara and other DSL-heavy testing tools.

Why I created this course

Learning Rails testing is hard. In addition to learning testing principles and developing testing habits, you have to learn a bunch of tools including RSpec, Capybara and Factory Bot.

When most people see tests for the first time that use these tools, they're totally confused. The code looks like magic. It's unclear what's what, how it works, or why it works that way.

And because most Ruby developers have never had a reason to deeply learn how Ruby DSLs work, it's unclear where the "DSL stuff" ends and where the "RSpec stuff" (or Capybara stuff or Factory Bot stuff) begins. It's just one big confusing bowl of "code soup".

That's why I created Ruby DSLs Demystified. Once you understand Ruby DSLs, you can look at a piece of code and see "that part is DSL syntax, that part is just Ruby, and that other part is specific to Factory Bot". The noise melts away and you can see everything for what it really is.

Here are the details of what's covered in Ruby DSLs Demystified.

What's in the course

Ruby DSLs Demystified is comprised of seven concise, information-dense lessons which each provide a deep dive into an area of Ruby DSLs. Here's a description of each lesson in the course.

Understanding Ruby Proc objects. You probably already use Proc objects all the time, although you might not realize it. In this lesson we cover what a Proc object is. We look at a Proc object "hello world". We also take the Proc object definition from the official Ruby docs and break it down bit-by-bit to make it understandable.

Understanding Ruby blocks. Blocks are a ubiquitous and fundamental concept in the Ruby language, although many Ruby developers don't have a solid understanding of them. In this lesson we discuss what a block is and we look at how blocks are used in several native Ruby methods like map and times. We also carry out an exercise where we write our own method that takes a block.

Understanding Ruby closures. Many discussions of closures use "computer-sciency" language that makes closures seem like a lofty, complicated concept. In this lesson we'll discuss closures in plain, easily-understandable words. We'll also look at some illustrations in code so that, by the time we're done, no stone in left unturned.

The difference between procs and lambdas in Ruby. Procs and lambdas are very similar entities in Ruby, although they're not exactly the same. In this lesson we'll go over the differences one-by-one.

What the & in front of &block means. Among the things that can make Ruby DSL syntax seem mysterious and magical is the & at the beginning of &block. In this lesson we look at the function the ampersand serves and we look at a few code examples to illustrate what's going on.

How and why to use Ruby's method_missing. method_missing is very commonly used in Rails testing libraries like RSpec and Factory Bot. In this lesson we discuss what method_missing is and how it works. Includes a brief tutorial in which we write our own program that uses method_missing.

How Ruby's instance_exec works instance_exec is one of the big reasons why the DSLs for RSpec and Factory Bot look the way they do. Understanding how instance_exec works can provide a lot of clarity when looking at code that uses these libraries. In this lesson we discuss how instance_exec works as well as build a small code example as an illustration.

Understanding Ruby Proc objects

8:42

Understanding Ruby blocks

7:46

Understanding Ruby closures

6:00

The difference between procs and lambdas in Ruby

2:55

What the & in front of &block means

4:04

How and why to use Ruby's method_missing

8:06

How Ruby's instance_exec works

3:43

Ruby DSLs Demystified: Free Sample

Here's the first video of the course, "Understanding Ruby Proc objects".

Complete Guide to Rails Testing: Table of Contents

  • Chapter 1: Introduction
    1. Who this book is for
    2. What’s in this book
    3. How to use this book
  • Chapter 2: Fundamentals: Intro to Testing Principles
    1. Overview
    2. How to make testing a habit
      1. Motivator 1: laziness
      2. Motivator 2: fear
      3. Motivator 3: pride
      4. Takeaways
    3. What level of test coverage to shoot for
      1. Pains that tell you your test coverage might be insufficient
    4. Test-driven development (TDD) vs. testing without TDD
      1. Testing != TDD
      2. Learning vs. incorporating
      3. TDD is beneficial but optional
      4. I don’t always practice TDD
      5. Takeaways
  • Chapter 3: Fundamentals: Rails Testing Tools
    1. Overview
    2. RSpec vs. Minitest: which framework to learn
      1. Usually, someone else decides for you
      2. Usually, they’ve chosen RSpec
      3. What does this mean?
      4. Also, it doesn’t matter much
      5. So try both
      6. But if you just want me to pick for you, I say RSpec
    3. Rails testing tools and how to use them
      1. RSpec
      2. Factory Bot
      3. Capybara
      4. VCR and WebMock
    4. The different kinds of RSpec tests and when to use each
      1. The eight types of RSpec specs
      2. Spec types I always use
      3. Spec types I rarely use
      4. Spec types I never use
    5. Adding tests to an existing project vs. starting fresh
      1. If you have little testing experience
      2. If you’re already comfortable with testing
  • Chapter 4: Fundamentals: Your First Practice Tests
    1. Overview
    2. Setting up a new Rails project for testing
      1. My application template
      2. The setup process
      3. The gems
      4. Next steps
    3. A Rails testing “hello world” using RSpec and Capybara
      1. What we’re going to do
      2. Creating our static page
      3. Writing our test
      4. Run the test
  • Chapter 5: Ruby DSLs: Introduction
  • Chapter 6: Ruby DSLs: Blocks
    1. Native Ruby methods that take blocks
      1. Method: times
      2. Method: each
      3. Method: map
      4. Method: tap
    2. Custom methods that take blocks
      1. An HTML generator
      2. The method definition
      3. Adding an argument to the block
    3. The technical details of blocks
    4. Takeaway
  • Chapter 7: Ruby DSLs: Proc Objects
    1. What we’re going to do and why
    2. A Proc object “hello world”
    3. Understanding Proc objects more deeply
      1. The official Ruby docs’ definition of Proc objects
      2. The Ruby Proc object definition, broken into chunks
      3. A Proc object is an encapsulation of a block of code
      4. A Proc object can be stored in a local variable
      5. A Proc object can be passed to a method or another Proc
      6. A Proc object can be called
    4. Closures
    5. Proc objects and blocks
    6. Proc objects and lambdas
    7. Takeaways
  • Chapter 8: Ruby DSLs: Closures
    1. Why you’d want to know about Ruby closures
    2. What a closure is
    3. First point: “A closure is a record”
    4. Second point: “which stores a function”
    5. Third point: “plus (potentially) some variables”
    6. Takeaways
  • Chapter 9: Ruby DSLs: The difference between procs and lambdas
    1. Overview
    2. The behavior of “return”
    3. Argument handling
      1. Argument matching
      2. Array deconstruction
    4. Takeaways
  • Chapter 10: Ruby DSLs: What the ampersand in front of &block means
    1. Blocks and Proc objects
      1. Converting the Proc object to a block before passing the Proc object
    2. The differences between blocks and Proc objects
      1. First way: put it inside a Proc object
      2. Second way: use it to call a method that takes a block
    3. Why converting a block to a Proc object is necessary
    4. Takeaways
  • Chapter 11: Ruby DSLs: The two common ways to call a Ruby block
    1. The first way: block.call
    2. The second way: yield
    3. Takeaways
  • Chapter 12: Ruby DSLs: How instance_exec works
    1. Passing arguments to blocks
    2. Executing a block in a different context
    3. How this works
    4. Why instance_exec is useful
    5. Takeaways
  • Chapter 13: Ruby DSLs: How and why to use method_missing
    1. Why method_missing exists
    2. Arbitrary attribute setter example
      1. A plain User object
      2. Adding method_missing
      3. Parsing the attribute name
      4. Setting the attribute
    3. A note about blocks
    4. Takeaways
  • Chapter 14: Factory Bot: Introduction
    1. Overview
    2. What Factory Bot is
    3. Factories, fixtures and manual test data creation
      1. Manual data creation
      2. Factories
      3. Fixtures
      4. Which is best?
  • Chapter 15: Factory Bot: Getting Started
    1. Installing Factory Bot
    2. Factory definitions
    3. Where to put factory definitions
    4. Factory Bot hello world
    5. Configuring Factory Bot with RSpec
  • Chapter 16: Factory Bot: Build Strategies and Faker
    1. Build strategies
    2. Using Factory Bot with Faker
  • Chapter 17: Factory Bot: Advanced Usage
    1. Introduction
    2. Nested factories
      1. Physician user example
      2. Options for addressing this challenge
      3. How nested factories work
    3. Traits
    4. When to use traits versus nested factories
      1. “Is” versus “has”
    5. Callbacks
      1. The various callback types
    6. Transient attributes
      1. PDF file attachment example
      2. An example without using transient attributes
      3. An example with transient attributes
      4. What’s next
  • Chapter 18: RSpec Syntax: Introduction
  • Chapter 19: RSpec Syntax: The Structure of a Test
    1. The purpose of each test phase
      1. Setup
      2. Exercise
      3. Assertion
      4. Teardown
    2. A concrete example
  • Chapter 20: RSpec Syntax: Let, Let! and Instance Variables
    1. The purpose of let and the differences between let and instance variables
      1. Differences between let and instance variables
    2. How let works and the difference between let and let!
      1. How let works
      2. An example method
      3. Memoization
      4. The lazy evaluation of let vs. the immediate evaluation of let!
    3. Takeaways
  • Chapter 21: RSpec Syntax: The Parts of an RSpec Test
    1. What we’re going to do in this chapter
    2. The example code
      1. An “emphasize” method
      2. The test for the emphasize method
    3. Specs, examples, “example groups” and “it blocks”
      1. Tests vs. specs
      2. Example groups
      3. Examples and “it blocks”
    4. The expect keyword
      1. The eq matcher
    5. What’s next
  • Chapter 22: RSpec Syntax: Build Your Own RSpec, Part 1
    1. What we’re going to do
    2. Step 1: expect
      1. Beginning the process
    3. Organizing our files
    4. What’s next
  • Chapter 23: RSpec Syntax: Build Your Own RSpec, Part 2
    1. The goal
    2. The implementation
      1. Adding the outer block
  • Chapter 24: RSpec Syntax: Describe and Context
    1. When I use describe
    2. When I use context
  • Chapter 25: System Specs: Introduction
    1. What this section will cover
    2. What system specs are
    3. When to write system specs
    4. The tools that support system specs
    5. Why I recommend against using Cucumber
      1. Why Cucumber is bad when it’s not used as intended
      2. Why Cucumber is bad even when it is used as intended
    6. The difference between system specs and feature specs
      1. Two levels of Rails tests
      2. From feature spec to system spec
      3. Summary
  • Chapter 26: System Specs: Getting Started
    1. Installing Capybara and related tools
    2. RSpec + Capybara “hello world” revisited
    3. Logging the user in before tests
      1. Log in before each test or log in once before all tests?
    4. Headless vs. not headless
  • Chapter 27: System Specs: Writing Specs for CRUD Features
    1. The three integration test cases I write for any Rails CRUD feature
    2. Creating a record with valid inputs
    3. Trying to create a record with invalid inputs
    4. Updating a record
  • Chapter 28: System Specs: Tutorial
    1. Tutorial overview
      1. Project description
      2. Tutorial outline
    2. Setting up our Rails project
    3. Writing our integration tests
      1. Creating the city resource
      2. Integration tests for City
      3. Writing the first system spec (creating a city)
      4. Verifying that the test actually does its job
      5. Integration test for trying to create a city with invalid inputs
      6. Integration test for updating a city
      7. Integration test for deleting a city
  • Chapter 29: System Specs: Capybara’s Domain-Specific Language (DSL)
    1. Navigation
    2. Clicking links and buttons
    3. Interacting with forms
      1. Text inputs
      2. Select inputs
      3. Checkboxes
      4. Radio buttons
    4. Finding content on the page
  • Chapter 30: System Specs: Simplifying Test Code with Page Objects
    1. The challenge of keeping test code clean
    2. What a Page Object is and when it’s helpful
    3. A Page Object example
    4. The obscure test
      1. What’s next
  • Chapter 31: Model Specs: Introduction
    1. The purpose of model specs
      1. Implementation vs. behavior
      2. Common errors of testing implementation instead of behavior
      3. The value of loose coupling
    2. Meaningful model specs vs. pointless model specs
      1. Testing the presence of associations
      2. Testing that a model responds to certain methods
      3. Testing for the presence of callbacks
      4. Testing for database columns and indexes
      5. Tips for writing valuable RSpec tests
    3. Why I don’t recommend Shoulda matchers
      1. What Shoulda is
      2. Test behavior, not implementation
      3. Takeaway
  • Chapter 32: Model Specs: Tutorial, Part One
    1. What a model is
    2. Why model specs are different from other types of specs
    3. The tutorial
      1. Learning objectives
      2. The scenario
      3. The approach
      4. The shell of the spec and PhoneNumber class
      5. Our first test
      6. The other two formats
  • Chapter 33: Model Specs: Tutorial, Part Two
    1. Prerequisites
    2. The tutorial
      1. Learning objectives
      2. The scenario
      3. The PhoneNumber model
      4. Our first test case
      5. The other two formats
      6. Refactoring
    3. Takeaways
    4. What’s next
  • Chapter 34: Request Specs
    1. When I use request specs and when I don’t
      1. Controller specs vs. request specs
      2. I only use request specs in three scenarios
      3. Scenario 1: legacy projects
      4. Scenario 2: APIs
      5. Scenario 3: it’s too awkward or costly to write a feature spec
    2. What’s next
  • Chapter 35: Mocks and Stubs
    1. The problem with testing terminology
    2. Test doubles
    3. Stub explanation
    4. Mock explanation
    5. The difference between mocks and stubs
    6. Example application code
    7. Stub example
    8. Mock example
    9. Why I don’t often use mocks or stubs in Rails
    10. What’s next
  • Chapter 36: VCR and WebMock
    1. Introduction
      1. Why VCR and WebMock exist
      2. The difference between VCR and WebMock
    2. Using WebMock
      1. Installation
      2. Disabling network connections
      3. Stubbing a request
    3. Using VCR
      1. Installation
      2. Configuration
      3. Recording a cassette
    4. Tutorial
    5. What we’re going to do
      1. The scenario
      2. WebMock
      3. VCR
    6. The feature
      1. The test
    7. Installing and Configuring WebMock
      1. Seeing the test fail
    8. Installing and Configuring VCR
      1. Adding VCR to our test
    9. Takeaways
  • Chapter 37: Conclusion

Testimonials

Before I read Jason's book, a majority of my (admittedly small) test suite was failing. The structure of the book and attention to the details of testing I couldn't find anywhere else make it one of the best resources for testing in Rails out there. I was able to get all of my tests passing and even add a couple new ones over the course of one weekend.

- Ry Kulp

Jason, I started reading your book and so far it is amazing. I'm only about 30 pages in but the language you use is very easy to understand and you start from the most basic level while explaining the why's. I wish I read this years ago! Thank you so much.

- Julie J

Before reading the book, I had little understanding of testing, but the book helped me write my first test within an hour. The material is set out to be progressively deeper, and after re-reading it a few times I'm still learning. Great book.

- Mederic Mesle

I already had some experience with testing but I really enjoyed the book that help me understood the different kind of tests I could find in a Rails app and better assess when to use them. It also helped me to better understand how rspec works under the hood and I loved the explanations given to present mocks and stubs. I've since recommended the book to several developers.

- Thomas Pouillevet

The whole testing ecosystem was overwhelming. I understood that "testing" is a solid way to ensure code integrity but the whole thing still seemed ominous. Your book "The Complete Guide to Rails Testing" answers all the questions and gave me a clear path to getting testing into my teams workflow and applications.

- Rick Smoke

I had not used rails for a couple years so this was really an excellent refresher. The information was well thought out and very direct in terms of do's and don'ts. I found it much easier to review this way. Jason presents things in a way that is very straightforward, building on information already learned.

- Bailey Weathers

I just finished reading "The Complete Guide to Rails Testing," and I loved it. It goes direct to the point. I also liked that Jason explained testing terminology and historical changes in RSpec.

- Emanuel Farias

Reading The Complete Guide to Rails Testing has been invaluable in helping me become a better developer. There is still so much I can take away from the book that I continue to reference it during my workday. If you are serious about becoming a better developer, then I highly recommend that you read this book.

- Aweys Ahmed

Wouldn't be nearly this comfortable testing without Jason's resources. I highly recommend folks buy his book.

- Mikhail Grigoriev

I struggled with testing for a while. What should I test? How do I write them? I tried other resources but The Complete Guide to Rails Testing offers a practical approach in plain English. I love the Build Your Own RSpec section. It breaks down all the RSpec syntax as you recreate each keyword one method at a time. Not only is the book easy to understand, but it’s honestly a lot of fun to work through!

- Daniel Murphy

Hi Jason, I have purchased your book. Looking forward to reading it fully, learning and follow-through. Thanks for putting this together. I liked your writing style and explaining things in simple way.

- Rohan Daxini

Thank you, Jason, for writing The Complete Guide to Rails Testing. This is the first resource that I feel has actually helped me wrap my head around testing.

- Lee Stetson

Your Chapter 9 on ampersands in front of &block is really well put together, Jason. You helped build up what's going on bit by bit and the implication at the end wraps it up super nicely. Well done. It made me feel like I had circled that concept and everything I needed to know on the subject was laid out.

- Pascal Laliberté

Thanks Jason, your book has been a very valuable resource for me in leveling up my testing skills!

- Joseph Clarke

Purchase the Complete Guide to Rails Testing

Choose a package below to get instant access to the Complete Guide to Rails Testing.

Team Package

Book + Course + Slack Access (for Businesses)

  • The Complete Guide to Rails Testing ebook
  • Ruby DSLs Demystified video course
  • Code with Jason Slack access - chat with other Rails devs
  • Up to 10 developers may access the material
  • Custom invoicing for your financial records
Buy Now ($269)
Comes with 100% money-back guarantee

Professional Package

Book + Course + Slack Access (for Individuals)

  • The Complete Guide to Rails Testing ebook
  • Ruby DSLs Demystified video course
  • Code with Jason Slack access - chat with other Rails devs
  • Custom invoicing for your financial records
  • Up to 10 developers may access the material
Buy Now ($119)
Comes with 100% money-back guarantee

Basic Package

Book + Slack Access

  • The Complete Guide to Rails Testing ebook
  • Code with Jason Slack access - chat with other Rails devs
  • Ruby DSLs Demystified video course
  • Up to 10 developers may access the material
  • Custom invoicing for your financial records
Buy Now ($49)
Comes with 100% money-back guarantee

FAQs

How long is the book?

The book is 229 pages long.

What's the format of the book?

When you purchase, you get a zip file containing PDF, EPUB and MOBI formats. No print version as of now.

What testing frameworks and tools are covered?

RSpec, Capybara, Factory Bot, and Faker (no Minitest). What's more important than the testing framework or other tools though are the testing principles covered that apply no matter what set of tools you're using.

What versions of Rails/RSpec are covered?

There's nothing in the book that's version-specific.

When was the book last updated?

The book was last updated in August of 2022.

What if I buy it and I don’t like it? Do I get my money back?

Yes. I offer a 100% no-questions-asked money-back guarantee.

Get a Free Sample

Not ready to buy yet? Here's a free sample of what's in the book.

About the Author

I'm Jason Swett. I'm a developer, speaker, trainer, author and host of The Code with Jason Podcast.

I've taught programming classes and given tech talks all over the US and the world, including conferences like RailsConf, RubyConf, RubyConf India and RubyHACK. My corporate teaching clients have included Deloitte, VMware, Liberty Mutual and HP.

I've spoken or taught in the US, India, Nigeria, Bulgaria and the Netherlands.