Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
authentication

How to Capture Screenshots of Authenticated Pages in Ruby

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

Use a real browser session, complete the website’s normal authorized sign-in flow, verify that the protected page—not a login redirect—has loaded, and then save the screenshot. In Ruby, you can do this through Capybara with a Selenium driver or directly with Selenium WebDriver. The browser session must remain the same from login through capture so its cookies, local storage, redirects and other authentication state are available to the protected page.

What you need before capturing

  • Ruby and a browser such as Chrome installed on the machine that runs the script.
  • A browser automation driver. Capybara’s default rack_test driver does not run a remote browser and is not suitable for JavaScript-heavy or remote authenticated pages; configure a browser-capable driver such as Selenium.
  • An authorized test account whenever possible. Do not automate access to an account or page you are not permitted to use.
  • A reliable success condition, such as the final post-login URL or an element that appears only for signed-in users.
  • A protected-page condition, such as a heading, navigation item or URL pattern that proves the account page loaded.

Selectors, multi-factor authentication, single sign-on, CAPTCHA challenges and driver installation vary by site. The examples below deliberately leave those site-specific parts visible instead of pretending that one selector works everywhere.

Capture an authenticated page with Capybara

Capybara is a good fit when your Rails system tests, RSpec suite or existing Ruby test harness already uses its session API. It delegates navigation, waiting and screenshots to the configured driver.

require "capybara"
require "capybara/dsl"

session = Capybara::Session.new(:selenium)

begin
  session.visit("https://example.com/login")

  # Replace these selectors and values with the site's authorized test flow.
  session.fill_in("Email", with: ENV.fetch("TEST_LOGIN_EMAIL"))
  session.fill_in("Password", with: ENV.fetch("TEST_LOGIN_PASSWORD"))
  session.click_button("Sign in")

  # Wait for a condition that only holds after authentication.
  session.assert_current_path("/dashboard")
  session.assert_selector("[data-testid='signed-in-user']")

  session.visit("https://example.com/account")

  # Prove that this is the protected page, not a login or error page.
  session.assert_current_path("/account")
  session.assert_selector("h1", text: "Account")

  FileUtils.mkdir_p("tmp")
  session.save_screenshot("tmp/account.png")
ensure
  session.driver.quit
end

Add require "fileutils" if your Ruby version does not already load it through your test framework. Capybara’s save_screenshot(path) method forwards the request to the selected driver. The exact driver registration, browser binary and driver-management approach depend on your project and installed Selenium version.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
HP OmniBook 3 17.3 inch Laptop PC, FHD Display, AMD Ryzen 3 30, 8 GB RAM, 512 GB SSD, AMD Radeon 610M Graphics, Windows 11 Home, Mica Silver, 17-dp0199nr
  • FULL HD IPS DISPLAY - Enjoy vibrant, crystal-clear images with 178-degree wide-viewing angles
  • AMD RYZEN 3 30 PROCESSOR - Everyday performance you can count on; Multitask, stream, game casually, and edit photos smoothly with responsive power and vibrant HDR visuals
  • ENJOY UP TO 14 HOURS AND 15 MINUTES OF BATTERY LIFE - HP Fast Charge restores battery from 0 to 50% in approximately 45 minutes
  • AMD RADEON 610M GRAPHICS - Experience smooth entertainment; Built for streaming and multitasking, enjoy realistic visuals and efficient performance for work and play
  • STORAGE AND MEMORY - 512 GB PCIe NVMe M.2 SSD offers fast speed and efficient storage; and 8 GB LPDDR5 RAM memory boosts performance with higher bandwidth

Use explicit waits instead of a fixed sleep

Authentication commonly involves redirects and asynchronous requests. A fixed sleep 5 can be too short on a busy run and unnecessarily slow on a fast one. Capybara’s selector assertions wait up to its configured maximum for the condition to become true:

session.assert_selector("[data-testid='signed-in-user']", wait: 15)
session.assert_current_path("/account", wait: 15)

Choose a marker that cannot appear on the unauthenticated page. If the application redirects to a tenant-specific URL, assert the complete expected path or a narrower, safe pattern rather than merely checking that navigation finished.

Capture directly with Selenium WebDriver

Direct Selenium is preferable when you need lower-level browser control or do not use Capybara. The Ruby API saves a PNG screenshot of the viewport by default.

require "selenium-webdriver"
require "fileutils"

options = Selenium::WebDriver::Chrome::Options.new
# options.add_argument("--headless=new") # Enable in CI if appropriate.

