ScreenshotNeo

BlogHow-to

How to Fix RSpec Capybara Test Suite Timeouts

Find the timeout layer in RSpec and Capybara, replace flaky sleeps, tune waits, and make browser specs reliable in CI.

By the ScreenshotNeo team30 September 20269 min read

How to Fix RSpec Capybara Test Suite Timeouts

RSpec and Capybara timeouts have several possible causes. A selector wait, Selenium command, Rails server boot, asset compilation step, or the RSpec process itself can be the layer that stopped progressing. Increasing Capybara.default_max_wait_time helps only when Capybara is still waiting for a synchronization-aware condition.

The reliable fix is to identify the layer first, reproduce one example, then change the narrowest configuration that addresses it. This guide shows the diagnostic sequence, runnable RSpec code, driver and server settings, CI checks, and ways to remove arbitrary sleeps.

1. Identify which layer timed out

Read the exception before changing a timeout. The error usually tells you which subsystem stopped:

A timeout can occur in Capybara, the browser, the Rails server, or the test process.
A timeout can occur in Capybara, the browser, the Rails server, or the test process.
Symptom Likely layer First check
expected to find text or selector matcher failure Capybara synchronization Use a waiting matcher and inspect the page state
Selenium transport error, disconnected session, or browser crash Browser or driver Chrome/Chromedriver versions, headless flags, and session creation
Connection refused, server failed to start, or port bind error Rails test server Server configuration, port availability, and boot logs
Failure while compiling JavaScript or CSS Application boot/assets Build command, dependencies, and CI environment
No exception and the process remains alive Process-level hang Frozen time, open connections, deadlock, or a stuck external call

Run the smallest reproduction and preserve the output:

bundle exec rspec spec/system/checkout_spec.rb:42 --format documentation

Capture the Capybara screenshot and server log when your configuration provides them. A screenshot can show that the page is still on a login redirect, a cookie banner is covering the target, or the application rendered an error page.

2. Replace sleeps with Capybara synchronization

Capybara’s synchronization-aware predicates and RSpec matchers retry until the condition is true or the configured wait expires. Its README describes this as a reason you do not need to manually wait for asynchronous processes. Prefer a matcher that states the condition you need:

# Fragile
sleep 2
expect(page.body).to include("Saved")

# Synchronization-aware
click_button "Save"
expect(page).to have_content("Saved")

Use waiting selectors for elements that appear after an Ajax request:

expect(page).to have_css("[data-testid='results']")
within "[data-testid='results']" do
  expect(page).to have_text("Invoice paid")
end

Be careful with negative assertions. A predicate that is already successful can return immediately, while a negative matcher waits after a failed check. For example, has_no_xpath? waits for the element to disappear; a negated predicate can behave differently if the element is absent at the first check. Express disappearance with the matcher form:

expect(page).to have_no_css(".loading-spinner")

3. Tune the wait narrowly

Capybara documents this configuration example:

Capybara.default_max_wait_time = 5

Five seconds is an example, not a universal value. Keep the global wait near the time your application normally needs. A very high global value makes every genuine failure slow to report and can hide a broken server.

For one unusually slow operation, pass a per-call wait:

expect(page).to have_css(".report-ready", wait: 15)
find(".export", wait: 10).click

If you use multiple sessions or Capybara’s threadsafe mode, set the value on the session that needs it:

session = Capybara::Session.new(:rack_test, Rails.application)
session.config.default_max_wait_time = 10
session.visit "/reports"

This avoids making unrelated sessions slower. Keep a comment explaining why the operation needs extra time, so the setting can be revisited when the application improves.

4. Match the driver to the spec

RSpec Rails system specs use Capybara and, in the cited documentation, default to Selenium with Chrome. Capybara’s RSpec integration lets non-JavaScript examples use the faster :rack_test driver, while JavaScript examples can opt into a JavaScript-capable driver with js: true or an explicit driver.

