Implementation:Teamcapybara Capybara Selector Node Filter
| Knowledge Sources | |
|---|---|
| Domains | Testing, Selector_System |
| Last Updated | 2026-02-12 00:00 GMT |
Overview
Concrete tool for defining post-query node filters provided by Selector::Definition#node_filter and NodeFilter#matches?.
Description
Definition#node_filter delegates to FilterSet#node_filter (L18-22) which creates a NodeFilter instance. The filter stores a block that receives a DOM node and a filter value, returning Boolean. During query resolution, NodeFilter#matches? calls the block; false removes the node from results and collects a @errors message. Boolean-typed filters auto-generate descriptive error messages.
Usage
Define inside an add_selector block for post-DOM-query validation.
Code Reference
Source Location
- Repository: capybara
- File: lib/capybara/selector/filter_set.rb (L18-22), lib/capybara/selector/filters/node_filter.rb (L8-21 initialize, L23-27 matches?)
Signature
# Inside a selector definition block:
node_filter(name, *types, **options, &block)
# @param name [Symbol, Regexp] Filter name
# @param types [Symbol] Type flags (:boolean)
# @param options [Hash] valid_values:, default:, skip_if:, matcher:
# @yield [node, value] Block that evaluates the node
# @yieldparam node [Capybara::Node::Element] The candidate element
# @yieldparam value The filter value
# @yieldreturn [Boolean] Whether the node matches
# NodeFilter#matches? (internal)
def matches?(node, name, value, context)
# Calls the block, returns Boolean
# Collects error message on false
end
Import
require 'capybara'
# Used within Capybara.add_selector blocks
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| name | Symbol/Regexp | Yes | Filter option name |
| types | Symbol | No | Type flags (:boolean) |
| valid_values | Array | No | Accepted filter values |
| block | Block | Yes | Receives (node, value), returns Boolean |
Outputs
| Name | Type | Description |
|---|---|---|
| match result | Boolean | Whether the node passes the filter |
Usage Examples
Boolean Node Filter
Capybara.add_selector(:toggle) do
css { |locator| ".toggle[data-name='#{locator}']" }
node_filter(:enabled, :boolean) do |node, value|
node['aria-disabled'] != 'true' == value
end
end
find(:toggle, 'notifications', enabled: true)
Custom Value Filter
Capybara.add_selector(:price_cell) do
css { '.price' }
node_filter(:min_value) do |node, value|
node.text.gsub(/[^0-9.]/, '').to_f >= value
end
end
all(:price_cell, min_value: 100.0)