File: link.rb

package info (click to toggle)
ruby-capybara 3.40.0%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,368 kB
  • sloc: ruby: 23,988; javascript: 752; makefile: 11
file content (55 lines) | stat: -rw-r--r-- 2,096 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# frozen_string_literal: true

Capybara.add_selector(:link, locator_type: [String, Symbol]) do
  xpath do |locator, href: true, alt: nil, title: nil, target: nil, **|
    xpath = XPath.descendant(:a)
    xpath = builder(xpath).add_attribute_conditions(href: href) unless href == false

    if enable_aria_role
      role_path = XPath.descendant[XPath.attr(:role).equals('link')]
      role_path = builder(role_path).add_attribute_conditions(href: href) unless [true, false].include? href

      xpath += role_path
    end

    unless locator.nil?
      locator = locator.to_s
      matchers = [XPath.attr(:id) == locator,
                  XPath.string.n.is(locator),
                  XPath.attr(:title).is(locator),
                  XPath.descendant(:img)[XPath.attr(:alt).is(locator)]]
      matchers << XPath.attr(:'aria-label').is(locator) if enable_aria_label
      matchers << XPath.attr(test_id).equals(locator) if test_id
      xpath = xpath[matchers.reduce(:|)]
    end

    xpath = xpath[find_by_attr(:title, title)]
    xpath = xpath[XPath.descendant(:img)[XPath.attr(:alt) == alt]] if alt
    xpath = xpath[find_by_attr(:target, target)] if target

    xpath
  end

  node_filter(:href) do |node, href|
    # If not a Regexp it's been handled in the main XPath
    (href.is_a?(Regexp) ? node[:href].match?(href) : true).tap do |res|
      add_error "Expected href to match #{href.inspect} but it was #{node[:href].inspect}" unless res
    end
  end

  expression_filter(:download, valid_values: [true, false, String]) do |expr, download|
    builder(expr).add_attribute_conditions(download: download)
  end

  describe_expression_filters do |download: nil, **options|
    desc = +''
    if (href = options[:href])
      desc << " with href #{'matching ' if href.is_a? Regexp}#{href.inspect}"
    elsif options.key?(:href) && href != false # is nil specified?
      desc << ' with no href attribute'
    end
    desc << " with download attribute#{" #{download}" if download.is_a? String}" if download
    desc << ' without download attribute' if download == false
    desc
  end
end