RSpec.describe "Account settings", type: :system do
  it "updates the profile without JavaScript", js: false do
    visit "/account"
    fill_in "Display name", with: "Ada"
    click_button "Save"
    expect(page).to have_content("Profile updated")
  end

  it "loads the live preview", js: true do
    visit "/account"
    fill_in "Display name", with: "Ada"
    expect(page).to have_css(".preview", wait: 10)
  end
end

Do not launch a real browser for an assertion that only needs an HTTP response and HTML. Move controller-independent behavior to request specs:

RSpec.describe "Invoices", type: :request do
  it "returns the invoice" do
    get "/invoices/123"
    expect(response).to have_http_status(:ok)
    expect(response.body).to include("Invoice")
  end
end

Request specs are faster HTTP-level tests and do not exercise UI or JavaScript. Keep browser specs for user-visible behavior, JavaScript, navigation, and integration with the real browser.

5. Verify the Rails server and boot path

Capybara can use an explicit server such as Puma:

Capybara.server = :puma
Capybara.server_port = 0 # let the OS choose a free port

Use a fixed port only when your environment requires it. A server that cannot bind, crashes during boot, or stalls while compiling assets will not be repaired by a larger selector wait. RSpec Rails’ system integration requires both Capybara and a web server; missing dependencies should fail during setup rather than appear as a mysterious browser timeout.

When the server is the problem, run the application boot command outside RSpec and inspect its first error:

RAILS_ENV=test bundle exec rails runner 'puts Rails.application.class'
RAILS_ENV=test bundle exec rails server -p 4567

Check database preparation, environment variables, migrations, asset builds, and port conflicts. In CI, record the elapsed time from process start to the first successful HTTP response.

6. Check time control and network stubs

Freezing application time can interfere with Capybara’s timeout clock on Ruby and platform combinations that do not provide a monotonic process clock. Ajax polling may never reach its deadline, leaving the example hanging. Prefer a time-travel approach that preserves elapsed-time measurement where your stack supports it, and avoid freezing the clock around browser synchronization.

Inspect WebMock when a timeout creates many connections. Capybara documents a “Too many open files” failure mode caused by repeated requests during a timeout and gives this workaround to investigate:

WebMock.disable_net_connect!(allow_localhost: true,
  net_http_connect_on_start: true)

Use the option only when it matches your WebMock version and test policy. Make external calls deterministic with explicit stubs, and allow the Capybara server’s localhost traffic.

7. Make JavaScript tests deterministic

Most flaky waits come from an assertion that does not describe the real readiness condition. Wait for a rendered element, a status change, or a disabled/enabled state rather than a guessed delay:

click_button "Submit"
expect(page).to have_css("[data-state='complete']", wait: 12)
expect(page).to have_button("Submit", disabled: false)

Ensure the page’s JavaScript reports failures visibly. A browser console error, failed asset request, or unhandled promise can leave the expected element absent forever. In CI, retain browser logs and the HTML produced at failure. Use stable data-testid attributes instead of selectors tied to layout or generated class names.

8. Compare local and CI environments

There is no universal CI timeout value. Compare the exact versions and runtime conditions that affect browser startup and application boot:

  • Ruby, Rails, Capybara, Selenium, Chrome, and Chromedriver versions
  • Database engine and schema state
  • Node.js, package manager, and compiled asset versions
  • Headless browser flags, shared memory size, and container limits
  • Environment variables, feature flags, locale, timezone, and network access

Log three milestones for a failing job: server started, browser session created, and first failing command. If the first two are slow, tune CI resources or boot work. If only a selector is slow, use a scoped Capybara wait. If the process stops producing logs, investigate a deadlock, frozen clock, open connection, or browser crash instead of increasing default_max_wait_time.

9. A complete configuration example

Place shared setup in your system-spec support file and keep per-example exceptions local:

# spec/support/capybara.rb
require "capybara/rspec"

Capybara.default_max_wait_time = 5
Capybara.server = :puma
Capybara.save_path = ENV.fetch("CAPYBARA_ARTIFACTS", "tmp/capybara")

RSpec.configure do |config|
  config.before(:each, type: :system) do
    driven_by(:selenium, using: :headless_chrome,
      screen_size: [1400, 1000])
  end
