Rails System Tests: Test Real User Interactions

Learn how Rails system tests use Capybara and Selenium to verify real user workflows, handle JavaScript, and debug flaky tests.


By Jean Emmanuel Cadet • 22 min read

Rails System Tests: Test Real User Interactions
Share with friends

You change a validation, run the test suite, and every test passes. Then a teammate opens the sign-up page and the button does nothing, because a JavaScript controller never connected. Model tests and request tests could not see that bug. They never open a browser, so they never notice that a real person cannot finish a task.

Rails system tests close that gap. They drive a real browser through your application the way a user would: visit a page, fill in a form, click a button, and check what appears on screen. This guide shows how they work, how to set them up, and how to write stable ones for registration, authentication, and JavaScript-powered interactions. It also covers debugging and the cases where a simpler test is the better choice.

Examples target Rails 8.1 with Minitest, the default Rails test framework. They use a small task tracker app called TaskTracker. Adapt the names to your own application.


What Are Rails System Tests?

A system test exercises your application from the outside, through a browser. The test does not call a model method or send a hand-built HTTP request. It visits a URL, types into fields, clicks links and buttons, and asserts on what the page shows.

In Rails, system tests inherit from ActionDispatch::SystemTestCase. Rails provides the test class and the driven_by configuration. Capybara provides the commands you write inside the test, and a browser driver such as Selenium controls the actual browser.

How System Tests Differ from Other Test Types

Each layer of Ruby on Rails testing answers a different question:

  • Model tests check business rules in isolation. Does a Task without a title fail validation?
  • Controller tests call a single controller action directly. Rails still supports them, but the Rails guides lean toward integration tests for most controller behavior.
  • Integration tests (ActionDispatch::IntegrationTest) send simulated HTTP requests through the full Rails stack, including routing, middleware, controllers, and views. They can follow redirects across several controllers. They do not run a browser or JavaScript.
  • Request tests are the RSpec name for the same idea. In a Minitest app, integration tests fill that role.
  • System tests run a real browser against a running copy of your app, so HTML, CSS, JavaScript, and Turbo behavior are all in play.

The distinction that matters is the browser. An integration test can confirm that a form submission creates a record and redirects. A system test can confirm that a person can find the form, type into it, submit it, and see the result.

Why They Are Useful for Complete User Workflows

Real features span many layers: a route, a controller, a view, a Stimulus controller, a database write, and a Turbo Stream update. Each layer can pass its own tests and still fail when combined. System tests catch problems that live between the layers, such as a missing label, a button hidden behind an overlay, or a form that never reaches the server.

They are also the closest thing to a recorded manual QA session. If your checklist says "sign up, create a task, mark it done," a system test is that checklist in code.


How Rails System Tests Work

When a system test runs, several pieces cooperate. Knowing who does what makes failures much easier to understand.

Rails, Capybara, and the Browser Driver

  • Rails starts your application in a Puma server on a local port inside the test process, and loads your test environment and database. It also supplies driven_by and the failure screenshots.
  • Capybara is a Ruby library for browser testing. It provides the commands you write (visit, fill_in, click_button) and the assertions and waiting logic around them.
  • A driver translates Capybara commands into browser actions. The default is Selenium, which controls Chrome or Firefox through WebDriver.

So when you write click_button "Add task", Capybara finds a button with that accessible name, asks the driver to click it, and the browser sends a real request to the Puma server started by your test run.

Supported Browsers and Drivers

With Selenium, Rails supports :chrome, :headless_chrome, :firefox, and :headless_firefox. Recent selenium-webdriver versions download the matching browser driver automatically, so you usually only need the browser itself installed.

Other drivers exist. Rails also accepts driven_by :rack_test, which skips the browser entirely and does not run JavaScript. Third-party drivers such as Cuprite (a Chrome driver that talks to the browser directly) are available as separate gems. This article sticks to Selenium because it is the Rails default.

Headless vs. Visible Browsers

A visible browser opens a real window. It is slower, but you can watch the test click through your app, which is ideal while writing or debugging a test. A headless browser runs the same engine without a window. It is faster and works on servers and CI machines that have no display.

A common pattern is headless by default and visible on demand, which we will configure in the next section.

How a Test Talks to Your App

