BDD and end to end testing in Rails: Cucumber, Capybara and system tests that catch real bugs

TL;DR

Difficulty: Intermediate

A browser test is the most expensive test you have, so each one must guard a seam: a bug that lives between the server and Turbo, the HTML and Stimulus, or the model and Action Cable.

  • Every system test should finish the sentence: this test fails if ___, and no faster test would notice.
  • Wait for a fact, never for a time. Capybara retries for up to two seconds, so use assert_text and assert_no_text, never sleep or a negated has_text?.
  • For live Hotwire screens, wait until the stream is connected before you act, and test with two browser sessions.
  • Flakiness compounds: 38 tests at 1% each give a red run one time in three.
  • Cucumber earns its keep only when someone who does not write Ruby reads the scenarios before the code is written.

Browser tests either catch the bugs customers would have found, or they become a slow suite that fails at random and that nobody trusts. The difference is not the tool. It is which tests you write and how they wait. Here is how to do it in Rails 7.1, with system tests, Capybara and Cucumber, on a Limerick bike workshop's booking page and live workshop board.

The question behind this article

"How do I write behaviour driven and end to end tests in Rails that catch real bugs without becoming slow and flaky?"

Most teams arrive at this question from one of two directions. Some have no browser tests at all, ship a form that shows no error message when it should, and hear about it from a customer. Others have hundreds of browser tests, a suite that takes half an hour, and a habit of pressing "re run" until it goes green. Both are expensive. The first costs you bugs, the second costs you trust, and a suite nobody trusts is a suite nobody reads.

This article is the practical half of the end to end story for Rails. The testing map explained what behaviour driven development (BDD) and end to end tests are and how many of them a web application needs. The test driven development chapter for Rails built the inner loop with Minitest, fixtures and request tests. This article goes out to the browser: Rails system tests, Capybara and the drivers behind it, testing Hotwire in a real browser, Cucumber for scenarios that business people read, and keeping all of it fast and stable.

The example is the one from the whole programme. Freewheel Cycles (freewheelcycles.example) is an invented chain of six bicycle repair workshops in Limerick, founded by Niamh, with 38 mechanics and about 1,150 repair bookings a week. Saturday morning is when the place is hopping: 30% of the week's online bookings arrive between Friday 6pm and Saturday noon. Its two developers, Aisling and Cian, chose Rails after building a spike in both frameworks, and built a live workshop board with Hotwire in the Hotwire chapter. The company, the people and the numbers are made up. The code is real.

The versions, as of 4 June 2024: Ruby 3.3, Rails 7.1.3, Capybara 3.40.0, selenium webdriver 4.21, turbo rails 2.0.5, Cuprite 0.15, cucumber rails 3.0.0 with Cucumber 9.21.

A browser test is for the seams

Here is the idea I would most like you to take from this article. A system test is the most expensive test you can write: it starts a browser, a web server and your whole application, and it takes seconds where a model test takes milliseconds. So it must buy something no lower level test can buy. That something is a bug in a seam.

A seam is a place where two technologies meet and each assumes something about the other. In a Rails application with Hotwire the seams are easy to list:

  • Server and Turbo. A form answers with the wrong status code, and Turbo silently ignores the response.
  • HTML and Stimulus. A data-action attribute has a typo, and the button does nothing.
  • Model and Action Cable. A broadcast goes to the wrong stream name, and the other screens never hear about it.
  • Page and CSS. An element is in the HTML but hidden, so a person cannot click it.
  • Two requests. Something changes between loading a page and submitting it.

A model test cannot see any of these, because each bug lives between two pieces that are each correct on their own. A request test sees the server's half and never the browser's half.

So here is the rule of thumb I use: every system test must complete one sentence: "This test fails if ___, and no faster test would notice." If you cannot fill the blank with a seam, write the test one level down. Validation rules, prices, VAT, permissions and which status may follow which belong in model and request tests, where they run in milliseconds and fail with a precise message.

Example: Freewheel's seam list

Aisling and Cian wrote the sentence for every candidate browser test for the booking page and the workshop board. Here is what survived, and where the rest went.

BugSeam?Fastest test that catches it
Two bookings for the same mechanic and slotnomodel test plus the database constraint
A slot taken while the customer types shows no messageyes, server and Turbosystem test
The price of a repair includes VAT at 23%nomodel test
A mechanic sees another workshop's job cardsnorequest test
A move on one tablet never reaches the wall screenyes, model and Action Cablesystem test with two browsers
Dragging a card does nothingyes, HTML and Stimulussystem test
"Mark ready" is not offered for a waiting cardnomodel test of the allowed moves
The confirmation email has the wrong timenomailer test

Eight candidates, three browser tests. That ratio is not a target. It is what falls out when every browser test has to name its seam.

What a Rails system test is

A system test in Rails is a class that inherits from ActionDispatch::SystemTestCase. It drives a real browser through Capybara, a Ruby library that simulates how a person uses a web application: visit a page, fill in a field, click a button, look for text23. Rails added system tests in version 5.13. In Rails 7.1 the generator writes this file into every new application, as shown here4.

# test/application_system_test_case.rb, as Rails 7.1 generates it
require "test_helper"

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

Four things happen behind that one line:

  1. A driver. driven_by :selenium tells Capybara to control the browser through Selenium WebDriver, the long standing standard for browser automation. using: :chrome opens a visible Chrome window. :headless_chrome runs Chrome without a window, which is what you want on a build server2.
  2. A server. Capybara starts your application in Puma, on a random port, in the same Ruby process as the test3.
  3. A shared database connection. Since Rails 5.1, the test and the server threads share one database connection, so the records your test creates are visible to the server, and every test still rolls back at the end like any other Rails test3.
  4. A screenshot on failure. Rails calls take_failed_screenshot before teardown, and saves the image to tmp/screenshots25.