end

# spec/system/report_spec.rb
RSpec.describe "Reports", type: :system do
  it "renders a slow report" do
    visit "/reports"
    expect(page).to have_css("[data-testid='report-ready']", wait: 20)
  end
end

Adapt the driver registration to the Selenium and Capybara versions in your application. The important properties are explicit driver selection, a reasonable global wait, and a documented local exception.

10. Troubleshooting common failures

Error or behavior Cause Fix
Element never appears Wrong selector, JavaScript error, or request failure Save HTML, inspect browser/server logs, and wait for a real readiness element
Every failure takes a long time Global wait is too high Lower default_max_wait_time; add a per-call wait only where needed
Connection refused Rails server failed or port is unavailable Run the server directly, inspect boot output, and use a free port
Chrome session cannot start Browser/driver mismatch or container limits Compare versions, headless flags, shared memory, and CI packages
Test hangs after freezing time Timeout clock cannot advance Use time travel that preserves monotonic elapsed time
Too many open files Repeated network attempts during a wait Review WebMock and investigate net_http_connect_on_start: true
Works locally, fails in CI Different assets, versions, resources, or environment Log startup milestones and compare the complete matrix
Browser starts for simple HTML checks Spec marked as system/JavaScript unnecessarily Use request specs or :rack_test where no browser is required

11. Performance, reliability, and cost

Browser startup, server boot, and asset compilation dominate many suites. Reuse setup where safe, keep JavaScript coverage focused, and move HTTP behavior to request specs. A short, accurate wait improves feedback because failures surface promptly; a large blanket wait increases the cost of every broken example.

Clean captures remove common overlays before the screenshot is billed.
Clean captures remove common overlays before the screenshot is billed.

Reliability comes from deterministic readiness conditions and visible diagnostics. Capture the page, browser log, server log, versions, and the first failing command. Run a single example repeatedly before running the whole suite. When a timeout is intermittent, record whether it correlates with parallel workers, database contention, external calls, or resource pressure.

If you need screenshots of pages for documentation, visual review, or debugging outside the test browser, ScreenshotNeo provides a website screenshot API and MCP server. It accepts one GET request and returns PNG, JPEG, WebP, or PDF. Its clean capture removes known cookie-consent banners, newsletter popups, and chat widgets before the shot; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed as clean shots. Response headers identify the page verdict and whether it was billed.

Or skip the browser setup

For a direct page capture, use the documented API examples at ScreenshotNeo docs:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also supports full-page capture with lazy images, CSS-selector element capture, dark mode, device presets and custom viewports, retina scale, PDF output, custom CSS and JavaScript, clicks, selector or network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous jobs with signed webhooks, bulk capture, a usage API, and an OpenAPI specification. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

There are no browser drivers to install for this call. Cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed; an MCP server lets AI agents take screenshots; 1,000 screenshots a month are free with no card, and paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

FAQ

Should I always increase Capybara.default_max_wait_time?

No. Increase it only when a synchronization-aware condition genuinely needs more time. A browser, server, boot, or process timeout requires a different fix.

What wait value should CI use?

Measure your application’s normal readiness time in that CI environment and add a small margin. The Capybara documentation’s five-second setting is an example, not a universal CI recommendation.

Does sleep ever belong in a Capybara spec?

Rarely. A sleep does not verify readiness and makes fast runs wait unnecessarily. Prefer a matcher for the state the user needs to see.

When should I use a request spec?

Use one when the behavior is HTTP-level and does not require a browser, rendered UI, or JavaScript. Request specs avoid browser startup and synchronization overhead.

Why can a negative assertion behave unexpectedly?

Some predicates return immediately when their condition is already true. Use a negative matcher such as have_no_css when you need Capybara to wait for an element to disappear.

Can screenshots diagnose a timeout?

Yes. A failure screenshot can reveal redirects, overlays, missing content, or an error page. It cannot replace server logs or browser logs when the page never loads.

Primary references: Capybara documentation, RSpec system specs, and RSpec Rails.