Consider one step: fill_in "Email address", with: "[email protected]". Capybara searches the page for a field whose label, name, id, or placeholder matches. It then sends the keystrokes through the driver. Because the browser is real, JavaScript event handlers fire exactly as they would for a person typing. When a test fails, you are often looking at a real problem a user could hit.


Setting Up System Tests in Rails

New Rails applications are ready for system tests, so setup is mostly about knowing what you already have.

The Default Setup

A standard Rails app includes capybara and selenium-webdriver in the :test group of the Gemfile. It also generates test/application_system_test_case.rb, the base class for every system test:

# test/application_system_test_case.rb
require "test_helper"

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :selenium, using: :chrome, screen_size: [ 1400, 1400 ]
end

The driven_by line is a Rails method. It picks the driver (:selenium), the browser (using: :chrome), and the window size. A fixed screen_size keeps layouts consistent, which matters when your CSS changes at breakpoints.

Run bin/rails test:system to execute only system tests. Plain bin/rails test skips them because they are slower, and bin/rails test:all runs everything.

Generating a System Test

Use the generator:

bin/rails generate system_test registrations

This creates test/system/registrations_test.rb:

require "application_system_test_case"

class RegistrationsTest < ApplicationSystemTestCase
# test "visiting the index" do
# visit registrations_url
#
# assert_selector "h1", text: "Registrations"
# end
end

The class inherits from ApplicationSystemTestCase, so it gets the browser configuration automatically. The commented example shows the basic shape: visit a page, then assert on what you see. Generating a scaffold with bin/rails generate scaffold also creates a system test for it.

Configuration Worth Knowing

Keep configuration small at first. Two changes help most beginners.

First, switch between headless and visible mode with an environment variable:

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
browser = ENV["SHOW_BROWSER"] ? :chrome : :headless_chrome

driven_by :selenium, using: browser, screen_size: [ 1400, 1400 ]
end

Run SHOW_BROWSER=1 bin/rails test:system when you want to watch the test. Everything else runs headless.

Second, Capybara waits up to Capybara.default_max_wait_time seconds (2 by default) for elements to appear. If your pages are slow on CI, raise it modestly instead of adding sleeps:

Capybara.default_max_wait_time = 5

You can pass extra browser flags through a block on driven_by, but you rarely need that to get started.


Writing Your First System Test

A registration flow makes a good first test because it touches a form, validations, a database write, a redirect, and a flash message.

The Page Under Test

Here is the sign-up form. The labels matter, because the test will locate fields by them:

<%# app/views/registrations/new.html.erb %>
<h1>Create your account</h1>

<%= form_with model: @user, url: registration_path do |form| %>
<div>
<%= form.label :email_address, "Email address" %>
<%= form.email_field :email_address, required: true, autocomplete: "email" %>
</div>

<div>
<%= form.label :password, "Password" %>
<%= form.password_field :password, autocomplete: "new-password" %>
</div>

<div>
<%= form.label :password_confirmation, "Confirm password" %>
<%= form.password_field :password_confirmation, autocomplete: "new-password" %>
</div>

<%= form.submit "Create account" %>
<% end %>

Properly labeled fields are good for users and for tests, and the same labels make your app more accessible. If you want to go deeper, see CodeCurious's guide to accessible forms in Rails.

The Test

# test/system/registrations_test.rb
require "application_system_test_case"

class RegistrationsTest < ApplicationSystemTestCase
test "visitor creates an account" do
visit new_registration_path

fill_in "Email address", with: "[email protected]"
fill_in "Password", with: "correct-horse-battery"
fill_in "Confirm password", with: "correct-horse-battery"
click_button "Create account"

assert_current_path tasks_path
assert_text "Welcome to TaskTracker!"
assert_selector "h1", text: "Your tasks"
end
end

What Each Part Does

  • visit opens a path in the browser. Inside system tests, route helpers such as new_registration_path work as usual.
  • fill_in finds a field by its label (or name, id, or placeholder) and types into it.
  • click_button finds a button by its text, id, or title. click_link does the same for links.
  • assert_current_path confirms where the browser ended up after the redirect.
  • assert_text checks that visible text appears anywhere on the page.
  • assert_selector checks for an element matching a CSS selector, optionally filtered by text.