Two details catch people out. First, bin/rails test does not run system tests. You run them with bin/rails test:system, or everything with bin/rails test:all2. That is deliberate: the fast tests stay fast. Second, you no longer need a gem to download ChromeDriver. Rails 7.1 removed the webdrivers gem from the generated Gemfile6, because Selenium Manager, which ships with selenium webdriver, finds or downloads the right driver itself6.

Example: Freewheel's base class

Cian made three small changes to the generated file: headless Chrome in continuous integration (CI), a visible window on his laptop so he can watch a test when he wants to, and a sign in helper that every board test needs.

# test/application_system_test_case.rb
require "test_helper"

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  # GitHub Actions sets CI=true. Locally, HEADLESS=0 opens a visible window.
  BROWSER = ENV["CI"] || ENV["HEADLESS"] != "0" ? :headless_chrome : :chrome

  driven_by :selenium, using: BROWSER, screen_size: [1400, 1400]

  def sign_in_as(user, password: "long enough secret")
    visit new_session_path
    fill_in "Email", with: user.email_address
    fill_in "Password", with: password
    click_on "Sign in"

    # Wait for proof that the login finished before the test moves on.
    # Without this line, the next visit can race the redirect.
    assert_button "Sign out"
  end
end

The users come from the fixtures in the authentication chapter, where every staff password is "long enough secret". The labels "Email", "Password", "Sign in" and "Sign out" are the ones on Freewheel's sign in page and layout.

That last assertion is worth a closer look, because it is the whole subject of the next section in one line. click_on "Sign in" returns as soon as the click is sent. The browser is still submitting the form, and the server is still setting the session cookie. If the test calls visit straight away, it can arrive at the board before the cookie exists, and land on the sign in page instead. It will work on a fast laptop nearly every time and fail on a busy build server now and then. Asserting on something that only exists after the login, the "Sign out" button, turns a race into a wait.

The diagram shows the path one step takes from the test to the browser and back.

Tap or click to enlarge

Wait for a fact, never for a time

Almost every flaky browser test I have read comes down to the same mistake: the test checks the page before the page has finished changing. The browser and the server work in parallel with your test. A click starts something. The test has to know when that something is done.

There are two ways to know. You can wait for a time (sleep 1), or you can wait for a fact (the text "Booked" is on the page). Capybara is built around the second. Its README calls this out under asynchronous JavaScript: when you look for something that is not there yet, Capybara waits and retries, for up to Capybara.default_max_wait_time, which is 2 seconds by default3. Under the hood, every finder and every matcher runs inside a loop that catches the failure, sleeps for the retry interval of 0.01 seconds, and tries again until the time runs out7.

So assert_text "Booked" is not a single look. It is "keep looking for up to two seconds, and pass the moment it appears". click_on "Book this slot" waits for the button to exist before clicking. within("#column_ready") waits for the column. You get waiting for free, as long as you let Capybara do the looking.

A sleep is a bet on the slowest machine you will ever run on

A sleep gets both sides of the trade wrong at once. On a fast machine it wastes time, because the page was ready long before the sleep ended. On a slow machine it is too short, because the page was not ready when the sleep ended. You pay the full delay on every run, and you still fail on the runs that matter. Martin Fowler made the same point in 2011, in his essay on non deterministic tests: never use a bare sleep to wait for an asynchronous response, use a callback or polling instead8. Capybara is the polling.

The second trap is quieter. Capybara can only wait if it knows what you are waiting for. These two lines look the same and are not3:

# Wrong: has_text? waits for the text to APPEAR. If it is still there,
# it returns true at once, and the refute fails, or worse, passes too early.
refute page.has_text?("Blue Brompton")

# Right: assert_no_text waits for the text to DISAPPEAR.
assert_no_text "Blue Brompton"

The Capybara README says plainly that you should always use the has_no_ form rather than negating the positive one3. The same goes for assert_no_selector and assert_no_button. And never read the raw HTML with page.html and check it with plain Ruby. That is a single look, taken at whatever moment the line happens to run.

The third trap is the "nothing happened" test. Say you want to prove that dropping a waiting card on "Ready" does nothing. within("#column_waiting") { assert_text "Blue Brompton" } passes at once, because the card is still there in the first millisecond, whether or not it would have moved a moment later. To prove nothing happened, make something else happen after it, wait for that, and then check. A waiting assertion can only prove that something arrived. It can never prove on its own that something will not.

Example: Cian's first board test

Cian's first version of the board test, before he had read the Capybara README, had three sleeps. Here are the first two:

click_on "Start repair"
sleep 1   # give Turbo time
assert page.has_css?("#column_in_repair", text: "Blue Brompton")
sleep 1   # give the broadcast time

On his laptop the response arrived in about 0.2 seconds, so each sleep wasted about 0.8 seconds. Over the three sleeps in that test, that is 2.4 seconds on every run, for nothing. On the shared build server, now and then, the broadcast took longer than a second, and the test failed with a screenshot that showed the board in exactly the right state, because by the time the screenshot was taken, it was. That screenshot is the signature of a timing bug: the failure message says the text is missing, and the picture shows it there.

The rewrite has no sleeps and is shorter:

click_on "Start repair"
within("#column_in_repair") { assert_text "Blue Brompton" }   # waits up to 2 seconds

The test now takes as long as the application takes, never longer, and fails only if the card really does not arrive within two seconds.

The arithmetic of a flaky suite

One flaky test does not look like a problem. A suite full of slightly flaky tests is. If each of nn tests fails at random with probability pp, and the failures are independent, the chance that a whole run is green is:

P(green run)=(1−p)nP(\text{green run}) = (1 - p)^{n}

Here pp is the chance that one test fails for no reason on one run, and nn is the number of such tests. The Foundations section on probability explains why independent chances multiply.

