Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Call save_screenshot while the Selenium browser is still running: @driver.save_screenshot('tmp/screenshots/example.png'). In a Capybara spec, use save_screenshot on the session. For hands-off failure artifacts, load capybara-screenshot/rspec after capybara/rspec. The examples below show where each approach belongs, how to avoid common lifecycle errors, and how to preserve files in continuous integration.

Pick the screenshot method that matches your spec

Test setup Capture call Best use
Direct Selenium WebDriver @driver.save_screenshot(path) A precise screenshot at a known point in an example
Capybara with a Selenium driver save_screenshot(path) Feature or system specs where Capybara owns the session
RSpec failure capture capybara-screenshot/rspec Automatic image and HTML artifacts when supported browser specs fail

All three require a real browser driver. Capybara’s default :rack_test driver is not a browser and does not execute JavaScript, so it cannot provide a Selenium browser screenshot. Choose a Selenium-backed driver such as :selenium, :selenium_chrome, or a headless Selenium option described by your installed Capybara version.

Direct Selenium WebDriver in an RSpec example

Selenium’s Ruby API saves a PNG of the current viewport. Create the destination directory, navigate, capture, and only then quit the driver.

require 'fileutils'
require 'selenium-webdriver'

RSpec.describe 'page behavior' do
  before do
    @driver = Selenium::WebDriver.for :chrome
  end

  after do
    @driver&.quit
  end

  it 'captures the current view' do
    @driver.get('https://example.com')

    FileUtils.mkdir_p('tmp/screenshots')
    @driver.save_screenshot('tmp/screenshots/example.png')
  end
end

FileUtils.mkdir_p is ordinary Ruby setup, not a Selenium requirement. A relative filename is resolved from the process working directory, so a stable artifact folder such as tmp/screenshots is easier to find locally and in CI. Use the .png extension; Selenium’s Ruby API documents PNG output and warns when the extension does not match.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Capture at the useful moment

Place the call after navigation and any action or assertion whose visual state you need to inspect. For example:

it 'shows the validation message' do
  @driver.get('https://example.com/signup')
  @driver.find_element(name: 'email').send_keys('not-an-email')
  @driver.find_element(css: 'button[type="submit"]').click
  @driver.save_screenshot('tmp/screenshots/signup-validation.png')
end

The screenshot represents the viewport, not automatically the entire document. Selenium’s optional full_page argument works only with drivers that implement full-page capture; unsupported drivers raise an unsupported-operation error. Treat viewport capture as the portable default.

Make names safe for parallel runs

Parallel examples can overwrite a shared filename. Include an example identifier, process number, or timestamp in the path, and keep the directory writable by the test process:

name = "tmp/screenshots/#{Process.pid}-#{RSpec.current_example.id.hash}.png"
FileUtils.mkdir_p(File.dirname(name))
@driver.save_screenshot(name)

If your parallel-test tool supplies a worker identifier, prefer that over a timestamp so two workers cannot choose the same name.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Capybara screenshots with RSpec

Capybara’s session method delegates to the active driver. In a Selenium-backed feature or system spec, the simplest call is:

require 'capybara/rspec'

RSpec.describe 'account page', type: :feature do
  it 'captures the rendered page' do
    driven_by :selenium_chrome
    visit '/account'
    save_screenshot('account-page.png')
  end
end

Whether driven_by is available and which driver names are registered depends on your Capybara/Rails setup. You can instead configure the driver in your suite or metadata. The important requirement is that the example uses Selenium rather than :rack_test.

Where Capybara writes the file

For a relative path, Capybara resolves the filename against its configured save_path. With no path, it generates a filename under that directory. Set a stable save directory using the configuration supported by your installed Capybara version, then verify the resulting path in a local run. Configuration APIs and defaults can change between releases, so check the versioned Capybara documentation when upgrading.

Capture screenshots automatically when an example fails

The capybara-screenshot gem adds automatic failure artifacts for supported browser drivers. Add it to your test dependencies, then require the adapters in this order:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
require 'capybara/rspec'
require 'capybara-screenshot/rspec'

Loading the screenshot adapter before Capybara’s RSpec integration can prevent hooks from being installed correctly. The project documents a screenshot plus the failed page HTML for supported driver failures. Rails-like applications commonly default to tmp/capybara; non-Rails projects use the working directory unless configured otherwise. Confirm the exact default for the gem version in your bundle.

Useful capybara-screenshot controls

