skip to content

In a Rails 8.1 app, what does bin/rails generate rspec:install create, and why do Rails specs require rails_helper instead of spec_helper?

level: juniorimportance: should knowfreq 46%

answer

  1. two helper files, two jobs
  2. .rspec carries --require spec_helper
  3. config/environment boots the whole app
  4. maintain_test_schema! before RSpec.configure
  5. fixture_paths is plural since Rails 7.1

basics

~10 s

rspec:install writes .rspec, spec/spec_helper.rb and spec/rails_helper.rb. spec_helper configures plain RSpec without Rails; rails_helper loads config/environment, requires rspec/rails and sets fixtures and transactions, so any spec touching Rails code requires rails_helper.

solid answer

~30 s

With `rspec-rails` in the `:development` and `:test` groups, `bin/rails generate rspec:install` creates `.rspec`, `spec/spec_helper.rb` and `spec/rails_helper.rb`. `.rspec` holds `--require spec_helper`, so every run loads the Rails-free helper. `rails_helper.rb` sets `RAILS_ENV` to test, loads `config/environment`, aborts if the environment is production, requires `rspec/rails`, calls `ActiveRecord::Migration.maintain_test_schema!`, and configures `fixture_paths`, `use_transactional_fixtures = true` and `filter_rails_from_backtrace!`. A model or request spec starts with `require "rails_helper"` because it needs the booted app; a spec for a plain Ruby class can stay on `spec_helper` and skip the boot. The gem's railtie also switches the generators, so `bin/rails generate model TimeEntry` writes `spec/models/time_entry_spec.rb` instead of a Minitest file.

code

ruby · 19 lines
ruby
# spec/models/time_entry_spec.rb
require "rails_helper"

RSpec.describe TimeEntry, type: :model do
  it "is invalid without minutes" do
    entry = TimeEntry.new(minutes: nil)
    expect(entry).not_to be_valid
  end
end

# spec/lib/duration_spec.rb -- plain Ruby, no Rails boot
require "spec_helper"
require_relative "../../lib/duration"

RSpec.describe Duration do
  it "formats minutes as hours" do
    expect(Duration.new(90).to_s).to eq("1h 30m")
  end
end

go deeper

for a junior

Recall the three files rspec:install writes and that any spec touching models, routes or jobs starts with require rails_helper.

for a middle

Walk through rails_helper.rb in order: environment, production guard, rspec/rails, maintain_test_schema!, then the configure block with fixture_paths and transactional fixtures.

for a senior

Explain when a spec should avoid rails_helper to keep boot cost down, and what changes if the team adds --require rails_helper to .rspec.

for a principal

Weigh one global rails_helper against split helpers for a large suite: boot time per run, consistency of configuration and how new contributors pick the right one.