Take a suite with 38 system tests, the size Freewheel's suite reaches two years in. If each one has a 1% chance of a random failure, then P=0.9938≈0.68P = 0.99^{38} \approx 0.68. About one run in three is red for no reason. At 2% per test, 0.9838≈0.460.98^{38} \approx 0.46: more red runs than green. At that point people stop reading the failures, and the real failures start to hide among the false ones. Fowler calls this an infection: once a team ignores some red builds, it ignores the healthy tests too8.

With 38 tests and independent random failures: at 0.1% per test the run is green 96% of the time, at 0.5% it is 83%, at 1% it is 68%, and at 2% it is 46%. Tap or click to enlarge

The lesson in the chart: flakiness does not add up, it compounds. A tolerance of "only 1%" per test is not a tolerance at all once you have a few dozen browser tests.

Example: what removing the sleeps did at Freewheel

The chart below is illustrative: invented counts for the example, not a measurement. It shows how the failures Cian saw on the build server fell into causes, per 100 runs of the system tests, before and after one afternoon of rewrites: every sleep replaced by a waiting assertion, every negated has_ replaced by its has_no_ twin, and a wait for the board's live connection, which the Hotwire section below explains.

Illustrative numbers for the invented example. Before: 14 failures from sleeps that were too short, 6 from negated has_ checks, 9 from acting before the live connection was ready, 3 from other causes. After: 0, 0, 0 and 3. Tap or click to enlarge

The three "other causes" are the honest remainder, and they deserve the policy Fowler describes: move such a test into quarantine, a separate group that does not block a release, and fix it within days, because while it sits there it protects nothing8. The chapter on keeping a suite fast and trustworthy in CI, at the end of this series, turns that into a written policy.

The worked example, part one: book a repair as a system test

Now the first full test. The booking page is the one customers use, without logging in. For this chapter, the page lists each day as a group of radio buttons with one hour slots per mechanic ("09:00 with Darragh"), then asks for a name, an email address and the bike, and has one button, "Book this slot". How the free slots are worked out is not the subject here. The test only cares what a customer sees.

Step 1: the fixtures

The fixtures follow the pattern from the earlier chapters: two workshops, castletroy and dooradoyle, and a few mechanics and customers.

# test/fixtures/workshops.yml
castletroy:
  name: Castletroy
  city: Limerick

dooradoyle:
  name: Dooradoyle
  city: Limerick
# test/fixtures/mechanics.yml
darragh:
  workshop: castletroy
  name: Darragh
  email: darragh@freewheelcycles.example
# test/fixtures/customers.yml and test/fixtures/bikes.yml
regular:
  name: Ciarán Moloney
  email: ciaran@example.com

# bikes.yml
ciaran_tourer:
  customer: regular
  make: Raleigh
  model: Pioneer

There are no bookings for next Saturday in the fixtures, so every slot on that day is free. That is a choice: a test that depends on "Saturday" must never depend on today's date, so the test works out next Saturday itself.

Step 2: the happy path

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

class BookARepairTest < ApplicationSystemTestCase
  setup do
    @workshop = workshops(:castletroy)
    @saturday = Date.current.next_occurring(:saturday)   # never a hard coded date
  end

  test "a new customer books a Saturday slot with Darragh" do
    visit new_workshop_booking_path(@workshop)

    within_fieldset(day_label(@saturday)) { choose "09:00 with Darragh" }
    fill_in "Your name", with: "Orla Quinlan"
    fill_in "Email", with: "orla@example.com"
    fill_in "Your bike", with: "Green Dawes Galaxy"
    click_on "Book this slot"

    assert_text "Booked. See you on Saturday."
    assert_text "09:00 with Darragh at Castletroy"
  end

  private

  # "Saturday 8 June", the legend of each day's group of slots
  def day_label(date) = date.strftime("%A %-d %B")
end

next_occurring is an Active Support date method that returns the next date with the given weekday9. Every line in the test describes what a customer does or sees. There is no CSS class, no id and no sleep. The labels are the same words a customer reads on screen, which has a pleasant side effect: if a label is missing or does not belong to its field, fill_in cannot find the field, and the test fails. Accessible forms and testable forms turn out to be the same forms.

What seam does this test cover? Its sentence reads: "This test fails if the booking page, the form, the controller and the confirmation page do not fit together in a browser, and no faster test would notice." It is the one test that proves the main journey of the business works end to end. Everything about the slot rules has its own model tests.

Step 3: the slot that goes while the customer types

The second test is the one that earns the browser. Saturday morning brings two customers to the same slot within seconds. The Active Record chapter made sure the database never accepts both: a validation, a partial unique index, and a rescue in the controller that adds the message "was just taken. Please pick another time." In this version the uniqueness validation uses the same message, so the customer reads one sentence either way.

The browser part is what happens next. As the Hotwire chapter explained, Turbo shows a failed form only if the server answers with an error status such as 422. Render the form again with a 200 and Turbo ignores it, so the customer presses "Book this slot" and nothing at all happens10. That is a seam bug in its purest form: the model is right, the controller renders the right template, and the customer still sees nothing.

  # test/system/book_a_repair_test.rb, continued
  test "a slot taken while the customer types shows a clear message" do
    visit new_workshop_booking_path(@workshop)
    within_fieldset(day_label(@saturday)) { choose "09:00 with Darragh" }
    fill_in "Your name", with: "Orla Quinlan"
    fill_in "Email", with: "orla@example.com"
    fill_in "Your bike", with: "Green Dawes Galaxy"

    # Meanwhile, another customer books the same slot. The test and the
    # server share one database connection, so the server sees this row.
    nine = @saturday.in_time_zone.change(hour: 9)
    Booking.create!(workshop: @workshop, mechanic: mechanics(:darragh),
                    customer: customers(:regular), bike: bikes(:ciaran_tourer),
                    starts_at: nine, ends_at: nine + 1.hour)

    click_on "Book this slot"

    assert_text "was just taken. Please pick another time."
    assert_field "Your name", with: "Orla Quinlan"   # nothing the customer typed is lost
  end

