ScreenshotNeo

BlogHow-to

How to Capture Multi-Step Page Snapshots with Rails and PhantomJS

Capture every state in a Rails workflow with Capybara, Poltergeist and PhantomJS, diagnose flaky JavaScript, and compare a hosted API option.

By the ScreenshotNeo team30 September 20263 min read

How to Capture Multi-Step Page Snapshots with Rails and PhantomJS

Direct answer: keep one Capybara session for the entire workflow, perform each user action in order, wait for asynchronous JavaScript to settle, and call page.save_screenshot immediately after every milestone. Configure Rails to use Poltergeist, set a deterministic viewport, and enable JavaScript errors and debug logging while diagnosing failures.

Poltergeist is the Capybara driver that connects Rails tests to PhantomJS. It provides screenshots, full-page rendering, selector rendering and JavaScript execution. The complete flow below captures checkout states while preserving cookies, navigation and DOM state between steps.

What you need

  • Ruby and a Rails application with Capybara-based system or feature tests.
  • The poltergeist gem and PhantomJS installed on the test machine or CI runner.
  • A writable directory such as tmp/snapshots.

Poltergeist’s repository is archived and PhantomJS development is suspended, so this stack is useful for maintaining an existing suite but should be evaluated carefully for new long-lived projects. The [Poltergeist repository](https://github.com/teampoltergeist/poltergeist) is read-only, and the [PhantomJS project](https://phantomjs.org/) states that development is suspended.

1. Install Poltergeist and configure Rails

Add the driver to the test group:

One Capybara session preserves state while each meaningful milestone is rendered.
One Capybara session preserves state while each meaningful milestone is rendered.
# Gemfile
group :test do
  gem "capybara"
  gem "poltergeist"
end

Install the bundle:

bundle install

Require the driver in your test setup. The exact file differs between Rails versions; use the file that is loaded by your test suite.

# test/application_system_test_case.rb
require "test_helper"
require "capybara/rails"
require "capybara/poltergeist"

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  driven_by :poltergeist,
    screen_size: [1280, 900],
    options: {
      js_errors: true,
      timeout: 30,
      phantomjs_options: ["--ignore-ssl-errors=true"]
    }
end

If your Rails version does not use ActionDispatch::SystemTestCase, register the driver directly:

# test/test_helper.rb or spec/rails_helper.rb
require "capybara/rails"
require "capybara/poltergeist"

Capybara.register_driver :poltergeist_diagnostics do |app|
  options = {
    js_errors: true,
    timeout: 30,
    phantomjs_options: ["--ignore-ssl-errors=true"]
  }
  Capybara::Poltergeist::Driver.new(app, options)
end

Capybara.javascript_driver = :poltergeist_diagnostics
Capybara.default_max_wait_time = 5
Capybara.save_path = Rails.root.join("tmp", "capybara")

Use --ignore-ssl-errors=true only when your test environment intentionally uses an untrusted certificate. Do not hide certificate problems in production monitoring.

2. Capture each state in one session

A screenshot is a rendering of the page’s current state. Starting a new session for every image loses cookies, form data and navigation history. Keep the whole scenario inside one test.

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

class CheckoutSnapshotsTest < ApplicationSystemTestCase
  def setup
    FileUtils.mkdir_p(Rails.root.join("tmp", "snapshots"))
  end

  def snapshot(name, full: true, selector: nil)
    path = Rails.root.join("tmp", "snapshots", "#{name}.png")
    options = { full: full }
    options[:selector] = selector if selector
    page.save_screenshot(path.to_s, **options)
  end

  test "captures every checkout milestone" do
    visit "/checkout"
    snapshot "01-checkout"

    click_link "Next"
    assert_selector "#shipping-form"
    snapshot "02-shipping"

    fill_in "Address", with: "10 Example Street"
    fill_in "City", with: "London"
    fill_in "Postcode", with: "SW1A 1AA"
    click_button "Continue"
    assert_selector "#payment-form"
    snapshot "03-payment"

    click_button "Place order"
    assert_selector ".confirmation"
    snapshot "04-confirmation"
  end
end

Give files stable, ordered names. A numbered prefix makes a sequence easy to review and prevents later steps from overwriting earlier ones.

3. Wait for JavaScript before rendering

Capybara synchronizes many asynchronous operations automatically: commands such as click_button wait for the driver to finish pending work before returning. Follow each meaningful action with an assertion for the state you need. Assertions are better than arbitrary sleeps because they express what must be true.

click_button "Continue"
assert_selector "#payment-form", wait: 10
refute_selector ".loading-spinner", wait: 10
page.save_screenshot("tmp/snapshots/03-payment.png", full: true)

Use a short explicit wait only for a condition Capybara cannot observe directly:

Timeout.timeout(10) do
  sleep 0.1 until page.evaluate_script("window.checkoutReady === true")
end
page.save_screenshot("tmp/snapshots/03-payment-ready.png", full: true)

Do not add a large sleep after every step. It slows the suite and still fails when a network request takes longer than the chosen delay.

4. Full-page, element and viewport screenshots

Full page

page.save_screenshot("tmp/snapshots/full.png", full: true)

Use full: true when the image should include content below the viewport. Long pages with lazy-loaded images may need a scroll pass before capture so image loading is triggered.

page.execute_script(<<~JS)
  window.scrollTo(0, document.body.scrollHeight);
JS
assert_no_selector ".lazy-loading", wait: 10
page.save_screenshot("tmp/snapshots/full-loaded.png", full: true)

A bounded element

page.save_screenshot(
  "tmp/snapshots/order-summary.png",
  selector: "#order-summary"
)

The selector must match an element that exists and is visible. Capture the element after asserting it is present.

Viewport and clipping

Set the viewport in the driver configuration so CI and local runs use the same geometry. For a focused region, use a selector rather than manually guessing clip coordinates. PhantomJS can render PNG, JPEG, GIF and PDF; the output extension and driver options determine the format supported by your setup.

5. A reusable snapshot helper

Centralizing naming and metadata keeps large workflows readable.

module SnapshotSteps
  def capture_step(number, label, full: true, selector: nil)
    safe_label = label.downcase.gsub(/[^a-z0-9]+/, "-").gsub(/\A-|\z/, "")
    filename = format("%02d-%s.png", number, safe_label)
    path = Rails.root.join("tmp", "snapshots", filename)
    options = { full: full }
    options[:selector] = selector if selector
    page.save_screenshot(path.to_s, **options)
    path
  end
end

class CheckoutSnapshotsTest < ApplicationSystemTestCase
  include SnapshotSteps

  test "captures the flow" do
    visit "/checkout"
    capture_step 1, "checkout"
    click_link "Next"
    assert_selector "#shipping-form"
    capture_step 2, "shipping"
  end
end

6. Direct PhantomJS rendering

Use the PhantomJS API directly when you are not running through Rails or Capybara. The basic sequence is page.open followed by page.render.

// snapshot.js
var page = require("webpage").create();
page.viewportSize = { width: 1280, height: 900 };
page.open("https://example.com/checkout", function (status) {
  if (status !== "success") {
    console.log("open failed: " + status);
    phantom.exit(1);
  }
  page.render("tmp/snapshots/01-checkout.png");
  phantom.exit(0);
});
phantomjs snapshot.js

For a multi-step flow, perform navigation and form actions inside page callbacks or injected JavaScript, then call page.render after each state. Capybara and Poltergeist are usually easier for Rails selectors, sessions and assertions.

7. Preserve useful failure evidence

When a step fails, save both the rendered page and its HTML before the test exits. Capybara documents save_screenshot and save_and_open_page; Poltergeist also supports screenshots and debug logging.

def save_failure_artifacts(name)
  FileUtils.mkdir_p(Rails.root.join("tmp", "failures"))
  page.save_screenshot(Rails.root.join("tmp", "failures", "#{name}.png").to_s, full: true)
  File.write(
    Rails.root.join("tmp", "failures", "#{name}.html"),
    page.html
  )
end

begin
  click_button "Continue"
  assert_selector "#payment-form", wait: 10
rescue Minitest::Assertion, Capybara::ElementNotFound => error
  save_failure_artifacts("payment-step")
  raise error
end

Enable Poltergeist's JavaScript errors while diagnosing failures. A browser-console exception can prevent a click handler from changing the DOM even when the selector is correct.

8. Common failures and fixes

Symptom Likely cause Fix
Screenshot shows the previous step Rendering happened before an asynchronous update completed. Assert the new heading, form or URL; inspect a loading marker; then capture.
Capybara::ElementNotFound The selector is wrong, the element is inside an iframe, or it has not rendered. Save HTML, verify the selector in page.html, wait for the container, and switch to the correct frame when needed.
Intermittent click failures An overlay, animation or consent dialog covers the target. Assert the overlay is gone, wait for the target to be visible, and capture a failure screenshot.
JavaScript errors reported Application code or a third-party script is throwing in PhantomJS. Read the console error, fix or stub the failing dependency, or run the flow in a maintained browser engine if the code requires newer APIs.
Blank or partially loaded image Lazy loading was never triggered, a request timed out, or the page failed to load. Scroll to trigger lazy content, increase the diagnostic timeout, check network dependencies, and save HTML for comparison.
Different dimensions in CI Viewport, device scale or fonts differ between machines. Set a fixed screen size, install the same fonts, and keep asset loading deterministic.
SSL or certificate error CI uses a self-signed certificate. Install the test certificate or, only for that isolated test environment, pass PhantomJS's ignore-SSL-errors option.
PhantomJS cannot start Binary is missing, incompatible, or not on PATH. Install the pinned binary used by the project, verify phantomjs --version, and check executable permissions.
PDF or image cannot be opened Output extension, permissions or directory is invalid. Create the directory first, use an absolute writable path, and choose PNG, JPEG, GIF or PDF explicitly.

9. Reliability and CI practices

  • Use one session per scenario and reset it between scenarios so state does not leak.
  • Prefer semantic assertions over fixed sleeps.
  • Freeze or stub clocks, random values and external APIs when those values affect the rendered state.
  • Wait for fonts and critical images if visual comparison depends on them.
  • Store screenshots as CI artifacts on failure; avoid committing every generated image unless the repository intentionally keeps visual baselines.
  • Run a small number of diagnostic retries only after collecting evidence. Retries can hide a real race.
  • Pin PhantomJS and its dependencies if you must keep this stack, because its engine and JavaScript support are no longer advancing.

10. Performance and cost considerations

Each full-page render lays out and paints the current document, so capturing many milestones increases test time. Capture only states that explain a workflow or support a visual assertion. Element screenshots are often smaller and faster than full-page renders. Reuse the session, avoid unnecessary reloads, and keep external resources deterministic.

A hosted capture can clear common overlays before rendering the page.
A hosted capture can clear common overlays before rendering the page.

PhantomJS is self-hosted: your costs are the CI or server resources that run the browser, plus maintenance time for an archived engine. If compatibility with current JavaScript is more important than preserving this setup, compare a maintained headless-browser driver using the axes in the table below.

11. Choosing a replacement or hosted capture service

Evaluation area Questions to answer
Browser maintenance Does the engine support the JavaScript, CSS, fonts and security policies used by the application?
Rails integration Can the driver preserve sessions, expose Capybara selectors and provide useful failures?
Waiting Can you wait for selectors, network idle and application-specific readiness?
Rendering Are full-page, element, PDF and required image formats available?
CI operation Are fonts, viewport size, sandboxing, downloads and logs predictable?
Migration How much of the existing Capybara test code can remain unchanged?

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP or PDF. Cookie and consent banners, newsletter popups and chat widgets are removed before capture; bot checks, blank pages, timeouts, failed loads and cache hits are not billed. Responses identify the result with X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info and capture_pdf for Claude, Cursor and other MCP clients.

For a one-off page or a step URL that is already reachable, use the API documented at ScreenshotNeo's API 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,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', image));

ScreenshotNeo also supports custom JavaScript and CSS, clicks, selector waits, delays, network-idle waits, full-page capture with lazy images loaded, element capture, headers, cookies, user agents, authorization, timezone, geolocation, blocking rules, caching with a chosen TTL, signed links, asynchronous jobs, webhooks, bulk capture of up to 100 URLs per call, PDF controls and a usage API. A Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

FAQ

Does page.save_screenshot capture the browser's current state?

Yes. It renders the DOM and visual state at the moment the call runs, so call it after the interaction and the assertion that identifies the new state.

Should every step use a new Capybara session?

No. Reuse one session for a single workflow so cookies, navigation and form state carry forward. Reset between independent scenarios.

Can PhantomJS capture a PDF?

Yes. PhantomJS supports PNG, JPEG, GIF and PDF rendering, subject to the driver and output options used by the application.

Why do screenshots pass locally but fail in CI?

Common differences are viewport size, fonts, missing binaries, SSL certificates, external requests and timing. Save HTML and a failure screenshot, then make those inputs deterministic.

Is PhantomJS appropriate for a new Rails project?

Its official project is suspended and Poltergeist is archived. Treat it as a compatibility choice for existing suites and evaluate a maintained browser driver before standardizing on it for new work.