Back to Repositories

Validating XPath Element Matching in Capybara

This test suite validates the match_xpath? functionality in Capybara, focusing on element matching using XPath selectors. The tests ensure proper element identification and matching behavior across different selector scenarios.

Test Coverage Overview

The test suite covers essential XPath matching functionality in Capybara, verifying both positive and negative matching scenarios.

Key areas tested include:
  • Basic element presence validation using XPath
  • Class-specific element matching
  • Negative matching scenarios
  • Selector behavior with different default settings

Implementation Analysis

The implementation uses Capybara’s SpecHelper framework to structure the tests, with a before block setting up the test environment by visiting a specific page and finding an initial element.

The testing pattern follows a clear arrangement with distinct test cases for positive matches, negative matches, and selector consistency checks.

Technical Details

Testing tools and configuration:
  • Capybara SpecHelper for test organization
  • XPath selectors for element matching
  • CSS selectors for initial element location
  • Dynamic selector configuration testing

Best Practices Demonstrated

The test suite demonstrates several testing best practices including isolation of test cases, clear setup procedures, and comprehensive coverage of edge cases.

Notable practices:
  • Proper test isolation with before blocks
  • Clear expectation setting
  • Testing of both positive and negative scenarios
  • Verification of selector behavior across different configurations

teamcapybara/capybara

lib/capybara/spec/session/element/match_xpath_spec.rb

            
# frozen_string_literal: true

Capybara::SpecHelper.spec '#match_xpath?' do
  before do
    @session.visit('/with_html')
    @element = @session.find(:css, 'span.number')
  end

  it 'should be true if the given selector is on the page' do
    expect(@element).to match_xpath('//span')
    expect(@element).to match_xpath("//span[@class='number']")
  end

  it 'should be false if the given selector is not on the page' do
    expect(@element).not_to match_xpath('//abbr')
    expect(@element).not_to match_xpath('//div')
    expect(@element).not_to match_xpath("//span[@class='not_a_number']")
  end

  it 'should use xpath even if default selector is CSS' do
    Capybara.default_selector = :css
    expect(@element).not_to have_xpath("//span[@class='not_a_number']")
    expect(@element).not_to have_xpath("//div[@class='number']")
  end
end