Follow it through. The page loads with the slot free. The test inserts the other booking directly, which is how you set up "something changed between loading and submitting" without a second browser. The click submits the form. The validation finds the clash, the controller renders the form with status 422, Turbo replaces the page with it, and assert_text waits until the message appears. If anyone ever drops the status: :unprocessable_entity, this test fails within two seconds.

Once you know the 422 rule, a request test can check the status code too, and it should, because it is faster. The system test still earns its place: it catches the bug before you know the rule exists, and it catches the next seam bug of the same kind, the one nobody has thought of yet.

Testing Hotwire in the browser

Hotwire moves work into the browser in three ways, and each one has its own way of waiting.

Turbo Drive and forms. A link or a form fetches the next page in the background and swaps it in. Nothing about the address bar changing is a signal you should wait for. Wait for content that only the new page has, as the sign in helper does.

Turbo Frames. A frame replaces one part of the page. Scope your assertions to the frame, within("#job_card_panel") { assert_text "Blue Brompton" }, so the test proves the content landed in the frame and not somewhere else. If the response is missing the matching frame, Turbo writes "Content missing" into it, and an assertion on the expected content fails with a screenshot that makes the cause obvious.

Turbo Streams. A stream changes parts of a page in response to a form, or over Action Cable from the server, to every subscribed screen. The form response is like any other: wait for its effect. The broadcast is the interesting case, because it reaches a different browser. That needs two browsers in one test, and three facts that are easy to miss.

Fact one: broadcasts do reach the browser in a system test. The Rails 7.1 generator sets the Action Cable adapter for the test environment to test11. The test adapter extends the async adapter, which delivers messages within one process, and its own documentation notes that this makes it usable in system tests11. Since Capybara's Puma runs in the test process, the broadcast reaches every browser connected to it.

Fact two: the page must be subscribed before you act. When a page with turbo_stream_from loads, the browser opens a WebSocket and subscribes to the stream. That takes a moment. A broadcast sent before the subscription is confirmed is simply lost, and the test waits two seconds for a card that is never coming. turbo rails marks the <turbo-cable-stream-source> element with a connected attribute once the subscription is confirmed, and its own system tests wait for exactly that attribute before they broadcast anything12. So should yours.

Fact three: jobs do not run in system tests unless you ask. Rails includes ActiveJob::TestHelper in integration tests, and system tests are integration tests13. Before each test it switches Active Job to the test adapter, which records jobs instead of running them13. The board in the Hotwire chapter broadcasts at once, after the commit, so this does not affect it. But the broadcast_replace_later_to in the authentication chapter's version renders in a background job, and in a system test that job would never run. If you use the _later broadcasts, put the action and the assertion inside a perform_enqueued_jobs do ... end block, so the jobs enqueued during it run straight away13.

Example: the workshop board with two browsers

This is the board from the Hotwire chapter: three columns with the ids column_waiting, column_in_repair and column_ready, one card per job with the id job_card_<id>, and one small form per allowed move. The fixture castletroy_puncture is a waiting job card at Castletroy for a bike called "Blue Brompton".

Two Capybara sessions play two screens in the workshop. Capybara's using_session runs a block in a named session, creating it with the current driver if it does not exist yet, and switches back afterwards3. Each session is its own browser with its own cookies, so the two screens log in separately, exactly as they do in the workshop.

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

class WorkshopBoardTest < ApplicationSystemTestCase
  setup do
    @card = job_cards(:castletroy_puncture)          # waiting, a Blue Brompton
    @board = workshop_board_path(@card.workshop)
    @card_id = "#job_card_#{@card.id}"
  end

  test "a move on a tablet appears on the wall screen" do
    using_session(:wall_screen) do
      sign_in_as users(:castletroy_mechanic)
      visit @board
      wait_for_live_updates
      within("#column_waiting") { assert_text "Blue Brompton" }
    end

    using_session(:tablet) do
      sign_in_as users(:castletroy_mechanic)
      visit @board
      within(@card_id) { click_on "Start repair" }

      # The tablet sees the move through the HTTP response
      within("#column_in_repair") { assert_text "Blue Brompton" }
    end

    using_session(:wall_screen) do
      # The wall screen sees it through the broadcast
      within("#column_in_repair") { assert_text "Blue Brompton" }
      within("#column_waiting") { assert_no_text "Blue Brompton" }
    end
  end

  private

  # turbo rails sets the "connected" attribute once Action Cable has
  # confirmed the subscription. Broadcasts sent before that are lost.
  def wait_for_live_updates
    assert_selector "turbo-cable-stream-source[connected]", visible: false
  end
end

Read it as a story. The wall screen logs in, opens the board and waits until it is listening. The tablet logs in, opens the board, and a mechanic presses "Start repair" on the Blue Brompton. The tablet sees the card move, which proves the stream response to the form. Then the test switches back to the wall screen and waits for the card to arrive in "In repair" and leave "Waiting", which proves the broadcast. Every step waits for a fact. Nothing waits for a time.

The visible: false matters. The stream source element is in the page but has no size, and Capybara by default finds only elements a person could see. And notice what the test does not check: which statuses are allowed, or who may see which workshop. Those are the model test from the Hotwire chapter and the request tests from the authentication chapter. This test exists for one seam, the one between the model's broadcast and a second screen.

Example: the drag, as a separate test

The board also moves cards by drag and drop. The Stimulus controller from the Hotwire chapter finds the matching move form and submits it, so the drag adds exactly one seam: the data-action attributes and the controller's JavaScript. One short test covers it.

  # test/system/workshop_board_test.rb, continued
  test "dragging a waiting card onto In repair moves it" do
    sign_in_as users(:castletroy_mechanic)
    visit @board

    find(@card_id).drag_to find("#column_in_repair")

    within("#column_in_repair") { assert_text "Blue Brompton" }
  end

