skip to content

Test Types & Runner

Rails tests subclass ActiveSupport::TestCase or ActionDispatch::IntegrationTest and run through bin/rails test in parallel workers. Interviewers ask which type fits and how parallel runs stay apart.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

In a Rails 8.1 app, when do you subclass ActiveSupport::TestCase, ActionDispatch::IntegrationTest or ActionController::TestCase, and what does each exercise?

level: juniorimportance: must knowfreq 68%

answer

  1. three base classes, three depths
  2. model tests call Ruby directly
  3. requests through routes and middleware
  4. generators write IntegrationTest for controllers
  5. assigns lives in rails-controller-testing

basics

~20 s

ActiveSupport::TestCase is the base for model and plain-Ruby tests; ActionDispatch::IntegrationTest sends requests through routing, middleware, controller and view, and is what Rails generates for controller tests; ActionController::TestCase dispatches one action directly and is the legacy style.

solid answer

~40 s

All three subclass `ActiveSupport::TestCase`, which itself subclasses `Minitest::Test`, so they share `test "..." do`, fixtures and `parallelize` from `test/test_helper.rb`. I use `ActiveSupport::TestCase` directly for models and plain Ruby: the test calls methods on the object. For anything HTTP I use `ActionDispatch::IntegrationTest`: `get bookings_url` or `post bookings_url, params: {...}` goes through the routes, the Rack middleware, the controller and the view, and I assert on the response. That is what `bin/rails generate controller` and the scaffold write into `test/controllers`. `ActionController::TestCase` is the older functional test: `get :show, params: { id: 1 }` names an action and calls the controller's `dispatch` directly, skipping the middleware; `assigns` and `assert_template` now raise unless you add the `rails-controller-testing` gem.

code

ruby · 17 lines
ruby
# test/models/booking_test.rb
class BookingTest < ActiveSupport::TestCase
  test "rejects a departure before the arrival" do
    booking = Booking.new(spot: spots(:level_two_a),
                          arrives_at: 2.hours.from_now,
                          departs_at: 1.hour.from_now)
    assert_not booking.valid?
  end
end

# test/controllers/bookings_controller_test.rb
class BookingsControllerTest < ActionDispatch::IntegrationTest
  test "should get index" do
    get bookings_url
    assert_response :success
  end
end

go deeper

for a junior

Know which class each generated test file uses: models get ActiveSupport::TestCase, controllers get ActionDispatch::IntegrationTest, and you call get or post with a route helper.

for a middle

Explain what each class actually runs: integration requests pass through routing and middleware, while ActionController::TestCase dispatches one action directly and lets you inject session and flash.

for a senior

Argue for outcome-based integration tests over assigns and template checks, and plan how an old functional-test suite migrates without a big-bang rewrite.

for a principal

Frame the split between many cheap model tests and fewer integration tests as a cost decision for the whole team's suite runtime and refactoring freedom.