These assertions come from Capybara. Capybara's Minitest integration (Capybara::Minitest::Assertions) is already mixed into Rails system tests, so you can call them directly.

You will also see has_text? and has_selector?. Those return true or false instead of failing the test, which is handy in conditionals but rarely what you want in a test body. Prefer the assert_ forms, because they give clear failure messages.

Using find When You Need an Element

Most steps do not need find, because fill_in and click_button locate elements for you. Use find when you need to interact with something specific or scope the next step:

find("h1", text: "Your tasks")
find("#flash").assert_text("Welcome to TaskTracker!")

find raises an error if it matches zero or multiple elements, which keeps tests honest. It also waits for the element to appear.

A note on fill_in "Password" when a "Confirm password" field exists: Capybara's default match strategy is :smart. It tries an exact label match first and only falls back to partial matches if none is found. So "Password" resolves to the exact label, not the confirmation field.

Prefer Labels and Roles over CSS Selectors

A test that says click_button "Create account" survives a redesign. A test that says find("div.form-wrapper > input.btn-primary").click breaks the moment someone renames a class. Use visible text and labels first, then stable attributes, and use CSS selectors only when text is not enough.


Testing Complete User Workflows

A single page check is useful, but system tests pay off when they walk through a sequence. They show that the controller, view, database, and Turbo update all cooperate.

Fixtures for the Examples

The workflow tests below rely on these fixtures. Maria has two tasks, and Ravi has one that Maria should never see:

# test/fixtures/users.yml
maria:
email_address: [email protected]
password_digest: <%= BCrypt::Password.create("correct-horse-battery") %>

ravi:
email_address: [email protected]
password_digest: <%= BCrypt::Password.create("correct-horse-battery") %>
# test/fixtures/tasks.yml
write_report:
title: Write quarterly report
completed: false
user: maria

send_welcome_email:
title: Send welcome email
completed: true
user: maria

ravi_private:
title: Ravi private task
completed: false
user: ravi

A Shared Sign-In Helper

Every workflow test needs a signed-in user, so add a helper to the base class. We will discuss this choice in the authentication section.

# test/application_system_test_case.rb (inside the class)
private

def sign_in_as(user, password: "correct-horse-battery")
visit new_session_path
fill_in "Email address", with: user.email_address
fill_in "Password", with: password
click_button "Sign in"

assert_selector "h1", text: "Your tasks"
end

The final assertion is deliberate. It makes the helper wait until the login completes, so the next step does not run against a half-loaded page.

A Successful Workflow

# test/system/task_workflow_test.rb
require "application_system_test_case"

class TaskWorkflowTest < ApplicationSystemTestCase
setup { @user = users(:maria) }

test "user adds a task and marks it done" do
sign_in_as @user

assert_text "Write quarterly report"
assert_no_text "Ravi private task"

fill_in "Title", with: "Prepare invoice"
click_button "Add task"

assert_selector "li", text: "Prepare invoice"
assert_selector "li", count: 3
assert_field "Title", with: ""

within "li", text: "Prepare invoice" do
click_button "Complete"
assert_text "Done"
end
end
end

Notice what this single test verifies. The page lists only Maria's tasks. The new task appears after submitting. The form resets, and the completion state changes on screen. No single unit test covers all of that.

within scopes every command in its block to one element, so click_button "Complete" clicks the button inside the Prepare invoice row, not the first "Complete" button on the page.

An Unsuccessful Workflow

Failure paths deserve tests too, because validation messages are part of the user experience:

test "blank title shows a validation message" do
sign_in_as @user

click_button "Add task"

assert_text "Title can't be blank"
assert_selector "li", count: 2
end

If this form renders validation errors on a failed submission, remember that Turbo expects an error response status. A controller that re-renders the form should use render :index, status: :unprocessable_entity. Without that status, Turbo ignores the response and the user sees nothing, which is exactly the kind of bug a system test finds.

Navigation and Page Changes

Check navigation with assert_current_path and check changes with assert_text or assert_selector. Assert on what a user would notice (a flash message, a new row, a heading), not on instance variables or database state. If you do need to confirm the record exists, a quick assert Task.exists?(title: "Prepare invoice") after the visible assertion is fine. The visible assertion also guarantees the request has finished.