Browsers do not let automation tools perform a native HTML drag and drop easily. Capybara's Selenium driver handles it by running a script that fires the same drag events a person's mouse would, for elements marked draggable14. That makes the test a check of the wiring, not of the browser's own drag code, which is exactly the seam that matters here.

JavaScript errors: make the browser tell you

A JavaScript error in the browser does not fail a Capybara test by itself. If a Stimulus controller throws while connecting, the page may still show the text the test is looking for, and the test passes while a feature is broken. Errors on the server are a different matter: Capybara raises them in the test by default, through its raise_server_errors setting7.

So make the browser report its errors too. How depends on the driver.

With Cuprite, it is one option. Cuprite passes its options to Ferrum, the library underneath, and Ferrum's js_errors: true re raises JavaScript errors in Ruby15. The turbo rails project runs its own system tests on Cuprite with exactly this option12.

With Selenium and Chrome, ask Chrome to keep its console log and read it after each test. Rails yields the browser options to a block on driven_by, and selenium webdriver's Chrome options accept logging_prefs, as below16.

# test/application_system_test_case.rb, with JavaScript errors failing the test
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  driven_by :selenium, using: BROWSER, screen_size: [1400, 1400] do |options|
    options.logging_prefs = { browser: "ALL" }   # keep the console log
  end

  teardown do
    errors = page.driver.browser.logs.get(:browser).select { |entry| entry.level == "SEVERE" }
    assert_empty errors.map(&:message), "The browser logged JavaScript errors"
  end
end

SEVERE is how Chrome labels console errors and uncaught exceptions in this log. Warnings stay out of it, which keeps the check from failing on noise. If a third party script you cannot control logs errors, filter by its URL rather than dropping the check.

Example: the error that did not break the test

In the example, Cian renamed the Stimulus controller file to workshop_board_controller.js and forgot to change data-controller="board" in the view. No error, just a controller that never connected, and the drag test failed, as it should. But a week later he added a connect() method that called a missing function. The page still rendered, the button test still passed, and drag and drop was dead. With the teardown check, the button test failed too, with the message from the browser console naming the function. The cost of the check: one block in the base class.

Choosing the driver that moves the browser

Capybara does not care which driver moves the browser. You can change one line and keep every test. Three are worth knowing as of June 2024.

Selenium WebDriver is the Rails default and the longest established of the three. It drives Chrome, Firefox, Edge and Safari through a driver for each browser6, and Selenium Manager now fetches those drivers for you6. Its strength is breadth and stability. Its cost is one more process between Ruby and the browser.

Cuprite is a pure Ruby driver with no Selenium or ChromeDriver dependency. It talks to Chrome or Chromium directly over the Chrome DevTools Protocol, through the Ferrum library15. The Rails 7.1 testing guide names it as the example of an alternative driver: add the gem, require capybara/cuprite, and write driven_by :cuprite2. Its strengths are fewer moving parts, JavaScript errors raised in Ruby, request headers and network traffic you can inspect, and a debugging mode15. Its limit is that it drives only Chrome and Chromium.

Playwright is Microsoft's browser automation library, known for waiting until an element is visible, stable, enabled and able to receive clicks before it acts17. It drives Chromium, Firefox and WebKit17. In Rails it is an option through two community gems by Yusuke Iwaki: playwright-ruby-client, which needs the Playwright driver installed separately, usually with npm, and capybara-playwright-driver, which plugs it into Capybara18. The driver's README itself points out that to use Playwright's own features, such as its auto waiting and locators, you are better off using the client directly18. Through Capybara, you mostly get Capybara.

Selenium WebDriverCupritePlaywright through Capybara
Rails defaultyesnamed in the Rails guideno
BrowsersChrome, Firefox, Edge, SafariChrome and ChromiumChromium, Firefox, WebKit
Extra piecesbrowser drivers, fetched by Selenium Managernone beyond Chromethe Playwright driver, usually through npm
JavaScript errors fail the testwith a few lines, in Chromeone option, js_errors: truethrough the client's events
Who maintains itthe Selenium projectthe rubycdp projecta community gem around Microsoft's Playwright
Version at 4 June 20244.210.150.5.1

My view: start with the default. Selenium with headless Chrome is what every Rails guide, every answer and every new colleague assumes, and Capybara's waiting matters far more to stability than the driver does. Switch to Cuprite when the JavaScript error check and the extra debugging tools would save you real time, and you only need Chrome. Reach for Playwright when you need WebKit, Safari's engine, in automation, or when your team already knows Playwright from a JavaScript project. Cian did know it, from his React years, and still chose the default for Freewheel: one less tool to install on every machine for no change in what the tests can see.

BDD with Cucumber: when Gherkin earns its keep

Behaviour driven development, as Dan North described it in 2006, starts from a conversation: what should this feature do, described as examples in the words of the business19. Gherkin is the format those examples are written in: Given some context, When something happens, Then this should be the result. Cucumber is the tool that runs Gherkin files as tests, and cucumber rails connects it to Rails and Capybara20.

The most useful sentence about Cucumber was written by its creator. In 2014, Aslak Hellesøy wrote that "the vast majority doesn't realise that Cucumber is a collaboration tool"21. His argument: many Rails teams adopted it as a test runner and dropped the conversations that gave it value, and then wondered why they were maintaining English sentences that only developers read.

That leads straight to the test I apply.

The reader test

Gherkin earns its keep only if someone who does not write Ruby reads the scenario before the code is written, and would notice if it were wrong. If that person exists, the feature file is a specification you can run, and the extra layer pays for itself in misunderstandings caught before they are built. If that person does not exist, the same scenario is a Minitest test with an extra file of regular expressions in between, and you pay for the translation on every change.

The test is about readers, not about the tool. Cucumber done well is excellent. Cucumber with no readers is overhead with good intentions. I write tests first and use Cucumber for BDD where the business reads the scenarios, which is why I hold the second half of that sentence as firmly as the first.

Declarative steps, not imperative ones

