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 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. Cogwell Cycles (cogwellcycles.example) is an invented chain of six bicycle repair workshops in Sheffield, founded by Hannah, with 38 mechanics and about 1,150 repair bookings a week. Saturday morning is the peak: 30% of the week's online bookings arrive between Friday 6pm and Saturday noon. Its two developers, Priya and Owen, 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-actionattribute 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: Cogwell's seam list
Priya and Owen 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.
| Bug | Seam? | Fastest test that catches it |
|---|---|---|
| Two bookings for the same mechanic and slot | no | model test plus the database constraint |
| A slot taken while the customer types shows no message | yes, server and Turbo | system test |
| The price of a repair includes VAT at 20% | no | model test |
| A mechanic sees another workshop's job cards | no | request test |
| A move on one tablet never reaches the wall screen | yes, model and Action Cable | system test with two browsers |
| Dragging a card does nothing | yes, HTML and Stimulus | system test |
| "Mark ready" is not offered for a waiting card | no | model test of the allowed moves |
| The confirmation email has the wrong time | no | mailer 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:
- A driver.
driven_by :seleniumtells Capybara to control the browser through Selenium WebDriver, the long standing standard for browser automation.using: :chromeopens a visible Chrome window.:headless_chromeruns Chrome without a window, which is what you want on a build server2. - A server. Capybara starts your application in Puma, on a random port, in the same Ruby process as the test3.
- 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.
- A screenshot on failure. Rails calls
take_failed_screenshotbefore teardown, and saves the image totmp/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: Cogwell's base class
Owen changed three things in 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 Cogwell'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.
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: Owen's first board test
Owen'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 tests fails at random with probability , and the failures are independent, the chance that a whole run is green is:
Here is the chance that one test fails for no reason on one run, and 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 Cogwell's suite reaches two years in. If each one has a 1% chance of a random failure, then . About one run in three is red for no reason. At 2% per test, : 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.
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 Cogwell
The chart below is illustrative: invented counts for the example, not a measurement. It shows how the failures Owen 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.
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 Dev"), 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, kelham and ecclesall, and a few mechanics and customers.
# test/fixtures/workshops.yml
kelham:
name: Kelham Island
city: Sheffield
ecclesall:
name: Ecclesall Road
city: Sheffield
# test/fixtures/mechanics.yml
dev:
workshop: kelham
name: Dev
email: dev@cogwellcycles.example
# test/fixtures/customers.yml and test/fixtures/bikes.yml
regular:
name: Lou Marsh
email: lou@example.com
# bikes.yml
lou_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(:kelham)
@saturday = Date.current.next_occurring(:saturday) # never a hard coded date
end
test "a new customer books a Saturday slot with Dev" do
visit new_workshop_booking_path(@workshop)
within_fieldset(day_label(@saturday)) { choose "09:00 with Dev" }
fill_in "Your name", with: "Morgan Fell"
fill_in "Email", with: "morgan@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 Dev at Kelham Island"
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 Dev" }
fill_in "Your name", with: "Morgan Fell"
fill_in "Email", with: "morgan@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(:dev),
customer: customers(:regular), bike: bikes(:lou_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: "Morgan Fell" # 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 kelham_puncture is a waiting job card at Kelham Island 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(:kelham_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(:kelham_mechanic)
visit @board
wait_for_live_updates
within("#column_waiting") { assert_text "Blue Brompton" }
end
using_session(:tablet) do
sign_in_as users(:kelham_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(:kelham_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, Owen 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 WebDriver | Cuprite | Playwright through Capybara | |
|---|---|---|---|
| Rails default | yes | named in the Rails guide | no |
| Browsers | Chrome, Firefox, Edge, Safari | Chrome and Chromium | Chromium, Firefox, WebKit |
| Extra pieces | browser drivers, fetched by Selenium Manager | none beyond Chrome | the Playwright driver, usually through npm |
| JavaScript errors fail the test | with a few lines, in Chrome | one option, js_errors: true | through the client's events |
| Who maintains it | the Selenium project | the rubycdp project | a community gem around Microsoft's Playwright |
| Version at 4 June 2024 | 4.21 | 0.15 | 0.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. Owen did know it, from his React years, and still chose the default for Cogwell: 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
Hannah, 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. 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, Cogwell keeps Cucumber for the features Hannah 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 Kelham Island has a mechanic called Dev
@javascript
Scenario: A new customer books a free Saturday slot
Given Dev 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 Dev
And Dev has exactly one booking at 09:00 on Saturday
@javascript
Scenario: Someone else takes the slot first
Given Dev 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 "Morgan Fell", And I choose "09:00 with Dev", And I press "Book this slot". Every one of those lines would change the day the form changes. None of them tells Hannah 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
@javascriptswitches Capybara toCapybara.javascript_driver, which is:seleniumby default, and that means Firefox7. For Chrome, set it to:selenium_chrome_headless, which Capybara registers for you. - The generated
env.rbsetsDatabaseCleaner.strategy = :transactionfor ordinary scenarios andCucumber::Rails::Database.javascript_strategy = :truncationfor browser scenarios20. Truncation empties the tables after each scenario, which is safe and slower. Rails' shared connection makes:transactionpossible 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
Givenstep creates what the scenario needs. That is not a drawback: making the context visible is whatGivenis 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: "Morgan Fell", email: "morgan@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: "Lou Marsh", email: "lou@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("Kelham Island has a mechanic called {word}") do |name|
@workshop = Workshop.create!(name: "Kelham Island", city: "Sheffield")
@mechanic = @workshop.mechanics.create!(name: name, email: "#{name.downcase}@cogwellcycles.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 Kelham Island"
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 test | Cucumber with cucumber rails | |
|---|---|---|
| Files for the booking journey | one test file | a feature file, a step file, a helper and two support files |
| Who can read it | developers | anyone who knows the business |
| Test data | Rails fixtures, shared with all other tests | created in Given steps |
| Database between tests | transaction rollback, shared connection | transaction, or truncation for browser scenarios |
| Waiting and assertions | Capybara | the same Capybara |
| Runs with | bin/rails test:system | bundle exec cucumber |
| Cost of a form change | edit the test | edit the helper, the feature file stays |
| Best for | seams that only developers specify | rules 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
withinwhen 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_todoes 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 Owen'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 Cogwell's CI runs things in
Owen 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 Owen 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
sleepanywhere 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.
