Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 37 ยท Testing, Jobs and Deployment

Controller, Integration and System Tests

Test Rails controllers and whole user flows with ActionDispatch::IntegrationTest and Capybara system tests. Learn assertions for responses, redirects and DOM, test doubles and a runnable Rack app test stand-in.

Model tests check one class. But a bug often lives between the pieces: a route that points to the wrong action, a view that calls a missing method, a filter that blocks the wrong user. Integration tests send a request through the whole stack (router, middleware, controller, view) and check the response. System tests go further and drive a real browser.

Real Rails integration tests need Rails and a database, so those snippets are read-only here. To let you practice the idea, the runnable examples test a tiny Rack-style app written in plain Ruby with real Minitest. Everything labelled "stand-in" is plain Ruby, not Rails.

Integration tests

Ruby
# test/integration/posts_test.rb
require "test_helper"

class PostsTest < ActionDispatch::IntegrationTest
  test "index lists published posts" do
    get posts_url
    assert_response :success
    assert_select "h2", text: posts(:first).title
  end

  test "creating a post redirects and shows a notice" do
    sign_in users(:ana)   # helper you define in test_helper.rb

    assert_difference "Post.count", 1 do
      post posts_url, params: { post: { title: "Hello", body: "World" } }
    end

    assert_redirected_to post_url(Post.last)
    follow_redirect!
    assert_select ".notice", "Post created"
  end

  test "invalid post re-renders the form with 422" do
    sign_in users(:ana)
    assert_no_difference "Post.count" do
      post posts_url, params: { post: { title: "" } }
    end
    assert_response :unprocessable_entity
    assert_select ".error", /can't be blank/
  end
end

The pieces:

  • get, post, patch, delete send a request through the full stack.
  • assert_response :success | :redirect | :not_found | 404.
  • assert_redirected_to checks the Location header; follow_redirect! goes there.
  • assert_select "css selector", text or a regex checks the HTML.
  • assert_difference / assert_no_difference check that rows were created or not.
  • session, cookies and flash are readable inside the test.

Plain ActionController::TestCase controller tests still exist but Rails recommends integration tests, because they exercise the routes and the full middleware, like a real user would.

Stand-in: test a Rack app

Rails is a Rack app: an object with call(env) that returns [status, headers, body]. The next example builds a small one, then tests it with real Minitest in the same style as an integration test, with get and assert_response helpers written by us.

Ruby Stand-in: integration-style tests for a Rack app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The last test fails on purpose, to show that the response body really is checked.

Test doubles and time

Tests must be deterministic. Two usual troublemakers are time and outside services.

Ruby
# Freeze the clock (Rails: ActiveSupport::Testing::TimeHelpers)
test "trial expires after 14 days" do
  user = users(:ana)
  travel_to user.created_at + 15.days do
    assert user.trial_expired?
  end
end

# Replace an outside call with a stub (Minitest::Mock was removed in Minitest 6; use the mocha gem or a small fake)
class FakeMailer
  attr_reader :sent
  def initialize = @sent = []
  def deliver(to:, text:) = @sent << [to, text]
end

A plain Ruby fake object, passed in as an argument, is often clearer than a mocking library. The next example does exactly that and also freezes time by passing a clock into the code instead of calling Time.now inside it.

Ruby Stand-in: fakes and an injected clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

System tests

System tests use Capybara to drive a real browser (Chrome by default) the way a user does. They are slow, so keep them for the few critical journeys: sign up, log in, check out.

Ruby
# test/system/posts_test.rb
require "application_system_test_case"

class PostsTest < ApplicationSystemTestCase
  test "writing a post" do
    visit new_post_path
    fill_in "Title", with: "My first post"
    fill_in "Body", with: "Hello from a system test"
    click_on "Create Post"

    assert_text "Post created"
    assert_selector "h1", text: "My first post"
  end
end
SH
bin/rails test:system

Capybara waits for elements to appear, so you rarely sleep. On failure Rails saves a screenshot in tmp/screenshots. Rails also supports JavaScript-heavy pages (Turbo, Stimulus) this way, because a real browser runs the scripts.

How many of each?

Keep many fast model tests, a good set of integration tests for each controller, and just a few system tests for the main journeys. This is the "testing pyramid": the lower the layer, the faster and more plentiful the tests.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an integration test exercise that a model test does not?

    An integration test sends a request through the whole stack, so it catches routing and wiring mistakes.
  2. 2. Which assertion checks that a create action sent the user to the new record?

    assert_redirected_to compares the Location header; follow_redirect! then loads the target page.
  3. 3. Why keep system tests few?

    A browser start and real rendering make them far slower than model or integration tests.
  4. 4. What is a benefit of injecting a clock or a mailer into a class?

    A fake clock or mailer removes time and network from the test, making it repeatable.

Summary

  • Integration tests send requests through the whole stack; use get/post, assert_response, assert_redirected_to, assert_select.
  • System tests drive a real browser with Capybara; write a few for the key journeys.
  • Make tests deterministic: freeze time with travel_to or inject a clock, and replace outside services with fakes.
  • Follow the pyramid: many fast tests at the bottom, few slow ones on top.

Next: Background jobs, mail and caching