driver = Selenium::WebDriver.for(:chrome, options: options)
wait = Selenium::WebDriver::Wait.new(timeout: 15)

begin
  driver.navigate.to("https://example.com/login")

  email = wait.until { driver.find_element(name: "email") }
  password = driver.find_element(name: "password")
  email.send_keys(ENV.fetch("TEST_LOGIN_EMAIL"))
  password.send_keys(ENV.fetch("TEST_LOGIN_PASSWORD"))
  driver.find_element(css: "button[type='submit']").click

  wait.until { driver.current_url.end_with?("/dashboard") }
  wait.until { driver.find_element(css: "[data-testid='signed-in-user']") }

  driver.navigate.to("https://example.com/account")
  wait.until { driver.current_url.end_with?("/account") }
  wait.until { driver.find_element(css: "h1").text == "Account" }

  FileUtils.mkdir_p("tmp")
  driver.save_screenshot("tmp/account.png")
ensure
  driver.quit
end

The ensure block matters: it closes the browser even when a selector, navigation or assertion raises an exception. Without cleanup, repeated jobs can leave orphaned browser processes and consume memory.

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.

Capture one element instead of the viewport

When the target is a card, invoice or other component, locate that element and call its screenshot method:

Rank #2
HP 14" HD Chromebook Laptop for Students, Intel Quad-Core N4120(> N4020), 4GB RAM, 64GB eMMC, WiFi, Webcam, HDMI, USB-A&C, 14 Hours Battery Life, Zoom, Chrome OS, CUE Accessories
  • Intel Celeron N4120: 4 Cores & Threads, 1.1GHz Base Clock, Up to 2.6GHz Boost Clock, 4MB Cache, Intel UHD Graphics 600. The perfect combination of performance, power consumption, and value helps your device handle multitasking smoothly and reliably with four processing cores to divide up the work.
  • 14" HD Display: 14.0-inch diagonal, HD (1366 x 768), micro-edge, anti-glare. See your digital world in a whole new way. Enjoy movies and photos with the great image quality and high-definition detail of 1 million pixels.
  • Memory & Storage: 4 GB LPDDR4x & 64 GB eMMC Storage. Adequate high-bandwidth RAM to smoothly run multiple applications and browser tabs all at once. An embedded multimedia card provides reliable flash-based storage.
  • Ports:2 x USB 3.0 Type-A,1 x USB 3.0 Type-C,1 x HDMI,1 x Headphone Jack
  • Chrome OS: Chromebook is a computer for the way the modern world works, with thousands of apps. Enjoy the seamless simplicity that comes with Google Chrome and Android apps, all integrated into one laptop. It’s fast, simple, and secure.
element = wait.until { driver.find_element(css: "[data-testid='invoice']") }
element.save_screenshot("tmp/invoice.png")

Selenium’s Ruby examples document element screenshot capture. Use the output format accepted by your installed library version and inspect the resulting file in your pipeline.

Viewport, full-page and responsive captures

Viewport screenshots

A normal Selenium screenshot captures what is visible in the current viewport. Set the window size before navigation when a deterministic layout is important:

driver.manage.window.resize_to(1440, 1000)

Also set the size before waiting for responsive elements, because a mobile viewport may render different navigation and content.

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

Full-page screenshots

Full-page support is driver-dependent; do not assume that a full_page option works in every browser or Selenium combination. Check the documentation for the exact driver installed in your environment. If unsupported, capture a viewport or implement a driver-specific scrolling/stitching strategy and verify that lazy-loaded content has actually appeared.

Capture after lazy content appears

Waiting for the main heading may not mean charts, images or tables have finished rendering. Wait for a meaningful application marker, network-complete condition supplied by your test framework, or a specific element that is required in the screenshot. Avoid declaring success merely because the URL changed.

Rank #3
Sale
AKCHART 15.6'' AI Laptop with Office 365 12GB RAM 256GB SSD Win 11 Laptops
  • Stunning 15.6" FHD IPS Display: Experience crisp 1920x1080 resolution on this 15.6 inch laptop with an IPS panel that delivers wide viewing angles and vivid colors. The narrow-bezel design maximizes screen real estate for comfortable viewing on this Win 11 laptop, whether you're studying or working.
  • Celeron J4105 Processor & 256GB SSD: Powered by a reliable Celeron J4105 processor paired with 12GB DDR4 memory and a fast 256GB M.2 SSD. This laptop computer supports SSD expansion up to 2TB and TF card expansion up to 1TB, so your storage grows with your needs. Delivers smooth multitasking for daily productivity.
  • AI-Powered Win 11 Laptop: Built-in AI features enhance your productivity with smart assistance for writing, summarizing, and task management. Pre-installed with Win 11 and includes Office 365 subscription. This student laptop is backed by 1-year warranty and 24/7 customer support.
  • All-Day 7000mAh Battery & 180° Hinge: The high-capacity 7000mAh battery keeps this laptop powered through long classes or meetings. The 180-degree lay-flat hinge lets you share your screen effortlessly during presentations. This durable laptop computer adapts to your dynamic workflow.
  • Versatile Connectivity Hub: Equipped with USB 3.2, Type-C, Mini HDMI, and 3.5mm audio jack to connect all your peripherals. Stay online anywhere with high-speed 5G WiFi and Bluetooth 4.2. This college laptop keeps you connected at home, in the library, or on the go.