## One root, three depths Every Rails test class ends up as a subclass of **`ActiveSupport::TestCase`**, and `ActiveSupport::TestCase` subclasses **`Minitest::Test`**. Rails adds the declarative `test "rejects overlapping bookings" do ... end` form (it defines a method named `test_rejects_overlapping_bookings`), fixtures, parallel workers and its own assertions on top. What differs between the classes is **how far into the application a test reaches**. | Class | Usual folder | What the test calls | What actually runs | |---|---|---|---| | `ActiveSupport::TestCase` | `test/models` | methods on an object | the model, its validations, the database | | `ActionDispatch::IntegrationTest` | `test/controllers`, `test/integration` | `get`, `post`, `patch`, `delete` with a path or URL | routing, the middleware stack, the controller, the view | | `ActionController::TestCase` | `test/controllers` in older apps | `get :show` with an action name | one controller action, dispatched directly | ## ActiveSupport::TestCase for models and plain Ruby - `bin/rails generate model Booking` writes `test/models/booking_test.rb` as `class BookingTest < ActiveSupport::TestCase`. - The generated `test/test_helper.rb` **reopens** `ActiveSupport::TestCase` to call `parallelize(workers: :number_of_processors)` and `fixtures :all`, so every other test class inherits those settings. - The framework-specific bases are subclasses too: `ActiveJob::TestCase`, `ActionMailer::TestCase` and `ActionView::TestCase` all inherit from `ActiveSupport::TestCase`. - A model test needs no request: it builds a `Booking`, calls `valid?` or a pricing method, and asserts on the result. ## ActionDispatch::IntegrationTest for anything HTTP - The request helpers take a path or a route helper: `get bookings_url`, `post bookings_url, params: { booking: {...} }`, `patch booking_url(booking)`, plus `headers:`, `xhr:` and `as: :json` (which JSON-encodes the params and sets the content type). - Each request runs through the **whole Rails stack in the same process**: the route set, the Rack middleware (cookies, session, flash), `before_action` filters, the action and the view. - Cookies and the session **persist between requests inside one test**, so a sign-in request followed by a booking request behaves like one visitor. - You assert on outcomes: `assert_response`, `assert_redirected_to`, `response.parsed_body`, or the HTML with `assert_select`. - It does **not** open a browser or run JavaScript; browser-driven tests are a separate class (`ActionDispatch::SystemTestCase`). - `bin/rails generate controller Bookings index` and the scaffold both write `class BookingsControllerTest < ActionDispatch::IntegrationTest`. The folder is still called `test/controllers`, which is why people still say "controller tests". ## ActionController::TestCase, the older functional test - A test names the action instead of a URL: `get :show, params: { id: booking.id }, session: { user_id: user.id }`. - Rails builds a test request and calls the controller's `dispatch` directly, so **the Rack middleware stack does not run**; the test can inject `session:` and `flash:` values that real middleware would normally set. - `assigns(:booking)` and `assert_template` now raise `NoMethodError` with a message telling you to add `gem "rails-controller-testing"`. They were extracted in Rails 5, when the generators switched to integration tests. - The reasoning: a test that inspects instance variables and template names is coupled to how the action is written, and it misses failures that only appear once routing and middleware are in the path. ## Choosing in practice 1. Business rules on a model (an overlap validation, a price for a stay) go in an `ActiveSupport::TestCase`. 2. "Posting the form creates a booking and redirects to its page" goes in an `ActionDispatch::IntegrationTest`. 3. An existing `ActionController::TestCase` suite keeps working; new tests are written as integration tests, and old ones are converted when they are next touched. Integration tests cost more per test than model tests because they route and render, so the bulk of the rules belongs in model tests and a smaller number of integration tests prove the wiring. ## Mistakes interviewers listen for - **Calling the folder the class.** A file in `test/controllers` is not an `ActionController::TestCase` in a generated app; open it and read the superclass. - **Asserting internals.** Reaching for `assigns(:booking)` to check what the action loaded tests the implementation. In an integration test, assert what the visitor gets: the status, the redirect target, the rendered text. - **Testing a model rule through HTTP.** An overlap validation checked only by posting a form makes the failure slower to run and harder to read. Test the rule on the model and keep one request test for the happy path and one for the rejection. - **Expecting JavaScript to run.** Neither integration nor functional tests execute the page's scripts, so a Stimulus behaviour needs a browser-driven test.

  • Why did Rails stop generating ActionController::TestCase controller tests?
    Rails 5 switched the controller and scaffold generators to `ActionDispatch::IntegrationTest` and extracted `assigns` and `assert_template` into the `rails-controller-testing` gem. Integration tests go through routing and middleware and assert on the response, so they keep passing when the action is refactored and catch wiring failures a direct `dispatch` call hides.
  • Where do the parallelize and fixtures :all settings in test_helper.rb take effect?
    `test/test_helper.rb` reopens `ActiveSupport::TestCase` and calls them there. Because `ActionDispatch::IntegrationTest`, `ActionController::TestCase`, `ActiveJob::TestCase` and `ActionMailer::TestCase` all subclass it, every test class in the app inherits the worker count and the fixtures without repeating them.

  • New Rails apps generate controller tests as ActionController::TestCase subclasses.
  • assigns(:booking) works in a Rails 8.1 controller test without any extra gem.
  • ActionDispatch::IntegrationTest drives a real browser and runs the page's JavaScript.
  • ActionController::TestCase runs the full Rack middleware stack before the action.
  • Model tests must subclass ActionDispatch::IntegrationTest to get fixtures.
open as a page

In a Rails integration test, how do assert_response and follow_redirect! verify a booking form that redirects after a successful POST?

level: juniorimportance: should knowfreq 55%

basics

~10 s

assert_response :redirect passes for any 3xx and assert_redirected_to checks the Location; follow_redirect! then requests that Location with GET (keeping the verb on 307/308) and returns the new status for assert_response :success.

open as a page

With bin/rails test in Rails 8.1, how do you run one test by line, by name, or by folder, and what does a bare run skip?

level: middleimportance: should knowfreq 42%

basics

~20 s

bin/rails test takes paths with :line or :start-end suffixes and folders, filters by name with -i (Rails turns a test description into its method name), warns on -n, and by default skips test/system, which test:all includes.

open as a page

In a Rails 8.1 suite using parallelize(workers: :number_of_processors), how does each forked worker get its own database, and what shared state can still make tests flaky?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Rails forks one process per worker and, after each fork, appends the worker number to every test database name and loads the schema there; files, external caches and services stay shared, so isolate them in parallelize_setup.

open as a page

In a Rails 8.1 app, what do bin/ci and config/ci.rb run, and how does one failing step affect the rest of the run?

level: middleimportance: nice to knowfreq 24%

basics

~20 s

bin/ci loads ActiveSupport::ContinuousIntegration and runs the steps declared in config/ci.rb (setup, RuboCop, audits, Brakeman, bin/rails test, seeds); a failing step is reported but later steps still run, and the script exits non-zero at the end.

open as a page