Implementation:Teamcapybara Capybara Session Within
| Knowledge Sources | |
|---|---|
| Domains | Testing, Scoping |
| Last Updated | 2026-02-12 00:00 GMT |
Overview
Concrete tool for scoping Capybara operations to a DOM subtree provided by Capybara::Session#within.
Description
Session#within accepts the same arguments as find (or a Capybara::Node::Base instance directly). It pushes the found element onto the @scopes stack, yields the block, and pops the scope in an ensure block. Convenience variants within_fieldset and within_table scope to fieldset or table elements by id, legend, or caption.
Usage
Wrap interactions in within to scope to a container. Accepts CSS selectors, named selectors, or pre-found elements.
Code Reference
Source Location
- Repository: capybara
- File: lib/capybara/session.rb
- Lines: L362-371 (within), L379-381 (within_fieldset), L389-391 (within_table)
Signature
def within(*args, **kw_args)
# @param args Same as #find, or a Capybara::Node::Base instance
# @yield [new_scope] Block of scoped operations
# @return [Object] Block return value
end
def within_fieldset(locator, &block)
# @param locator [String] Id or legend of the fieldset
end
def within_table(locator, &block)
# @param locator [String] Id or caption of the table
end
Import
require 'capybara'
# within is available via Capybara::DSL or directly on Session
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| args | Symbol, String, Node::Base | Yes | Selector args or a node to scope to |
| block | Block | Yes | Operations to perform within the scope |
Outputs
| Name | Type | Description |
|---|---|---|
| block result | Object | Return value of the block |
Usage Examples
Scoping to a Form
within('#login-form') do
fill_in 'Email', with: 'user@example.com'
fill_in 'Password', with: 'secret'
click_button 'Log in'
end
Scoping to a Table
within_table('Users') do
expect(page).to have_selector('tr', count: 5)
end
Nested Scopes
within('#sidebar') do
within('.navigation') do
click_link 'Settings'
end
end