Reuse authentication state or sign in every run?

Approach Advantages Costs and risks
Sign in in each run Exercises the real login path and avoids storing a reusable browser-state file. Slower; can trigger MFA, rate limits or additional redirects; requires a stable test account.
Save and reuse browser state Shorter capture runs and fewer repeated login steps. The state can be as sensitive as a credential and may expire; your storage method must include every mechanism the application uses.

Browser authentication state can include cookies, local storage, IndexedDB and passkeys. Session storage may require a custom workaround. A saved state file can contain cookies and headers that impersonate the test account, so keep it outside version control, restrict filesystem and CI access, rotate it when practical, and delete it when no longer needed. Never print cookies, authorization headers or passwords in logs.

Protect credentials and screenshot data

  • Read test credentials from environment variables or a secret manager, not from source files.
  • Use a dedicated account with the minimum permissions and non-production data.
  • Mask passwords, cookies, authorization headers and tokens in exception messages and debug logs.
  • Store screenshots with appropriate access controls. An image can reveal names, addresses, financial details, support conversations or internal URLs even when the automation code is safe.
  • Use HTTPS URLs and verify that redirects stay within the expected identity provider and application.
  • Do not bypass bot checks, access controls or MFA. If an interactive challenge is required, use an approved test route or human-assisted setup.

Capybara or direct Selenium?

  • Choose Capybara when the project already uses Capybara assertions, Rails system tests or shared selectors. Its session API keeps navigation and assertions concise.
  • Choose Selenium directly when you need direct WebDriver operations, custom browser capabilities or a small standalone Ruby script.
  • Use the same browser session for login, protected navigation and capture. Creating a second session loses the cookies and other state that proved authentication.

Troubleshooting authenticated captures

The screenshot shows the login page

The sign-in step may have failed, the session may have been replaced, or the protected URL may have redirected. Capture the current URL and inspect a safe, non-secret page marker after login. Assert the expected URL and signed-in element before visiting the protected URL; then assert the protected marker before saving.

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

The script times out waiting for a selector

Check that the selector matches the rendered DOM, that the browser is on the expected origin, and that the account has permission for the page. Increase the wait only after confirming the condition is correct. A timeout can indicate a real authorization failure, not merely a slow browser.

JavaScript content is missing

A non-browser HTTP client or Capybara’s rack_test driver cannot render a remote JavaScript application like a real browser. Switch to Selenium (or another browser-capable driver), wait for the application’s content marker, and ensure required scripts and resources are not blocked.

The browser never closes in CI

Put driver.quit or session.driver.quit in ensure. Also check that failures occurring before driver creation are not being mistaken for cleanup failures, and use a per-job temporary directory for artifacts.

