Principle:Teamcapybara Capybara Auto Waiting
| Knowledge Sources | |
|---|---|
| Domains | Testing, Synchronization |
| Last Updated | 2026-02-12 00:00 GMT |
Overview
A retry-based synchronization mechanism that automatically waits for asynchronous page changes by re-executing queries until they succeed or a timeout expires.
Description
Auto Waiting solves the fundamental challenge of testing asynchronous web applications: the DOM may not be in the expected state when a query executes. Instead of requiring manual sleep calls, Capybara's synchronize method wraps element finding and assertion operations in a retry loop that:
- Executes the given block
- If a qualifying exception occurs (ElementNotFound, ExpectationNotMet, or driver-specific stale element errors), catches it
- Checks if the timeout has expired; if so, raises the exception
- Otherwise, sleeps for default_retry_interval (default 0.01 seconds) and retries
- Optionally reloads stale elements (if automatic_reload is enabled)
The timeout defaults to default_max_wait_time (2 seconds) and can be overridden per-call.
Usage
This mechanism is used implicitly by all finder and matcher methods. You rarely need to call synchronize directly — it wraps find, all, has_selector?, assert_selector, etc. Override the wait time via the :wait option on any query.
Theoretical Basis
# Abstract synchronize algorithm (not actual code)
def synchronize(seconds, errors):
return yield if already_synchronized
timer = start_timer(seconds)
loop:
try:
return yield # success
catch error in errors:
raise if timer.expired?
sleep(retry_interval)
reload_element if automatic_reload
retry