Working with Authentication

Most real applications keep important pages behind a login, so authentication shows up in nearly every system test.

Testing the Real Login Flow

Write a small set of tests that use the actual form:

# test/system/authentication_test.rb
require "application_system_test_case"

class AuthenticationTest < ApplicationSystemTestCase
test "user signs in and signs out" do
visit new_session_path
fill_in "Email address", with: "[email protected]"
fill_in "Password", with: "correct-horse-battery"
click_button "Sign in"

assert_selector "h1", text: "Your tasks"

click_button "Sign out"

assert_current_path new_session_path
assert_text "You have signed out."
end

test "wrong password is rejected" do
visit new_session_path
fill_in "Email address", with: "[email protected]"
fill_in "Password", with: "wrong-password"
click_button "Sign in"

assert_text "Try another email address or password."
assert_no_selector "h1", text: "Your tasks"
end

test "signed out visitors are sent to the login page" do
visit tasks_path

assert_current_path new_session_path
end
end

These three tests cover the success path, a failure path, and route protection. They assume a User with has_secure_password and your own routes and messages. Rails 8 ships an authentication generator, but its sessions are not the only option, so adapt the paths, labels, and messages to whatever your app uses.

Real Login vs. Shortcuts

Logging in through the form in every test is accurate but slow, and it repeats the same steps hundreds of times. Teams usually speed this up in one of three ways:

  • A helper that still uses the form, like sign_in_as above. It is simple and honest, with a small cost per test.
  • A library helper. If you use Devise, its underlying Warden library provides test helpers such as login_as. This is specific to Devise and not part of Rails.
  • A test-only route or endpoint that creates a session directly. It is the fastest, but it must never exist outside the test environment.

If login speed is a real bottleneck, shortcuts are reasonable. A shortcut only skips the setup, though. It is not a replacement for testing the login itself. If every test bypasses the form, a broken login page can ship with a fully green suite. Keep a few tests on the real flow, and use shortcuts elsewhere.

Some login concerns do not need a browser at all. Behavior like throttling repeated attempts is better covered by an integration test, as described in the article on Rails rate limiting.


Database and Test Data

System tests use your test database, the same one as model and integration tests. The difference is that your test and the Puma server run in different threads, so data created in the test must be visible to the app serving the browser.

Transactions and Shared Connections

Rails wraps each test in a database transaction and rolls it back afterward. For system tests, Rails shares the test's database connection with the server thread, so records created in setup or fixtures are visible to the browser, even though the transaction has not been committed. This is why transactional tests generally work in Rails with no extra setup.

Fixtures and Factories

Rails fixtures (YAML files in test/fixtures) load once and give you predictable, named records, as in the examples above. They are fast and built in.

Factories, such as those from the factory_bot_rails gem, build records on demand inside each test. Some teams prefer them because the data a test needs is visible right in the test:

# test/test_helper.rb (only if you use factory_bot_rails)
class ActiveSupport::TestCase
include FactoryBot::Syntax::Methods
end
user = create(:user, email_address: "[email protected]")
create(:task, user: user, title: "Write quarterly report")

Neither approach is required, and Rails does not assume you use factories. Pick one and stay consistent. Whichever you choose, keep data small and predictable. A test that depends on whatever is in the database is a flaky test waiting to happen.

Asynchronous Pitfalls

The browser works in the background, so a request can still be running when your test code reaches its last line. If the test ends and Rails rolls back the transaction while a request is in flight, you can see odd errors that appear only sometimes.

The fix is to end each test with an assertion on something visible. That assertion waits until the page has finished updating, so no request is left hanging. The sign-in helper above does this, and it is one of the cheapest ways to prevent random failures.

Background jobs deserve a thought as well. Decide whether your test needs the job's result. If it does, run jobs inline in the test environment, or assert only what the user sees right away and test the job separately.


JavaScript and Asynchronous Interactions

With a real browser, system tests can verify features that only exist because of JavaScript, including Turbo Streams, Stimulus controllers, modals, and dropdowns.

Why Capybara Waiting Matters

Assume clicking "Add task" triggers a request, and the server responds with a Turbo Stream that adds a row. The new row might take 50 milliseconds to appear, or 500. Capybara handles this for you. Its finders and assert_ methods retry until the condition is true or Capybara.default_max_wait_time runs out.