Rank #4
HP Essential Laptop 2026, Intel CPU, 128GB Storage, Office 365, Windows 11
  • Efficient Performance for Everyday Computing: Powered by Intel N150 processor with up to 3.6 GHz Intel Turbo Boost Technology, 6 MB L3 cache, 4 cores, and 4 threads, this HP laptop delivers responsive performance for web browsing, streaming, document editing, and multitasking. Paired with 4GB LPDDR5 RAM and 128GB UFS storage, it handles daily tasks smoothly. Includes 1-year Microsoft 365 Personal subscription for Word, Excel, PowerPoint, and cloud storage to maximize your productivity.
  • 14-Inch HD Micro-Edge Display:Enjoy clear visuals on the 14-inch HD (1366 x 768) anti-glare screen with 250-nit brightness and 62.5% sRGB coverage. The micro-edge bezel delivers a 79% screen-to-body ratio in a compact design. An HP True Vision 720p HD camera with noise reduction and dual-array microphones supports clear video calls, remote work, and online learning.
  • Modern Connectivity and Wireless Technology: Stay connected with Wi-Fi 6 (2x2) for faster wireless speeds and Bluetooth 5.4 for seamless pairing with accessories. Versatile port selection includes 1 USB Type-C 10Gbps with DisplayPort 1.2 for external displays, 2 USB Type-A 5Gbps ports for peripherals, 1 HDMI 1.4b port, 1 headphone/microphone combo jack, and 1 multi-format SD media card reader. Connect monitors, transfer files quickly, and expand your workspace with ease.
  • All-Day Battery Life and Portable Design: Enjoy up to 11 hours of video playback, 7.5 hours of mixed usage, or 7.5 hours of wireless streaming on a single charge, perfect for students and professionals on the go. Weighing just 3.24 lb and measuring 12.76" x 8.86" x 0.71", this lightweight laptop fits easily in backpacks and bags. The stylish willow green top cover with matte finish and natural silver keyboard deck with vertical brushing pattern offer a modern, professional look.
  • AI-Enhanced Productivity: Access Microsoft Copilot instantly with the dedicated Copilot key for faster assistance. AI Noise Reduction filters background sounds and improves voice clarity during calls. Dual speakers provide clear audio, while the full-size natural silver keyboard and HP Imagepad support comfortable typing and navigation.

The image is blank or incomplete

Wait for the actual content, not only the URL. Confirm the viewport is large enough, lazy-loaded elements have been triggered, and the page is not displaying an access-denied or consent overlay. Save diagnostic HTML or a non-sensitive DOM marker separately rather than logging authentication state.

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

ScreenshotNeo provides a website screenshot API and MCP server. It handles a URL with one request, while its capture options can handle authenticated workflows using custom headers, cookies, user agents or Authorization values. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets; each step can be turned off. 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.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Ruby can call the same endpoint with the standard library:

require "net/http"
require "uri"

uri = URI("https://api.screenshotneo.com/v1/shot")
uri.query = URI.encode_www_form(access_key: ENV.fetch("SCREENSHOTNEO_API_KEY"), url: "https://stripe.com")
response = Net::HTTP.get_response(uri)
raise "Screenshot failed: #{response.code}" unless response.is_a?(Net::HTTPSuccess)
File.binwrite("shot.webp", response.body)

Python and Node.js clients are also straightforward:

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}`);

For parameter names, authentication options, PDFs, async jobs and other settings, see the ScreenshotNeo documentation. Its MCP server includes 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 without a card; paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account.

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

Operational and cost considerations

  • Browser automation consumes CPU and memory; reuse one session for related captures when isolation requirements allow, and always close it.
  • Parallel jobs can shorten a batch but increase browser and site load. Respect the target application’s limits.
  • Cache or reuse authenticated state only when its secret-handling and expiry behavior are understood.
  • Keep screenshot artifacts separate from logs and set retention limits because images may contain account data.
  • For ScreenshotNeo, inspect X-Page-Verdict and X-Billed so your job can distinguish a clean capture from a failed or non-billable result.

FAQ

Can I use Capybara’s default driver for a remote authenticated site?

Not for a normal browser-rendered remote page. Configure a browser-capable driver such as Selenium so JavaScript, navigation and session cookies are handled by an actual browser.

Best Value
Sale
HP 14 inch Laptop Computer, 2027 Edition, Intel N150 CPU, 4GB RAM, 128GB SSD, 1TB Cloud Storage, Windows 11 with Microsoft 365
  • Designed for mobility with a slim 0.71-inch profile and lightweight 3.24 lb chassis, making it easy to carry between home, office

Does saving a screenshot prove that authentication succeeded?

No. A browser can save a screenshot of a login, error or redirect page. Assert an authenticated marker and the protected-page marker before calling the screenshot method.

Are saved cookies safe to commit with test fixtures?

Treat reusable browser state as sensitive authentication material. Keep it out of source control and limit access just as you would for a test credential.

Can Selenium always make a full-page image?

No. Full-page behavior depends on the browser driver and installed version. Viewport capture is the reliable baseline; verify full-page support in your exact stack.

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

Frequently Asked Questions

Can I use Capybara’s default driver for a remote authenticated site?

Not for a normal browser-rendered remote page. Configure a browser-capable driver such as Selenium.

Does saving a screenshot prove that authentication succeeded?

No. Assert an authenticated marker and protected-page marker before capture.

Are saved cookies safe to commit with test fixtures?

No. Treat reusable browser state as sensitive authentication material and keep it out of source control.

Can Selenium always make a full-page image?

No. Full-page behavior depends on the exact browser driver and version.

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.