The Cucumber documentation draws the distinction that decides whether a feature file stays readable. An imperative step describes how the user operates the interface: fill in this field, press that button. A declarative step describes the behaviour of the application22. The documentation's test for a step is a good one to keep on a sticky note: will this wording need to change if the implementation does22? If yes, the step is too close to the screen.

Two more rules from the Cucumber documentation keep step definitions healthy. Organise steps by domain concept, not by feature, so a step about bookings is found and reused wherever bookings appear. And when one step needs to do the work of several, extract a helper method and call it, instead of calling steps from other steps23.

Example: the booking conversation

Niamh, the founder, knows exactly what should happen when two people want the same Saturday slot, because she has watched it go wrong at the counter more than once. She does not write Ruby. She does read the booking scenarios on Friday afternoons, and twice she has changed one. That makes her the reader. So in the example, Freewheel keeps Cucumber for the features Niamh signs off: booking, and later invoices and VAT. The board, which only mechanics use and developers specify, stays in plain system tests.

Here is the feature file she reads:

# features/book_a_repair.feature
Feature: Book a repair online
  Customers book at any hour, Friday night included.
  They pick a free slot with a mechanic and get a clear answer straight away.

  Background:
    Given Castletroy has a mechanic called Darragh

  @javascript
  Scenario: A new customer books a free Saturday slot
    Given Darragh is free at 09:00 on Saturday
    When a new customer books that slot for a "Green Dawes Galaxy"
    Then the customer sees the booking confirmed for 09:00 with Darragh
    And Darragh has exactly one booking at 09:00 on Saturday

  @javascript
  Scenario: Someone else takes the slot first
    Given Darragh is free at 09:00 on Saturday
    And a new customer has started booking that slot
    But another customer books the same slot first
    When the new customer confirms the booking
    Then the new customer is asked to pick another time
    And nothing the new customer typed is lost

Compare that with the imperative version a developer would write by reflex: When I fill in "Your name" with "Orla Quinlan", And I choose "09:00 with Darragh", And I press "Book this slot". Every one of those lines would change the day the form changes. None of them tells Niamh anything she cares about. The declarative version reads as a rule of the business, and the details of the form live in one place in Ruby.

Example: setting up cucumber rails

# Gemfile
group :test do
  gem "capybara"
  gem "selenium-webdriver"
  gem "cucumber-rails", require: false
  gem "database_cleaner-active_record"   # cucumber rails cleans the database between scenarios
end
bundle install
bin/rails generate cucumber:install   # writes features/support/env.rb and config/cucumber.yml
bundle exec cucumber                  # runs every feature

Three settings in the generated setup matter for browser scenarios20:

  • A scenario tagged @javascript switches Capybara to Capybara.javascript_driver, which is :selenium by default, and that means Firefox7. For Chrome, set it to :selenium_chrome_headless, which Capybara registers for you.
  • The generated env.rb sets DatabaseCleaner.strategy = :transaction for ordinary scenarios and Cucumber::Rails::Database.javascript_strategy = :truncation for browser scenarios20. Truncation empties the tables after each scenario, which is safe and slower. Rails' shared connection makes :transaction possible here too, and cucumber rails maps it to a shared connection strategy20, but the generated comment warns it can cause threading problems, so measure before you switch.
  • Cucumber does not load Rails fixtures. A Given step creates what the scenario needs. That is not a drawback: making the context visible is what Given is for.
# features/support/capybara.rb
Capybara.javascript_driver = :selenium_chrome_headless
# features/support/minitest.rb
# Lets step definitions use the same assertions as the Rails tests
require "minitest"

module MinitestAssertions
  include Minitest::Assertions
  attr_writer :assertions

  def assertions = @assertions ||= 0
end

World(MinitestAssertions)

Example: the step definitions and the helper

The helper holds every detail of the screen, in one place, named after what a customer does. The steps call it.

# features/support/booking_journey.rb
module BookingJourney
  CUSTOMER = { name: "Orla Quinlan", email: "orla@example.com" }.freeze

  def next_saturday_at(hour)
    Date.current.next_occurring(:saturday).in_time_zone.change(hour: hour)
  end

  def start_booking(slot, bike: "Green Dawes Galaxy")
    visit new_workshop_booking_path(@workshop)
    within_fieldset(slot.strftime("%A %-d %B")) do
      choose "#{slot.strftime('%H:%M')} with #{@mechanic.name}"
    end
    fill_in "Your name", with: CUSTOMER[:name]
    fill_in "Email", with: CUSTOMER[:email]
    fill_in "Your bike", with: bike
  end

  def confirm_booking
    click_on "Book this slot"
  end

  # Another customer, booking the same slot without a browser
  def book_directly(slot)
    customer = Customer.create!(name: "Ciarán Moloney", email: "ciaran@example.com")
    bike = customer.bikes.create!(make: "Raleigh", model: "Pioneer")
    Booking.create!(workshop: @workshop, mechanic: @mechanic, customer: customer,
                    bike: bike, starts_at: slot, ends_at: slot + 1.hour)
  end
end

World(BookingJourney)
# features/step_definitions/booking_steps.rb
Given("Castletroy has a mechanic called {word}") do |name|
  @workshop = Workshop.create!(name: "Castletroy", city: "Limerick")
  @mechanic = @workshop.mechanics.create!(name: name, email: "#{name.downcase}@freewheelcycles.example")
end

Given("{word} is free at 09:00 on Saturday") do |_name|
  @slot = next_saturday_at(9)   # free means: no booking exists, so nothing to create
end

Given("a new customer has started booking that slot") do
  start_booking(@slot)
end

Given("another customer books the same slot first") do
  book_directly(@slot)
end

When("a new customer books that slot for a {string}") do |bike|
  start_booking(@slot, bike: bike)
  confirm_booking
end

When("the new customer confirms the booking") do
  confirm_booking
end

Then("the customer sees the booking confirmed for 09:00 with {word}") do |name|
  assert_text "Booked. See you on Saturday."
  assert_text "09:00 with #{name} at Castletroy"