That is why this test is stable:

click_button "Add task"
assert_selector "li", text: "Prepare invoice"

Avoiding Fixed Sleeps

A fixed sleep is the classic cause of flaky tests. It is too short on a slow CI machine and wastes time on a fast one:

# Fragile: guesses how long the page needs
click_button "Add task"
sleep 2
assert_equal 3, all("li").size

# Better: waits only as long as necessary
click_button "Add task"
assert_selector "li", count: 3

The first version fails in two ways. sleep 2 guesses a duration, and all("li").size returns the count right now without waiting. The second version states the expected result and lets Capybara wait for it.

Some other habits matter just as much:

  • Use assert_no_selector and assert_no_text to wait for things to disappear. assert_not page.has_selector? can pass too early.
  • find(...).text reads the text immediately, so prefer assert_text when the content is still changing.
  • Assert on the outcome, not on how long it takes.

A Dropdown That Updates the List

Suppose a "Show" dropdown filters tasks through a Turbo Frame:

test "filter shows only completed tasks" do
sign_in_as users(:maria)

select "Completed", from: "Show"

assert_selector "li", text: "Send welcome email"
assert_no_selector "li", text: "Write quarterly report"
end

select is a Capybara method that picks an option from a dropdown by its label.

A Modal Dialog

Imagine an Edit button that opens a <dialog> element with a form inside:

test "user edits a task in a modal" do
sign_in_as users(:maria)

within "li", text: "Write quarterly report" do
click_button "Edit"
end

within "dialog[open]" do
fill_in "Title", with: "Write final quarterly report"
click_button "Save"
end

assert_no_selector "dialog[open]"
assert_selector "li", text: "Write final quarterly report"
end

Scoping to dialog[open] ensures the test interacts with the visible modal, and assert_no_selector waits for it to close.

Confirmation Prompts

Delete buttons often use a confirmation. With Turbo, you can add data-turbo-confirm to the form, which triggers a browser confirm dialog. Capybara can handle it with Selenium:

test "user deletes a task after confirming" do
sign_in_as users(:maria)

within "li", text: "Write quarterly report" do
accept_confirm { click_button "Delete" }
end

assert_no_selector "li", text: "Write quarterly report"
end

accept_confirm and dismiss_confirm belong to Capybara's modal API and need a driver that supports them, such as Selenium. They do not work with rack_test, which has no JavaScript at all.


Debugging Failed System Tests

A failing browser test can be baffling at first, because there is more that can go wrong. A few habits make diagnosis fast.

Read the Failure and Look at the Screenshot

Read the error first. Capybara messages are specific: Unable to find field "Email address", or Ambiguous match, found 2 elements. When a system test fails, Rails automatically saves a screenshot of the page to tmp/screenshots. Open it. Very often the answer is visible: an error banner, a modal covering the button, or a page that never finished loading.

You can capture one at any point with take_screenshot:

click_button "Add task"
take_screenshot

Inspect the Page

When a screenshot is not enough, look at what the browser actually has:

puts page.html            # full HTML at this moment
puts page.text # visible text only
save_page # writes the HTML to tmp/capybara
debugger # pauses the test so you can inspect state

page.html and page.text come from Capybara. save_page writes a copy of the page to disk. debugger pauses the test, so if you run in visible mode you can click around and open the browser's developer tools while the test waits.

Browser Console Logs

JavaScript errors often explain why a feature silently failed. The easiest way to see them is to run the test in a visible browser and open the console. Selenium also exposes browser logs for Chromium-based drivers, but the exact API depends on your selenium-webdriver version, so check its documentation before building anything on it.

Reproduce Failures Locally

Run the failing test on its own, visibly:

SHOW_BROWSER=1 bin/rails test test/system/task_workflow_test.rb:12

The line number selects a single test. If a failure appears only in a full run, repeat it with the same Minitest seed, since test order can matter:

bin/rails test:system --seed 12345

The seed is printed at the top of every test run. CI can fail where your laptop passes because of a different browser version, a smaller screen, or a slower machine. Check how your CI workflow runs system tests. Recent Rails apps generate a workflow that includes them and can upload failure screenshots, and your own file may differ.