## What the installer writes `rspec-rails` is the gem that wires RSpec into a Rails application. It is added to **both** the `:development` and `:test` groups of the Gemfile; the development group matters because the generators and rake tasks it adds would otherwise need `RAILS_ENV=test` in front of them. After `bundle install`, one generator sets the project up: ```bash bin/rails generate rspec:install # create .rspec # create spec # create spec/spec_helper.rb # create spec/rails_helper.rb ``` | File | What it holds | Loads Rails? | |---|---|---| | `.rspec` | command-line defaults, starting with `--require spec_helper` | no | | `spec/spec_helper.rb` | plain RSpec settings produced by RSpec's own initializer | no | | `spec/rails_helper.rb` | the Rails boot plus the rspec-rails settings | yes | The split is deliberate. `spec_helper.rb` is RSpec's own file, created by the same code that `rspec --init` runs, with the generator name swapped in its comments. Because `.rspec` requires it for every run, it must stay cheap. `rails_helper.rb` is the expensive one: it boots the whole application. ## Inside the generated rails_helper.rb Read top to bottom, the template does this: 1. `require 'spec_helper'`, so the plain settings apply first. 2. `ENV['RAILS_ENV'] ||= 'test'`, then `require_relative '../config/environment'` to boot the app. 3. `abort(...) if Rails.env.production?`, a guard so a mis-set environment cannot wipe a production database through transactional cleanup or schema loading. 4. `require 'rspec/rails'`, which loads the spec types, the Rails matchers and the fixture support. The comment underneath says "Rails is not loaded until this point!", which is where extra requires belong. 5. `ActiveRecord::Migration.maintain_test_schema!` inside a `begin`/`rescue ActiveRecord::PendingMigrationError`, so the test database is reloaded from the schema file when that file has changed, and the run aborts with the pending-migration message when migrations have not been run. 6. An `RSpec.configure` block that sets: - `config.fixture_paths = [Rails.root.join('spec/fixtures')]` (plural: Rails 7.1 added `fixture_paths` and Rails 7.2 removed the singular `fixture_path`); - `config.use_transactional_fixtures = true`, which wraps each example in a rolled-back transaction; - a commented `config.infer_spec_type_from_file_location!` line; - `config.filter_rails_from_backtrace!`, which hides Rails' own gem frames in failure output. An app generated without Active Record gets `config.use_active_record = false` instead of the fixture lines. ## Why specs require rails_helper A spec file states its own dependencies. A spec for `TimeEntry` (an Active Record model), for a route, a job or a mailer needs autoloading, the database connection and the rspec-rails example groups, so it starts with `require "rails_helper"`. A spec for a plain Ruby object, say a `Duration` value class with no Rails constants, can rely on `spec_helper` alone and runs without the boot cost. Some teams add `--require rails_helper` to `.rspec` to save a line per file; the template carries a commented `return unless Rails.env.test?` for exactly that case, so generators do not crash before migrations have run. ## What else the gem changes - **Generators.** The railtie sets `test_framework :rspec` and `integration_tool :rspec`, so `bin/rails generate model`, `controller`, `scaffold` and `job` write files under `spec/` rather than `test/`. It also offers its own `rspec:model`, `rspec:request`, `rspec:system` and similar generators. - **Rake.** It replaces the `test` prerequisite of the default task with `spec` and defines `spec` plus one task per spec directory, each preceded by `spec:prepare`, which invokes `test:prepare`. - **Support version.** rspec-rails 8 requires Rails 7.2 or newer; its README table names Rails 8.0 and 7.2, but the gemspec has no upper bound and Rails 8.1 runs on it. - **Mailer previews and stats.** When no preview path is configured, the railtie adds `spec/mailers/previews`, and on Rails 8.0 and later it registers each `spec/` subfolder with `bin/rails stats` as test code. ## A first-day checklist After installing, a new Rails 8.1 project usually does three things: 1. Commits `.rspec`, `spec/spec_helper.rb` and `spec/rails_helper.rb` unchanged, so later diffs show deliberate edits. 2. Decides whether to keep the `test/` folder that `rails new` created; with RSpec as the only framework it is usually deleted, or the app is generated with `--skip-test` in the first place. 3. Adds support code under `spec/support` and enables the commented `Rails.root.glob('spec/support/**/*.rb')` line, or requires those files explicitly from the specs that need them. ## Common slips - Requiring only `spec_helper` in a model spec and then hitting `NameError` for the model constant, because Rails never booted. - Editing `spec_helper.rb` to load Rails, which makes every pure-Ruby spec pay the boot cost. - Expecting `bin/rails test` to run the specs; the specs run through `rspec`, while `bin/rails test` runs Minitest files under `test/`.

  • What does ActiveRecord::Migration.maintain_test_schema! do in rails_helper.rb?
    It reloads the test database from the schema file when that file has changed since the test database was built, then checks for pending migrations. If migrations exist that were never run, it raises `ActiveRecord::PendingMigrationError`, and the generated `rescue` turns that into an `abort` with the message, so the run stops before any example executes against a stale schema.
  • Why does the generated rails_helper.rb abort when Rails.env.production? is true?
    Because the helper is about to load the schema into the configured database and wrap every example in transactions and fixture loads. If `RAILS_ENV` were set to production by mistake, those steps would run against the production database. The `abort` line is a cheap guard against that one catastrophic misconfiguration.

  • spec_helper.rb boots Rails, so rails_helper.rb is optional
  • rspec:install creates a test/ directory alongside spec/
  • bin/rails test runs the RSpec suite once rspec-rails is installed
  • config.fixture_path (singular) is the current setting in rails_helper.rb
  • use_transactional_fixtures is off by default in the generated helper

Assumes rspec-rails 8.0 on Rails 8.1; rspec-rails 8 requires Rails 7.2 or newer, and its template writes the plural fixture_paths that replaced fixture_path (removed in Rails 7.2).