• Stars
    star
    2,150
  • Rank 21,457 (Top 0.5 %)
  • Language
    Ruby
  • License
    MIT License
  • Created about 10 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

RSpec cheatsheet & Rails app: Learn how to expertly test Rails apps from a model codebase

RSpec Rails Examples Build Status Join the chat at https://gitter.im/eliotsykes/rspec-rails-examples

An RSpec cheatsheet in the form of a Rails app. Learn how to expertly test Rails apps from a model codebase

A small yet comprehensive reference for developers who want to know how to test Rails apps using RSpec.

Here you'll find in-depth examples with detailed documentation explaining how to test with RSpec and related testing gems, which you can then apply to your own projects.

This application was originally written for the benefit of the developers I coach, who've found it a useful memory aid and catalyst for when they're learning RSpec. Now I'd like to get feedback from the wider community.

The repo contains examples of various spec types such as feature, mailer, and model. See the spec/ directory for all the example specs and types.

In the README below, you'll find links to some of the most useful cheatsheets and API documentation available for RSpec users.

See the well-commented files in the spec/support directory for walkthroughs on how to configure popular testing gems, such as DatabaseCleaner, Capybara, and FactoryGirl.

Hopefully this will be of help to those of you learning RSpec and Rails. If there's anything missing you'd like to see covered in the project, please submit your request via the issue tracker, I'd be happy to help — Eliot Sykes

PS. Interested in growing your skills and supporting this project? Learn with the TDD Masterclass, get Test Coverage First Aid for your app, or grow with one-to-one coaching for Rails developers.


Support Configuration

The tests rely on this configuration being uncommented in spec/rails_helper.rb, you probably want it uncommented in your app too:

# Loads `.rb` files in `spec/support` and its subdirectories:
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

(The rspec-rails installer generates this line, but it will be commented out.)

Run Specs in a Random Order

In a dependable, repeatable automated test suite, data stores (such as database, job queues, and sent email on ActionMailer::Base.deliveries) should return to a consistent state between each spec, regardless of the order specs are run in.

For a maintainable, predictable test suite, one spec should not set up data (e.g. creating users) needed by a later spec to pass. Each spec should look after its own test data and clear up after itself. (NB. If there is reference data that all tests need, such as populating a countries table, then this can go in db/seeds.rb and be run once before the entire suite).

The specs run in a random order each time the test suite is run. This helps prevent the introduction of run order and test data dependencies between tests, which are best avoided.

Random order test runs are configured using the config.order = :random and Kernel.srand config.seed options in spec/spec_helper.rb.

Testing Production Errors

When errors are raised, the Rails test environment may not behave as in production. The test environment may mask the actual error response you want to test. To help with this, you can disable test environment exception handling temporarily, spec/support/error_responses.rb provides respond_without_detailed_exceptions. See it in use in spec/api/v1/token_spec.rb to provide production-like error responses in the test environment.

Testing Rake Tasks with RSpec

RSpec testing Rake task configuration and example:

Pry-rescue debugging

pry-rescue can be used to debug failing specs, by opening pry's debugger whenever a test failure is encountered. For setup and usage see pry-rescue's README.

Time Travel Examples

ActiveSupport::Testing::TimeHelpers provides helpers for manipulating and freezing the current time reported within tests. These methods are often enough to replace the time-related testing methods that the timecop gem is used for.

TimeHelpers configuration how-to and examples:

ActiveJob Examples

ActiveJob::TestHelper provides help to test ActiveJob jobs.

ActiveJob::TestHelper configuration how-to and examples:

Database Cleaner Examples

Database Cleaner is a set of strategies for cleaning your database in Ruby, to ensure a consistent environment for each test run.

Database Cleaner configuration how-to:

Factory Girl Examples

Factory Girl is a library to help setup test data. factory_girl_rails integrates Factory Girl with Rails.

Factory Girl configuration how-to and examples:

VCR Examples

VCR records your test suite's HTTP interactions and replays them during future test runs. Your tests can run independent of a connection to external URLs. These HTTP interactions are stored in cassette files.

VCR configuration how-to and examples:

Capybara Examples

Capybara helps you write feature specs that interact with your app's UI as a user does with a browser.

Capybara configuration how-to and examples:

Puffing Billy Examples

Puffing Billy is like VCR for browsers used by feature specs. Puffing Billy is a HTTP proxy between your browser and external sites, including 3rd party JavaScript. If your app depends on JavaScript hosted on another site, then Puffing Billy will keep a copy of that JavaScript and serve it from a local web server during testing. This means tests dependent on that JavaScript will carry on working even if the original host cannot be connected to.

If you need to debug Puffing Billy, refer to its output in log/test.log.

Puffing Billy configuration how-to and examples:

Shoulda-Matchers Examples

Shoulda-matchers make light work of model specs.

shoulda-matchers configuration how-to and examples:

Email-Spec Examples

The "Subscribe to newsletter" feature was developed with help from email_spec

email_spec configuration how-to and examples:

Devise Examples

Specs testing registration, sign-in, and other user authentication features provided by Devise:

Custom Matchers

You can write your own custom RSpec matchers. Custom matchers can help you write more understandable specs.

Custom matchers configuration how-to and examples:

RSpec-Expectations Docs

RSpec-Mocks Specs & Docs

RSpec-Rails

See RSpec Rails for installation instructions.

Matchers

Generators

Feature Specs & Docs

API Request Specs, Docs, & Helpers

Mailer Specs & Docs

Controller Specs & Docs

View Specs & Docs

Helper Specs & Docs

Routing Specs & Docs

Validator Specs