Diagnosing Flaky Tests

Flaky tests usually come from one of a few causes:

  • Timing. A sleep, a non-waiting check like all(...).size, or a missing final assertion.
  • Shared state. One test depends on data or logins left by another.
  • Order dependence. The test passes alone and fails in the full suite.
  • Animation or overlays. A button exists but is covered or moving.

When a test fails once in twenty runs, rerun it repeatedly and read the screenshot from a failing run. Fix the cause. Do not add retries or longer waits as a first move, because they hide the problem instead of solving it.


Best Practices and Common Mistakes

Good system tests are few, readable, and boring. These habits keep them that way.

Habits to Keep

  • Test what the user sees. Assert on text, links, buttons, and visible state. Do not assert on CSS classes used only for styling, or on controller instance variables.
  • Prefer stable, accessible selectors. Labels and button text come first. If you need a hook, add a purpose-built attribute such as data-testid rather than depending on layout classes.
  • Keep tests independent. Each test should create what it needs and run in any order. A test that relies on another one having run first is a debugging trap.
  • Keep data predictable. Use small, named fixtures or explicit factory calls so a test reads like a story.
  • Wait with assertions. Let assert_selector and assert_text do the waiting.
  • Cover important journeys. Sign up, log in, check out, publish, pay. These are the flows where a failure costs you users or revenue.

Common Mistakes

  • Using system tests to check every validation message or edge case.
  • Copying the same twelve-step login into every test instead of using a helper.
  • Using sleep to wait for the page.
  • Selecting elements by position, such as all("button")[2].
  • Testing implementation details, such as which Stimulus controller is attached.

When a Simpler Test Is Better

Use the cheapest test that gives you confidence:

  • A validation rule belongs in a model test. It runs in milliseconds.
  • A redirect, status code, or JSON response belongs in an integration test, which still goes through routing and middleware without a browser.
  • Email content and delivery are better checked with mailer tests, as covered in the Action Mailer guide.

If a behavior has no browser-specific risk, a lower-level test will be faster and less fragile.


When Should You Use Rails System Tests?

Rails system tests give you the most confidence per test when a failure would be expensive and the behavior spans several layers.

Features That Benefit Most

  • Core journeys. Registration, login, onboarding, checkout, or the central action of your product.
  • JavaScript-heavy features. Turbo Streams, modals, drag and drop, inline editing, and autocomplete. Only a browser can verify them.
  • Forms with several steps. Multi-page flows where state passes from screen to screen.
  • Regressions you have already suffered. A bug that broke production once is a good candidate for a test.

The Trade-Offs

System tests are slower than other tests, because they start a browser and wait on real rendering. They are also more sensitive to changes in markup and timing, so they cost more to maintain. In return they provide the highest realism, since they test what the user experiences.

A Balanced Testing Strategy

A healthy suite resembles a pyramid. Many fast model tests sit at the base, a moderate number of integration tests handle request-level behavior, and a small number of system tests protect the most important journeys. This balance keeps your suite quick enough to run constantly while still catching the bugs that only appear in a browser. It is also a practical approach to Rails integration testing, because each layer covers what the others cannot.


Conclusion

Rails system tests answer a question no other test type can: can a real person actually use this feature? Rails, Capybara, and a browser driver work together to click through your application and check what appears on screen. That gives you protection against broken forms, missing labels, and JavaScript failures that unit tests cannot see.

You do not need to cover everything. Start with one or two critical workflows, such as signing up and signing in. Use accessible labels, rely on Capybara's waiting instead of sleeps, and end each test with a visible assertion. Once those tests are stable, add the next most valuable journey. Over time you will build a small suite that you trust, and that lets you ship changes with confidence.

Jean Emmanuel Cadet
Written by Jean Emmanuel Cadet
Jean Emmanuel is a Full-Stack Software Engineer specializing in Ruby on Rails and the modern Rails ecosystem. He builds scalable, maintainable web applications using Rails, Hotwire (Turbo & Stimulus), PostgreSQL, and SQLite, with a focus on fast, dynamic user experiences. Through CodeCurious, he shares practical lessons, development insights, and real-world solutions for modern developers.

Code. Learn. Grow.

A friendly newsletter sharing dev tips, lessons, and wins from my journey.