end

Then("{word} has exactly one booking at 09:00 on Saturday") do |_name|
  assert_equal 1, Booking.where(mechanic: @mechanic, starts_at: @slot).count
end

Then("the new customer is asked to pick another time") do
  assert_text "was just taken. Please pick another time."
end

Then("nothing the new customer typed is lost") do
  assert_field "Your name", with: BookingJourney::CUSTOMER[:name]
end

The {word} and {string} placeholders are Cucumber Expressions22, the readable alternative to regular expressions in step definitions. assert_text and assert_field are Capybara's own waiting assertions, the same ones the system test uses, so the waiting rules from earlier apply unchanged.

One order matters in the first scenario. The step that counts bookings in the database comes after the step that waits for the confirmation on screen. Counting first would race the request, the same race as the sign in helper's. Assert on the screen, then on the database.

Side by side: Cucumber or plain system tests

Here are the two versions of the same journey, compared on what they cost and what they buy.

Plain system testCucumber with cucumber rails
Files for the booking journeyone test filea feature file, a step file, a helper and two support files
Who can read itdevelopersanyone who knows the business
Test dataRails fixtures, shared with all other testscreated in Given steps
Database between teststransaction rollback, shared connectiontransaction, or truncation for browser scenarios
Waiting and assertionsCapybarathe same Capybara
Runs withbin/rails test:systembundle exec cucumber
Cost of a form changeedit the testedit the helper, the feature file stays
Best forseams that only developers specifyrules the business owns and reads

The rows that decide it are "who can read it" and "cost of a form change". The browser, the waiting and the stability are the same in both, because both are Capybara underneath. Cucumber does not make a test more reliable or more realistic. It makes it readable by people outside the team, and that is all it needs to do.

My view: default to plain system tests, and add Cucumber for a feature on the day a named person outside the development team agrees to read its scenarios. Review that agreement every few months. If the scenarios have not been read since they were written, fold them back into system tests and delete the Gherkin without guilt. The conversation was the valuable part, and it already happened.

Test data for end to end tests

Browser tests are where bad test data hurts most, because a failure costs seconds to reproduce and the cause is often far from the symptom. Five habits keep it under control.

  • Set up through the model, act through the browser. Create records with fixtures or with create!, never by clicking through other screens. Only the action under test goes through the browser. A booking test that first logs in as a manager and creates a mechanic through the admin screens tests three features and fails for reasons that have nothing to do with booking. The sign in helper is the one exception, because the session cookie has to come from the browser.
  • Never depend on today's date. Compute dates relative to today, as next_occurring(:saturday) does. A test written on a Tuesday that books "Saturday 8 June" stops working on 9 June.
  • Use records the screen can identify. "Blue Brompton" is a name a person sees on the card. Find things by what the screen shows, and scope with within when the same text could appear twice.
  • Keep each test independent. Rails runs tests in random order and rolls back each one. A test that only passes after another has run is a flaky test waiting for an unlucky seed.
  • Know where your threads are. Records created in the test are visible to the server because the connection is shared. The browser's own clock is not part of that process, and travel_to does not move it. Keep time sensitive rules, such as the cut off for same day bookings, in model tests, where you control the clock.

Screenshots, HTML and running in CI

When a system test fails, Rails saves a screenshot to tmp/screenshots and prints its path5. Set RAILS_SYSTEM_TESTING_SCREENSHOT_HTML=1 and it saves the page's HTML next to it, which is often more useful than the picture, because you can search it for the element you expected5. You can also call take_screenshot anywhere in a test while you debug2.

In CI, those files are only useful if you can get at them. Here is the part of a GitHub Actions workflow that runs the system tests in headless Chrome and keeps the screenshots when something fails:

# .github/workflows/ci.yml (the system test job only)
  system_tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: ruby/setup-ruby@v1
        with:
          bundler-cache: true
      - name: Prepare the database
        run: bin/rails db:test:prepare
      - name: Run system tests
        run: bin/rails test:system
      - name: Keep screenshots of failures
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: screenshots
          path: tmp/screenshots

GitHub's hosted Ubuntu runners come with Chrome installed, and GitHub Actions sets CI=true, which switches Cian's base class to headless Chrome24. A full workflow, with PostgreSQL and Redis as services, parallel jobs and a policy for flaky tests, is the subject of the chapter on CI at the end of this series.

Example: the order Freewheel's CI runs things in

Cian runs the fast tests first and the browser tests only if those pass. Model and request tests fail in seconds with precise messages, and there is no point starting Chrome for a build whose VAT calculation is already wrong. For the example, the numbers today are small: the whole unit and request suite runs in under a minute, the system tests and the Cucumber features in a few minutes. The arithmetic of the flaky suite above is why Cian treats every red system test run as a bug to understand, not a button to press again.

For the person paying for this

You do not need to read the tests to judge them. Ask these questions, and listen for specific answers.

  • "Which journeys are tested in a real browser, and why those?" A good answer names a short list, booking, checkout, the live screen, and the reason for each. "All of them" means a slow suite. "None" means the seams are untested.
  • "How often does the build fail for no reason?" A trustworthy suite almost never does. If the answer is "now and then, we just run it again", the team has stopped believing its own tests.
  • "Is there a sleep anywhere in the tests?" The right answer is no, or one, with a written reason.
  • "Who reads the Gherkin?" If the team uses Cucumber, there should be a name. If nobody outside the team reads it, you are paying for a translation layer nobody uses.
  • "What do you see when a browser test fails in CI?" The answer should include a screenshot and the page's HTML, kept by the build.

The code, the tests and the CI setup are yours, like the rest of the application. This is how I build web applications with Ruby on Rails, and my web application development page explains how I work. If you want to look at your own test suite against these questions, the free workshop is a good place to start.

Conclusion

