How to Find Text on React Pages With Capybara, Poltergeist, and PhantomJS
Use Capybara’s synchronized text matchers with a JavaScript driver, then debug rendered content with Poltergeist and PhantomJS APIs.

Direct answer: run the React page with a JavaScript-capable Capybara driver and assert the rendered result with expect(page).to have_text('Expected text'). Capybara’s matcher waits while asynchronous JavaScript updates the page, so it is generally more reliable than reading the DOM immediately or adding an arbitrary sleep. Poltergeist connects Capybara to the legacy PhantomJS browser; it remains useful when maintaining an old suite, but its repository is archived and PhantomJS’s documented ES6 limitations make it unsuitable for many new React applications.
This guide shows the complete workflow: driver setup, page-wide and scoped text assertions, waiting for React state changes, PhantomJS debugging, failure diagnosis, and a migration path. It also shows how to capture a rendered page without maintaining a browser stack.
1. Choose the right assertion
Use the assertion that matches what your test promises to a user:

| Need | Recommended code | Why |
|---|---|---|
| Text anywhere on the page | expect(page).to have_text('Expected text') |
Expresses a user-visible page result. |
| A boolean check | page.has_text?('Expected text') |
Useful in conditional diagnostic code; it returns a predicate. |
| Text in one component | expect(page).to have_css('#results', text: 'Expected text') |
Combines a stable scope with a text requirement. |
| Raw PhantomJS page text | page.plainText |
Debugging output for the main frame, without element tags. |
| Text from a particular DOM node | page.evaluate(function(selector) { ... }, '#results') |
Runs JavaScript in the page context. |
have_content is a familiar older alias for Capybara’s text matcher. Existing suites may use it, but have_text makes the intent explicit.
2. Set up a JavaScript-capable Capybara driver
Capybara’s default driver does not execute JavaScript. A React application that renders after hydration, fetches data, or responds to clicks therefore needs a JavaScript-capable driver. Select the driver in the test setup before running the example.
Legacy Poltergeist setup
Poltergeist is the historical Capybara driver for headless PhantomJS. Its setup pattern is:
# spec/support/capybara.rb
require 'capybara/rspec'
require 'capybara/poltergeist'
Capybara.javascript_driver = :poltergeist
Install the poltergeist gem and make sure the PhantomJS executable is available. The Poltergeist README documents options for the executable path, debugging, JavaScript error reporting, window size, and preloaded extension scripts. A typical explicit executable configuration looks like this:
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(
app,
phantomjs: '/path/to/phantomjs',
js_errors: true,
timeout: 10
)
end
Capybara.javascript_driver = :poltergeist
Use this approach when a legacy application is already pinned to PhantomJS. The Poltergeist repository was archived on November 27, 2020, so treat the stack as maintenance infrastructure rather than a default for a new React test suite. See the Poltergeist README for the historical configuration surface.
Keep driver selection local when suites have mixed needs
If only some examples require JavaScript, mark those examples and let Capybara select the configured JavaScript driver:
RSpec.describe 'results', type: :feature, js: true do
it 'shows the loaded result' do
visit '/results'
expect(page).to have_text('Expected text')
end
end
The exact metadata integration depends on your RSpec and Capybara versions. The invariant is that the example must run with a JavaScript driver before you assert text produced by React.
3. Write a page-wide React text assertion
Use have_text when the location of the text is not part of the behavior under test:
feature 'results page' do
scenario 'renders the API response', js: true do
visit '/results'
expect(page).to have_text('Expected text')
end
end
Capybara’s finder and matcher synchronization retries while asynchronous browser work is pending. The current documentation describes a default maximum wait of two seconds, configurable with Capybara’s wait settings. Prefer this retrying matcher to sleep 1; a sleep can be too short on a busy runner and unnecessarily slow when the response is immediate.
Wait for a state transition
For a loading flow, assert the stable result and, when useful, the disappearance of the loading state:
visit '/results'
expect(page).to have_text('Loading…')
expect(page).to have_text('Expected text')
expect(page).to have_no_text('Loading…')
Do not use an immediate negative predicate as a substitute for waiting. A check such as expect(page.has_no_text?('Loading…')).to be(true) can run before React has finished rendering, depending on timing and Capybara version. A synchronized matcher communicates the intended wait.
4. Scope the search to a component
A page-wide match can pass because the same words occur in a navigation item, hidden template, or unrelated component. Scope the assertion to a semantic container:
visit '/results'
expect(page).to have_css('#results', text: 'Expected text')
You can also locate a region and assert on its text:
results = find('#results')
expect(results).to have_text('Expected text')
Prefer stable IDs, accessible roles, labels, or other selectors owned by the component. Avoid selectors tied to generated class names. If the requirement is that a user can see a phrase, keep the text assertion; a selector-only assertion can pass even when the visible copy is wrong.
5. Interact before checking text
React often changes text after a click, form submission, or route transition. Perform the interaction, then let the matcher wait for the resulting state:
visit '/search'
fill_in 'Query', with: 'capybara'
click_button 'Search'
expect(page).to have_css('#results', text: 'Expected text')
If the click starts a request that never resolves, the matcher will eventually time out. That timeout is useful evidence: inspect the browser console, network path, test server logs, and the rendered page before changing the wait value.
6. Inspect rendered text with PhantomJS
When a Capybara assertion fails, PhantomJS exposes two useful debugging surfaces documented by its API.
Read the main frame as plain text
var text = page.plainText;
console.log(text);
plainText returns the main-frame page content without element tags. It is a diagnostic dump, not a replacement for a Capybara assertion: it does not express scope, visibility, or synchronization in your test.
Read one node with evaluate
var result = page.evaluate(function (selector) {
var node = document.querySelector(selector);
return node ? node.innerText : null;
}, '#results');
console.log(result);
PhantomJS runs the function in page context. Arguments and return values must be JSON-serializable; DOM nodes and closures cannot cross the boundary. Guard against a missing selector so a debugging probe does not throw a second, misleading error.
7. Configure waits without hiding real failures
Capybara retries finders and text matchers while asynchronous updates are pending. If your application legitimately needs longer than the default wait, configure the wait time for the slow operation or suite:
Capybara.default_max_wait_time = 5
Use the smallest value that covers the application’s normal response time. A very large global wait makes unrelated failures appear slow and can hide a broken request. First verify that the JavaScript driver is active, the test server is reachable, and the expected API response is available.
8. Troubleshooting checklist
| Symptom | Likely cause | Fix |
|---|---|---|
| Text is always missing | The default non-JavaScript driver is running. | Select a JavaScript driver and mark the example for JavaScript. |
| Assertion times out after a click | The request, route transition, or React update did not complete. | Check server logs and browser errors; verify the endpoint and test data before increasing the wait. |
| Text appears in a dump but matcher fails | Whitespace, visibility, or scope differs from the expectation. | Use a scoped matcher, confirm the exact rendered wording, and inspect the element’s visibility. |
| Poltergeist reports JavaScript errors | The page or bundle uses syntax unsupported by the PhantomJS runtime. | Enable JavaScript error reporting, inspect the failing bundle, and use a maintained JavaScript-capable driver for modern code. |
| PhantomJS executable cannot be found | The binary is absent or the configured path is wrong. | Install the executable or set Poltergeist’s executable path explicitly. |
| Selector inspection returns null | The node has not rendered yet or the selector is incorrect. | Wait with a Capybara matcher first, then run the diagnostic evaluation. |
| Page text differs between local and CI | Timing, viewport, environment data, or network behavior differs. | Use deterministic fixtures, a stable viewport, scoped assertions, and synchronized matchers. |
9. PhantomJS compatibility and migration decisions
Poltergeist’s README describes PhantomJS 1.8.1 as the minimum and documents that PhantomJS lacks ES6 support in that historical environment. Many current React bundles depend on language features or browser APIs that exceed those limits. If you are starting a new suite, choose a currently maintained JavaScript-capable browser driver supported by your project. If you are maintaining an existing suite, keep Poltergeist isolated, record its executable version, and plan migration around the application’s supported browsers.
Do not treat a passing plainText dump as proof that a real user can see the content. The test should assert the user-visible contract with Capybara, while PhantomJS APIs remain useful for diagnosing what the legacy browser rendered.
10. Performance, reliability, and cost notes
- Performance: JavaScript browser tests are slower than non-JavaScript requests because they start a browser, execute the bundle, and wait for asynchronous work. Keep selectors scoped and avoid unnecessary navigation.
- Reliability: deterministic fixtures and synchronized matchers reduce timing flake. Arbitrary sleeps increase runtime without proving readiness.
- Compatibility: legacy PhantomJS can fail before React renders when a bundle uses unsupported syntax. Treat driver choice as part of the application’s browser support policy.
- Cost: a self-hosted test stack costs engineering time and CI resources. For occasional visual inspection or generated images, an HTTP screenshot service can remove browser installation and maintenance.
11. Or skip the browser setup
ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns a PNG, JPEG, WebP, or PDF, so you can capture a rendered React route without installing PhantomJS or wiring Capybara to a browser. The ScreenshotNeo documentation lists the request options.

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 data = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', data);
ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed; response headers identify the page verdict and whether the request was billed. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients. The service also supports full-page and element capture, custom CSS and JavaScript, waits, request blocking, headers, cookies, user agents, authorization, device and viewport settings, dark mode, PDF options, caching, signed links, asynchronous jobs, bulk capture, and a usage API.
The Free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is available on every plan. Create a free ScreenshotNeo account.
12. FAQ
Should I use have_text or have_content?
They represent the same general text assertion in common Capybara usage. Use have_text in new examples for clarity and retain the alias when matching an existing suite’s conventions.
Why does React text require a JavaScript driver?
React may create or update the text after JavaScript executes. Capybara’s default driver does not execute JavaScript, so it cannot observe that rendered state.
Can PhantomJS inspect a DOM element directly?
Use page.evaluate with a selector and return serializable text such as innerText. Do not return a DOM node.
Is Poltergeist appropriate for a new project?
It is primarily a legacy maintenance option because the repository is archived and PhantomJS has historical ES6 limitations. Select a maintained JavaScript-capable driver for new work.
Can a screenshot replace a behavioral assertion?
No. A screenshot helps inspect visual output, while a Capybara matcher verifies a user-visible text contract and waits for asynchronous rendering.