To test a custom validator you've written, refer to these validator specs from other Rails projects. These specs each follow a similar pattern where the validator is tested with a dummy model that is defined and used within the spec only. Using a dummy model is usually preferable to writing a validator spec that is dependent on a real model.

Related task: Demonstrate Validator Specs within rspec-rails-examples

Enable Spring for RSpec

Spring is a Rails application preloader. It speeds up development by keeping your application running in the background so you don't need to boot it every time you run a new command.

To take advantage of this boost when you run bin/rspec, the spring-commands-rspec gem needs to be installed and a new rspec binstub needs to be created:

# 1. Add `spring-commands-rspec` to Gemfile in development and test groups and
#    install gem:
bundle install

# 2. Spring-ify the `bin/rspec` binstub:
bundle exec spring binstub rspec

# 3. Stop spring to ensure the changes are picked up:
bin/spring stop

# 4. Check bin/rspec is still working:
bin/rspec

See the spring-commands-rspec README for up-to-date installation instructions: https://github.com/jonleighton/spring-commands-rspec

Automated Continuous Integration with Travis CI

Continuous Integration (CI) is the practice of integrating new code into the master branch frequently, to help detect merge conflicts, bugs, and improve the quality of the software a development team writes.

CI is usually accompanied by running an application's test suite against the latest code changes, and flagging any test failures that are found. Developers are expected to investigate and fix these failures to maintain a passing test suite and therefore quality.

Travis CI is a build server that helps automate the CI process. Travis CI runs an application's tests against the latest changes pushed to the application's code respository. In this project, Travis CI runs the project's tests (rake test) on pull requests and on changes to the master branch.

Travis CI configuration how-to and example:


Contributors

More Repositories

1

real-world-rails

Real World Rails applications and their open source codebases for developers to learn from
Ruby
1,643
star
2

rails-security-checklist

🔑 Community-driven Rails Security Checklist (see our GitHub Issues for the newest checks that aren't yet in the README)
Ruby
1,332
star
3

rack-zippy

Rack middleware for serving gzip files
Ruby
160
star
4

rails-testing-toolbox

🔧 Tools to help Rails developers test
Ruby
127
star
5

asset_fingerprint

Asset Fingerprint Plugin for Ruby on Rails - allows you to use md5 or timestamps in query string or in asset filenames as suggested by Google Page Speed
Ruby
99
star
6

awesome-challenges

Sharpen skills & prepare for interview. Includes puzzles, kata, algorithm & data structure exercises
37
star
7

monitorstxt

monitors.txt - lazy web app monitoring, see http://monitorstxt.org and http://monitorstxt.org/monitors.txt
31
star
8

spree-zoom-photos

Lightbox+Zoom product photos for your Spree store
JavaScript
27
star
9

page_cache

Holeless page caching plugin for Rails. Users never have to wait for cached pages to be generated (unlike the page caching that ships with Rails).
Ruby
26
star
10

rails-code-review

An evolving set of guidelines & supporting reasons to consider when code reviewing Ruby on Rails apps
21
star
11

rails-static-router

Enjoy static routes in your Rails config/routes.rb
Ruby
18
star
12

real-world-ember

Use the source: Read & learn from Real World Ember apps
17
star
13

rspec-katas

A friendly place for RSpec-driven Kata to gather and teach those wanting to learn the ways of RSpec.
Ruby
16
star
14

spree-single-product-urls

Extension for Spree to give each product a single URL to minimize duplicate content issues. Behaves like Amazon's "Look for similar items in these categories" product page section.
Ruby
13
star
15

spree-redirects

An extension for managing redirects within Spree
Ruby
10
star
16

spree-titles

Replaces the general Spree title with accurate titles.
Ruby
10
star
17

spree-db-tools

An extension to add a few useful Spree-related database rake tasks.
Ruby
9
star
18

less-css-jawr

Less CSS for JAWR
Java
7
star
19

spring-site-scope

Sample code to show how a site scope in Spring might work.
Java
6
star
20

6-minute-backups

Simple ruby script for securely backing up directories and mysql databases
Ruby
6
star
21

spree-i18n-db

Spree extension to override YAML translations with translations stored in the database.
Ruby
5
star
22

spree-products-page-remover

Extension for removing the /products page in Spree. Helps avoid duplicate content issues between home page and /products.
Ruby
5
star
23

acts_as_geocodable_extra

Some personal changes I needed to acts_as_geocodable - see the original project at the homepage url below
Ruby
4
star
24

rails-testing-cheatsheet

🚌 Community-driven Rails Testing Cheatsheet. Contributions welcome!
4
star
25

rails-activerecord-aerobics

[UNMAINTAINED] Boost your Rails ActiveRecord Query core fitness with this workout plan. A+ abs or your money back.
Ruby
3
star
26

rails-console-cheatsheet

Rails console cheatsheet 📝 ☺️
2
star
27

debugging-rails

🐛 Tips & links for debugging Ruby and Ruby on Rails
2
star
28

ruby-data-structures

Ruby Data Structures
2
star
29

gordonflash

Gordon Flash Grails plugin protects flash scope from being cleared out unnecessarily
Groovy
1
star
30

tools

Handy Script Collection (for Rubyists)
Shell
1
star
31

gz-compare

Compare compression file sizes for gzip with Zopfli
Ruby
1
star
32

asset_fingerprint_tester

Rails app exists purely for testing the Asset Fingerprint plugin - you probably don't want this
Ruby
1
star
33

gitbook-plugin-markrundown

Write runnable markdown documents, with superpowers for technical authors
JavaScript
1
star
34

rails-troubleshooter

Troubleshoot common Ruby on Rails issues
1
star