Browser tests catch real bugs when each one guards a seam, a place where two technologies meet and each assumes something about the other: the server and Turbo, the HTML and Stimulus, the model and Action Cable. If you cannot finish the sentence "this test fails if ___, and no faster test would notice", write the test one level down.

They stay stable when every step waits for a fact instead of a time. Capybara already retries every finder and matcher for up to two seconds. Your part is to use the waiting forms, assert_no_text instead of a negated has_text?, to wait for the live connection before you broadcast, and never to write sleep. Flakiness compounds: 38 tests at 1% each give a red run one time in three.

They stay fast when the browser does only the action under test. Set up through the model, act through the browser, keep the rules in model and request tests.

And Cucumber earns its keep when someone who does not write Ruby reads the scenarios before the code exists. Then a feature file is a specification you can run. Without that reader, a plain system test says the same thing in fewer files.

The Django version of this chapter builds the same journey and the same live board with pytest bdd and Playwright, and the last chapter of the series takes both suites into CI.

Want to know which of your journeys deserve a browser test, and why your build goes red for no reason? Bring your suite to the free workshop and we will find its seams together. The first two weeks of work are on me.

Sources

  1. 1.

    RubyGems.org version histories, checked as of 4 June 2024: rails 7.1.3, capybara 3.40.0 (26 January 2024 in its changelog), selenium-webdriver 4.21.0 (16 May 2024), turbo-rails 2.0.5 (8 March 2024), cuprite 0.15 (4 November 2023), cucumber-rails 3.0.0 (1 November 2023), cucumber 9.2.0 (19 March 2024), capybara-playwright-driver 0.5.1 (19 February 2024), https://rubygems.org

  2. 2.

    Ruby on Rails Guides (v7.1), Testing Rails Applications, System Testing and Parallel Testing, https://guides.rubyonrails.org/v7.1/testing.html

  3. 3.

    Capybara, README, version 3.40.0, sections "Asynchronous JavaScript (Ajax and friends)", "Transactions and database setup" and "Using sessions", teamcapybara, GitHub, https://github.com/teamcapybara/capybara/blob/3.40.0/README.md

  4. 4.
  5. 5.

    Rails 7.1.3, ActionDispatch::SystemTesting::TestHelpers::ScreenshotHelper, GitHub, https://github.com/rails/rails/blob/v7.1.3/actionpack/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb

  6. 6.

    Rails 7.1.0, railties CHANGELOG, "Omit webdrivers gem dependency from Gemfile template", https://github.com/rails/rails/blob/v7.1.0/railties/CHANGELOG.md and Selenium, Selenium Manager documentation, https://www.selenium.dev/documentation/selenium_manager/ and Selenium 4.11.0 released, 31 July 2023, https://www.selenium.dev/blog/2023/selenium-4-11-0-released/

  7. 7.

    Capybara 3.40.0 source: configuration defaults (default_max_wait_time 2, default_retry_interval 0.01, raise_server_errors true, javascript_driver :selenium), https://github.com/teamcapybara/capybara/blob/3.40.0/lib/capybara.rb and the synchronize loop, https://github.com/teamcapybara/capybara/blob/3.40.0/lib/capybara/node/base.rb and the registered drivers, https://github.com/teamcapybara/capybara/blob/3.40.0/lib/capybara/registrations/drivers.rb

  8. 8.

    Martin Fowler, Eradicating Non Determinism in Tests, martinfowler.com, 14 April 2011, https://martinfowler.com/articles/nonDeterminism.html

  9. 9.

    Ruby on Rails API (v7.1), DateAndTime::Calculations, next_occurring, https://api.rubyonrails.org/v7.1/classes/DateAndTime/Calculations.html

  10. 10.

    Turbo Handbook, Navigate with Turbo Drive, form submissions, 37signals, https://turbo.hotwired.dev/handbook/drive

  11. 11.
  12. 12.
  13. 13.
  14. 14.
  15. 15.

    Cuprite, README, version 0.15, rubycdp, GitHub, https://github.com/rubycdp/cuprite/blob/v0.15/README.md and Ferrum, README, version 0.15 (js_errors option), https://github.com/rubycdp/ferrum/blob/v0.15/README.md

  16. 16.
  17. 17.

    Playwright documentation, Auto waiting (actionability checks), Microsoft, https://playwright.dev/docs/actionability and Browsers, https://playwright.dev/docs/browsers

  18. 18.

    Yusuke Iwaki, capybara-playwright-driver, README, version 0.5.1, GitHub, https://github.com/YusukeIwaki/capybara-playwright-driver/blob/0.5.1/README.md and playwright-ruby-client, README, version 1.44.0, https://github.com/YusukeIwaki/playwright-ruby-client/blob/1.44.0/README.md

  19. 19.

    Dan North, Introducing BDD, dannorth.net, 2006, https://dannorth.net/introducing-bdd/

  20. 20.
  21. 21.

    Aslak Hellesøy, The world's most misunderstood collaboration tool, Cucumber blog, 3 March 2014, https://cucumber.io/blog/collaboration/the-worlds-most-misunderstood-collaboration-tool/

  22. 22.

    Cucumber documentation, Writing better Gherkin (declarative and imperative style), https://cucumber.io/docs/bdd/better-gherkin/ and Cucumber Expressions, https://github.com/cucumber/cucumber-expressions

  23. 23.

    Cucumber documentation, Anti patterns (feature coupled step definitions, conjunction steps), https://cucumber.io/docs/guides/anti-patterns/

  24. 24.

    GitHub, actions/upload-artifact, release v4.0.0, 14 December 2023, https://github.com/actions/upload-artifact/releases/tag/v4.0.0 and GitHub Docs, Variables, default environment variables (CI), https://docs.github.com/en/actions/learn-github-actions/variables and actions/runner-images, Ubuntu 22.04 image (browsers installed), https://github.com/actions/runner-images/blob/main/images/ubuntu/Ubuntu2204-Readme.md

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter