What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
To inject a local JavaScript file into the page that Capybara is currently displaying, use a JavaScript-capable driver and pass the file contents to page.execute_script:
script_path = Rails.root.join('spec', 'support', 'scripts', 'helper.js')
page.execute_script(File.read(script_path))
File.read runs in the Ruby test process. Capybara then sends the resulting source string to Chrome for execution. This is the documented string-taking API; it is not a method that accepts a filesystem path directly. The default :rack_test driver cannot execute JavaScript, so the session must use Selenium Chrome or another JavaScript-capable driver.
What you need before injecting a file
There are two separate locations involved:
- The test runner’s filesystem: Ruby can read
spec/support/scripts/helper.jsfrom this machine. - The browser document: Chrome can execute JavaScript only after a document has been loaded in the current Capybara session.
A local path is meaningful to Ruby, not to the browser. If you want Chrome to fetch a file itself, the file must be exposed at a URL that the browser can reach.
Use a JavaScript-capable Capybara driver
Capybara’s default :rack_test driver does not run JavaScript. Capybara lists Selenium-backed Chrome drivers, including :selenium_chrome_headless, in its project documentation (Capybara README). Selenium’s WebDriver documentation also demonstrates configuring Chrome in headless mode and executing browser JavaScript (Selenium WebDriver documentation).
#1 Best Overall
- USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
- Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
- Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
- Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
- Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty
A typical setup in a Rails test suite looks like this:
# Gemfile
group :test do
gem 'capybara'
gem 'selenium-webdriver'
end
# spec/rails_helper.rb or test_helper.rb
require 'capybara/rspec'
Capybara.configure do |config|
config.default_driver = :selenium_chrome_headless
end
The exact browser, ChromeDriver and Selenium versions are project-dependent. Install a compatible Chrome/Chromium browser and driver, then confirm that an ordinary JavaScript feature spec passes before troubleshooting injection.
Method 1: read the local file and execute its source
This is the simplest approach when the script is a test helper, fixture or generated file that exists on the machine running Ruby.
- Navigate to the page that should receive the script.
- Build an absolute path in Ruby.
- Read the file as a string.
- Pass that string to the session-level
execute_scriptmethod.
visit '/dashboard'
script_path = Rails.root.join('spec', 'support', 'scripts', 'helper.js')
raise "Missing script: #{script_path}" unless File.file?(script_path)
page.execute_script(File.read(script_path))
Capybara documents page.execute_script(source) for scripts where you do not need a return value (Capybara session API). The source is evaluated in the current document. A relative file path, a Pathname object or a URL will not be interpreted as JavaScript source unless you read or construct the source yourself.
Free tools Windows power users keep installed
One-click scans. No signup required.
A complete RSpec example
require 'rails_helper'
RSpec.describe 'dashboard helper', type: :feature, js: true do
it 'injects the helper into the current page' do
visit '/dashboard'
script_path = Rails.root.join('spec', 'support', 'scripts', 'helper.js')
page.execute_script(File.read(script_path))
expect(page).to have_css('[data-helper-ready="true"]')
end
end
The js: true metadata is useful in RSpec Rails projects that switch JavaScript examples to a Selenium driver. If your suite uses a different driver-selection convention, set the driver explicitly for the example or configure it globally.
Make the injected script observable
Tests are easier to diagnose when the helper leaves a deliberate signal. For example, the file could set an attribute:
// spec/support/scripts/helper.js
document.documentElement.dataset.helperReady = 'true';
Then assert the signal from Ruby:
expect(page).to have_css('html[data-helper-ready="true"]')
Choose a signal that represents the behavior your test needs. Avoid asserting an implementation-only global unless the global itself is the contract.
Method 2: append a script element with a browser-reachable URL
Use a dynamically created <script src="..."> element when the browser should load the file as a resource. This is useful for an asset served by the application, a fixture route or a test server.
Recommended Free Tools
Rank #2
- High-speed USB 3.0 performance of up to 150MB/s(1) [(1) Write to drive up to 15x faster than standard USB 2.0 drives (4MB/s); varies by drive capacity. Up to 150MB/s read speed. USB 3.0 port required. Based on internal testing; performance may be lower depending on host device, usage conditions, and other factors; 1MB=1,000,000 bytes]
- Transfer a full-length movie in less than 30 seconds(2) [(2) Based on 1.2GB MPEG-4 video transfer with USB 3.0 host device. Results may vary based on host device, file attributes and other factors]
- Transfer to drive up to 15 times faster than standard USB 2.0 drives(1)
- Sleek, durable metal casing
- Easy-to-use password protection for your private files(3) [(3)Password protection uses 128-bit AES encryption and is supported by Windows 7, Windows 8, Windows 10, and Mac OS X v10.9 plus; Software download required for Mac, visit the SanDisk SecureAccess support page]
visit '/dashboard'
page.execute_script(<<~JS)
const script = document.createElement('script');
script.src = '/assets/helper.js';
document.head.appendChild(script);
JS
This example assumes that /assets/helper.js resolves from the page's origin and that the application serves it. A file that exists only under the test runner's spec/ directory cannot be used as the browser URL. For a cross-origin URL, content-security policy, CORS behavior and other browser loading rules can affect the result.
Wait for the external file to finish loading
Appending a script starts a network request; execute_script itself does not make your test wait for that resource's application work. Add a load marker in the file and wait for it through Capybara's normal synchronization:
// served /assets/helper.js
document.documentElement.dataset.helperReady = 'true';
page.execute_script(<<~JS)
const script = document.createElement('script');
script.src = '/assets/helper.js';
script.onload = () => { document.documentElement.dataset.helperLoaded = 'true'; };
script.onerror = () => { document.documentElement.dataset.helperLoadError = 'true'; };
document.head.appendChild(script);
JS
expect(page).to have_css('html[data-helperLoaded="true"]', wait: 10)
Use the attribute name consistently; HTML attributes are case-insensitive, but a consistent lowercase convention avoids confusing selectors. If the resource performs asynchronous work after its load event, expose a separate application-ready marker and wait for that marker instead.
Choosing between Capybara's script APIs
| API or technique | Use it when | Important limitation |
|---|---|---|
page.execute_script(source) |
You need to run JavaScript in the current page and do not need a return value. | It runs when called against the current document; it is not a pre-navigation hook. |
page.evaluate_script(expression) |
You need the value produced by a JavaScript expression. | Returned-value behavior can vary by driver. |
Append <script src> |
The browser should load a URL-backed resource. | The URL must be reachable from the browser and subject to page loading policy. |
Element-level execute_script |
The code intentionally needs one element as its context. | The element is bound as this; it is not equivalent to page-level execution. |
Capybara's session implementation describes the string-based methods and their driver-dependent argument support (session.rb). Its element implementation documents the element-scoped context (element.rb).
Read a value with evaluate_script
page.execute_script("window.__helperVersion = '1.4.0'")
version = page.evaluate_script('window.__helperVersion')
expect(version).to eq('1.4.0')
Use this only when the returned value is part of what you need to verify. Drivers differ in which JavaScript values they can marshal back to Ruby, so simple strings, numbers, booleans and plain data are safer than browser-native objects.
Understand element context
button = find('button.save')
button.execute_script("this.dataset.scriptRan = 'true'")
Here, this refers to the matched button. A script that expects document, page-level globals or the whole document should be run with page.execute_script instead.
Passing values into a script
Some drivers support arguments to script execution, but Capybara leaves the supported argument types to the selected driver. Keep the values simple and verify the behavior with your exact Selenium/browser combination. If portability matters, serialize a small JSON value into the source rather than relying on complex browser-object marshalling.
Timing: inject into the current document, not an imagined future page
execute_script acts on the document that exists when the call is made. Navigate first, then inject:
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Rank #3
- What You Get - 2 pack 64GB genuine USB 2.0 flash drives, 12-month warranty and lifetime friendly customer service
- Great for All Ages and Purposes – the thumb drives are suitable for storing digital data for school, business or daily usage. Apply to data storage of music, photos, movies and other files
- Easy to Use - Plug and play USB memory stick, no need to install any software. Support Windows 7 / 8 / 10 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, compatible with USB 2.0 and 1.1 ports
- Convenient Design - 360°metal swivel cap with matt surface and ring designed zip drive can protect USB connector, avoid to leave your fingerprint and easily attach to your key chain to avoid from losing and for easy carrying
- Brand Yourself - Brand the flash drive with your company's name and provide company's overview, policies, etc. to the newly joined employees or your customers
visit '/checkout'
expect(page).to have_css('#payment-form')
page.execute_script(File.read(Rails.root.join('spec', 'support', 'scripts', 'helper.js')))
If the script reads application globals, wait until the application has created them. If it changes a particular node, wait until that node exists. Capybara's matchers synchronize with page changes, so a semantic assertion is usually more robust than a fixed sleep:
expect(page).to have_css('[data-app-ready="true"]', wait: 15)
page.execute_script(File.read(script_path))
A fixed sleep can hide slow-page failures and still be too short on a busy CI runner. Use it only when the application has no observable readiness condition, and keep the duration deliberately bounded.
What if the script must run before page scripts?
Current-document injection is different from registering code that runs before the document's own scripts or before every navigation. The available Capybara API does not provide a portable, version-independent preload command for that requirement. Chrome DevTools Protocol solutions may exist for particular Selenium, ChromeDriver and browser versions, but the Ruby API and guarantees must be checked against those exact versions before adopting them.
If you control the application, a more stable solution is often to include the helper in the page's normal test asset bundle or expose a test-only initialization hook. That makes ordering explicit instead of depending on a post-navigation injection race.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Common errors and fixes
“JavaScript is not supported” or nothing happens
Cause: the session is using :rack_test or another non-JavaScript driver.
Fix: switch the example to :selenium_chrome_headless or another JavaScript-capable driver, install compatible browser and driver binaries, and confirm that a basic JavaScript assertion works.
The test passes a filename to execute_script
Cause: Capybara receives the path text instead of JavaScript source.
Fix: read the file in Ruby first:
page.execute_script(File.read(script_path))
“File not found” in CI
Cause: the path is relative to a different working directory, the fixture was not checked in, or the CI checkout omits it.
Rank #4
- GOOD VALUE PACKAGE - 1 Pack 32GB Memory Stick USB 2.0 Flash Drives with great cost performance and high quality.
- BIG CAPACITY - The available capacity: 29.10GB-29.8GB, You can save the data of movies, music, photos, designs, programs, manuals, handouts in a high speed.Good performance in digital data storing, transferring and sharing with families, friends, workmates, clients and machines.
- EASY TO USE & PLUG AND WORK - Support windows 7 / 8 / 10 / Vista / XP / 2000 / ME / NT Linux and Mac OS, Compatible with USB2.0 and below.
- TWISTTURN DESIGN & EASY CARRY - The metal clip rotates 360° round the ABS plastic body which with rubber oil skin feeling finish. The capless design can avoid lossing of cap, and providing efficient protection to the USB port.
- WARRANTY & SUPPORT - SIMMAX logo is laser printed on the USB connector surface, our products are of good quality and we promise that any problem about the product within one year since you buy.
Fix: anchor the path to Rails.root (or another known project root), assert File.file?, and ensure the file is included in the test job's checkout.
The script runs but cannot find an element
Cause: injection occurred before the application rendered the target node, or the selector refers to a different page state.
Fix: navigate first and wait for the relevant selector or application-ready marker before calling execute_script.
The URL-backed script never loads
Cause: the URL is not served, resolves against the wrong origin, is blocked by content-security policy, or fails a cross-origin browser rule.
Fix: open the exact URL from the test browser's origin, inspect the browser console/network log, verify that the response is JavaScript, and use the script's onerror marker while diagnosing.
You expected a result from execute_script
Cause: execute_script is intended for side effects and does not provide the evaluated value.
Fix: use evaluate_script for a value, then keep the returned data to driver-supported primitive types.
An element-scoped script behaves differently
Cause: element-level execution binds this to that element.
Best Value
- 【16GB Flash Drive】USB flash drives with 16GB capacity, meet your needs of daily use on work, school, home and travelling for photos, music, videos, files storage and transfer. IMEASON thumb drives can be used to store different files, easy to data backup.
- 【Metal Swivel Cap Design】USB thumb drive is metal swivel cover provides extra protection for the usb thumbdrive connector, no usb drive cap to lose; keychain design makes it easier to carry without worrying lose it.
- 【Wide Compatibility】USB drive supports Windows 7/8/10/11 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, also Supports USB 2.0 and 1.1 ports. USB Stick support TV, desktop, notebook computer, car, audio and other device. The USB Memory Stick is your great data storage and transfer companion with traveling and working.
- 【Easy to use】usb memory stick is plug and play without any software installation. Just simply plug the Flashdrive into the port of your USB-compatible devices such as computer, laptop to start data storage or transmission.
- 【What You Get】16 GB USB Flash Drive Thumb Drive, The default format of the usb storage flash drive is FAT32.
Fix: use the session-level method for document-wide code, or deliberately reference this when the element context is the behavior under test.
Keeping injected helpers reliable
- Use absolute, intention-revealing paths: keep helper files under a documented test-support directory and build paths from the project root.
- Make initialization idempotent: guard against duplicate listeners or duplicate DOM nodes if a test can inject more than once.
- Expose a narrow readiness signal: a data attribute or small global makes synchronization and failure diagnosis clearer.
- Keep production behavior isolated: load test-only helpers from test code or a test-only route rather than silently changing normal assets.
- Clean up state: each example should navigate or reset the session so globals, event listeners and DOM changes do not leak into another test.
- Log the resolved path on failure: the path shown in a CI failure should identify the exact file Ruby attempted to read.
The practical decision is straightforward: use File.read plus page.execute_script for a local fixture, append a script element for a browser-served URL, and treat pre-document execution as a separate, version-sensitive engineering problem.
Or skip the browser setup
If your goal is a clean image or PDF of a page rather than an interactive Capybara assertion, ScreenshotNeo provides a single HTTP request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; 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 page verdict and billing status in X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.
See the ScreenshotNeo API documentation for all options. A minimal cURL call is:
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchcurl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
The same request in Ruby, Python and Node.js:
require 'net/http'
require 'uri'
uri = URI('https://api.screenshotneo.com/v1/shot')
uri.query = URI.encode_www_form(access_key: 'YOUR_API_KEY', url: 'https://stripe.com')
response = Net::HTTP.get_response(uri)
File.binwrite('shot.webp', response.body)
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 supports full-page and selector captures, device presets and custom viewports, retina scale, dark mode, PDFs with paper and margin controls, HTML/CSS rendering, custom JavaScript and CSS, clicks, selector hiding, waits, request blocking, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, configurable caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API and an OpenAPI specification. Parameter names used by other screenshot APIs also work for easier migration.
The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account to try it without a card.
Frequently Asked Questions
Will the injected file run again after a redirect?
No. The code is evaluated in the document that exists at the moment of the call. A redirect or new navigation creates a new document, so inject again after that navigation if the new page needs the helper.
Can I use a file:// URL for a script in headless Chrome?
A browser-reachable URL is required, and file URLs introduce origin and security differences that do not match a normal application page. Serving the helper from the test application's origin is generally more predictable.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteHow can I tell whether a dynamically appended script failed?
Attach an onerror handler that writes a diagnostic data attribute, then assert that the success marker appears with a Capybara matcher and inspect the browser's network or console output when it does not.
Quick Recap
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.