The gem documents manual helpers such as screenshot_and_save_page, along with options to:

  • disable automatic failure capture;
  • change the save path and filename prefix;
  • control timestamp suffixes;
  • prune older artifacts; and
  • adjust links printed in RSpec output.

Option names and defaults are version-specific. Read the README shipped with the version you install before placing these settings in shared support files. Generated HTML can contain page content, user data, or test data; review it before uploading or sharing.

Hooks: save before Selenium quits

RSpec runs teardown hooks after an example. If an after hook quits the driver first, a later failure hook cannot capture anything. Keep the browser alive until the screenshot code has run:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
RSpec.describe 'checkout' do
  before do
    @driver = Selenium::WebDriver.for :chrome
  end

  after do |example|
    if example.exception
      FileUtils.mkdir_p('tmp/screenshots')
      @driver.save_screenshot("tmp/screenshots/#{example.id.hash}.png")
    end
    @driver&.quit
  end

  it 'completes payment' do
    @driver.get('https://example.com/checkout')
    # assertions and interactions
  end
end

Guard the driver because setup itself can fail. If you use a framework or gem that already owns teardown, put custom capture logic into the supported failure hook rather than adding a second competing lifecycle.

CI artifact handling

Screenshot creation only writes a file; your CI service must preserve that directory after the job. Configure the provider’s artifact upload feature for the exact folder you chose, such as tmp/screenshots or tmp/capybara. Because artifact syntax differs by provider, use that provider’s current configuration reference. A reliable workflow is:

  1. Create the directory before the first capture.
  2. Use unique names for parallel workers.
  3. Run the test command and allow failures to finish so the upload step executes.
  4. Upload the screenshot and, when enabled, HTML directories as build artifacts.
  5. Apply the retention and access policy required for pages that may contain sensitive data.

Troubleshooting Selenium and RSpec screenshots

“No such file or directory”

The parent directory does not exist. Call FileUtils.mkdir_p (direct Selenium) or configure Capybara’s save path to a directory created by the job. Also check the process working directory and write permissions.

A blank or missing image after a failure

The browser may already have been quit, or the failure occurred during driver startup. Capture in a hook that runs before quit, guard a possibly nil driver, and inspect the original exception separately. A startup failure cannot produce a browser screenshot.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Capybara says the driver cannot screenshot

Check the current driver. :rack_test is not a browser and does not execute JavaScript. Select a registered Selenium driver and ensure Chrome/Chromium plus its compatible driver are available on the machine.

Automatic files are not generated

Verify both requires and their order: capybara/rspec first, then capybara-screenshot/rspec. Confirm the failing example uses a supported browser driver and that no suite configuration disables automatic capture.

The screenshot is only part of the page

That is the normal viewport result. Full-page capture depends on driver support; Selenium documents an optional full_page parameter but unsupported drivers raise an error. Use a supported driver or capture the relevant viewport states separately.

Files overwrite each other

Use worker- or example-specific filenames. This is a filesystem concern, not a Selenium setting, and is especially important when examples run concurrently.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If you need a rendered image without maintaining Selenium and RSpec browser lifecycle code, ScreenshotNeo provides a website screenshot API and MCP server. A single request returns PNG, JPEG, WebP, or PDF. It accepts cookie/consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers.

Read the full parameter reference in the ScreenshotNeo documentation. The same endpoint supports full-page lazy-image loading, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, PDF page controls, custom CSS and JavaScript, pre-capture clicks, selector hiding, waits, request/resource blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, and an OpenAPI specification.

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 has an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots, and every feature is available on every plan. Create a free ScreenshotNeo account to try it.

Practical decision checklist

  • Use direct Selenium when the test already owns a WebDriver and needs a screenshot at an exact step.
  • Use Capybara’s helper when the spec is written around a Capybara session.
  • Use capybara-screenshot when every supported browser failure should leave image and HTML evidence.
  • Keep capture before teardown, create the destination directory, and make names unique.
  • Preserve the chosen directory as a CI artifact and protect HTML that may contain test data.
  • Expect viewport output unless your specific Selenium driver supports full-page capture.

Frequently Asked Questions

Does Selenium save JPEG or WebP screenshots in Ruby?

The Selenium Ruby API method described here saves a PNG screenshot; use the .png extension.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can I take a screenshot with Capybara’s rack-test driver?

No. rack-test is not a real browser and does not execute JavaScript; select a Selenium-backed driver.

Why does capybara-screenshot save HTML as well as an image?

Its documented failure integration records the failed page HTML alongside the screenshot for supported browser drivers; review that HTML for sensitive test data.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.