Best Capybara code snippet using Capybara.Queries.selector_format
selector_query.rb
Source:selector_query.rb
...9 def initialize(*args,10 session_options:,11 enable_aria_label: session_options.enable_aria_label,12 test_id: session_options.test_id,13 selector_format: nil,14 **options,15 &filter_block)16 @resolved_node = nil17 @resolved_count = 018 @options = options.dup19 super(@options)20 self.session_options = session_options21 @selector = Selector.new(22 find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]),23 config: { enable_aria_label: enable_aria_label, test_id: test_id },24 format: selector_format25 )26 @locator = args.shift27 @filter_block = filter_block28 raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty?29 @expression = selector.call(@locator, @options)30 warn_exact_usage31 assert_valid_keys32 end33 def name; selector.name; end34 def label; selector.label || selector.name; end35 def description(only_applied = false)36 desc = +''37 show_for = show_for_stage(only_applied)38 if show_for[:any]39 desc << 'visible ' if visible == :visible40 desc << 'non-visible ' if visible == :hidden41 end42 desc << "#{label} #{locator.inspect}"43 if show_for[:any]44 desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text]45 desc << " with exact text #{exact_text}" if exact_text.is_a?(String)46 end47 desc << " with id #{options[:id]}" if options[:id]48 desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class]49 desc << case options[:style]50 when String51 " with style attribute #{options[:style].inspect}"52 when Regexp53 " with style attribute matching #{options[:style].inspect}"54 when Hash55 " with styles #{options[:style].inspect}"56 else ''57 end58 desc << selector.description(node_filters: show_for[:node], **options)59 desc << ' that also matches the custom filter block' if @filter_block && show_for[:node]60 desc << " within #{@resolved_node.inspect}" if describe_within?61 if locator.is_a?(String) && locator.start_with?('#', './/', '//')62 unless selector.raw_locator?63 desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \64 "Please see the documentation for acceptable locator values.\n\n"65 end66 end67 desc68 end69 def applied_description70 description(true)71 end72 def matches_filters?(node, node_filter_errors = [])73 return true if (@resolved_node&.== node) && options[:allow_self]74 matches_locator_filter?(node) &&75 matches_system_filters?(node) &&76 matches_node_filters?(node, node_filter_errors) &&77 matches_filter_block?(node)78 rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : [])79 false80 end81 def visible82 case (vis = options.fetch(:visible) { default_visibility })83 when true then :visible84 when false then :all85 else vis86 end87 end88 def exact?89 supports_exact? ? options.fetch(:exact, session_options.exact) : false90 end91 def match92 options.fetch(:match, session_options.match)93 end94 def xpath(exact = nil)95 exact = exact? if exact.nil?96 expr = apply_expression_filters(@expression)97 expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath)98 expr = filtered_expression(expr)99 expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression?100 expr101 end102 def css103 filtered_expression(apply_expression_filters(@expression))104 end105 # @api private106 def resolve_for(node, exact = nil)107 applied_filters.clear108 @resolved_node = node109 @resolved_count += 1110 node.synchronize do111 children = find_nodes_by_selector_format(node, exact).map(&method(:to_element))112 Capybara::Result.new(children, self)113 end114 end115 # @api private116 def supports_exact?117 return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil?118 @selector.supports_exact?119 end120 def failure_message121 +"expected to find #{applied_description}" << count_message122 end123 def negative_failure_message124 +"expected not to find #{applied_description}" << count_message125 end126 private127 def selector_format128 @selector.format129 end130 def matching_text131 options[:text] || options[:exact_text]132 end133 def text_fragments134 (text = matching_text).is_a?(String) ? text.split : []135 end136 def xpath_text_conditions137 case (text = matching_text)138 when String139 text.split.map { |txt| XPath.contains(txt) }.reduce(&:&)140 when Regexp141 condition = XPath.current142 condition = condition.uppercase if text.casefold?143 Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs|144 strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&)145 end.reduce(:|)146 end147 end148 def try_text_match_in_expression?149 first_try? &&150 matching_text &&151 @resolved_node.is_a?(Capybara::Node::Base) &&152 @resolved_node.session&.driver&.wait?153 end154 def first_try?155 @resolved_count == 1156 end157 def show_for_stage(only_applied)158 lambda do |stage = :any|159 !only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage))160 end161 end162 def applied_filters163 @applied_filters ||= []164 end165 def find_selector(locator)166 case locator167 when Symbol then Selector[locator]168 else Selector.for(locator)169 end || Selector[session_options.default_selector]170 end171 def find_nodes_by_selector_format(node, exact)172 hints = {}173 hints[:uses_visibility] = true unless visible == :all174 hints[:texts] = text_fragments unless selector_format == :xpath175 hints[:styles] = options[:style] if use_default_style_filter?176 if selector_format == :css177 if node.method(:find_css).arity != 1178 node.find_css(css, **hints)179 else180 node.find_css(css)181 end182 elsif selector_format == :xpath183 if node.method(:find_xpath).arity != 1184 node.find_xpath(xpath(exact), **hints)185 else186 node.find_xpath(xpath(exact))187 end188 else189 raise ArgumentError, "Unknown format: #{selector_format}"190 end191 end192 def to_element(node)193 if @resolved_node.is_a?(Capybara::Node::Base)194 Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self)195 else196 Capybara::Node::Simple.new(node)197 end198 end199 def valid_keys200 VALID_KEYS + custom_keys201 end202 def matches_node_filters?(node, errors)203 applied_filters << :node204 unapplied_options = options.keys - valid_keys205 @selector.with_filter_errors(errors) do206 node_filters.all? do |filter_name, filter|207 next true unless apply_filter?(filter)208 if filter.matcher?209 unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name|210 unapplied_options.delete(option_name)211 filter.matches?(node, option_name, options[option_name], @selector)212 end213 elsif options.key?(filter_name)214 unapplied_options.delete(filter_name)215 filter.matches?(node, filter_name, options[filter_name], @selector)216 elsif filter.default?217 filter.matches?(node, filter_name, filter.default, @selector)218 else219 true220 end221 end222 end223 end224 def matches_filter_block?(node)225 return true unless @filter_block226 if node.respond_to?(:session)227 node.session.using_wait_time(0) { @filter_block.call(node) }228 else229 @filter_block.call(node)230 end231 end232 def filter_set(name)233 ::Capybara::Selector::FilterSet[name]234 end235 def node_filters236 if options.key?(:filter_set)237 filter_set(options[:filter_set])238 else239 @selector240 end.node_filters241 end242 def expression_filters243 filters = @selector.expression_filters244 filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set)245 filters246 end247 def custom_keys248 @custom_keys ||= node_filters.keys + expression_filters.keys249 end250 def assert_valid_keys251 unless VALID_MATCH.include?(match)252 raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}"253 end254 unhandled_options = @options.keys.reject do |option_name|255 valid_keys.include?(option_name) ||256 expression_filters.any? { |_name, ef| ef.handles_option? option_name } ||257 node_filters.any? { |_name, nf| nf.handles_option? option_name }258 end259 return if unhandled_options.empty?260 invalid_names = unhandled_options.map(&:inspect).join(', ')261 valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ')262 raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}"263 end264 def filtered_expression(expr)265 conditions = {}266 conditions[:id] = options[:id] if use_default_id_filter?267 conditions[:class] = options[:class] if use_default_class_filter?268 conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash)269 builder(expr).add_attribute_conditions(conditions)270 end271 def use_default_id_filter?272 options.key?(:id) && !custom_keys.include?(:id)273 end274 def use_default_class_filter?275 options.key?(:class) && !custom_keys.include?(:class)276 end277 def use_default_style_filter?278 options.key?(:style) && !custom_keys.include?(:style)279 end280 def apply_expression_filters(expression)281 unapplied_options = options.keys - valid_keys282 expression_filters.inject(expression) do |expr, (name, ef)|283 next expr unless apply_filter?(ef)284 if ef.matcher?285 unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name|286 unapplied_options.delete(option_name)287 ef.apply_filter(memo, option_name, options[option_name], @selector)288 end289 elsif options.key?(name)290 unapplied_options.delete(name)291 ef.apply_filter(expr, name, options[name], @selector)292 elsif ef.default?293 ef.apply_filter(expr, name, ef.default, @selector)294 else295 expr296 end297 end298 end299 def warn_exact_usage300 return unless options.key?(:exact) && !supports_exact?301 warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect."302 end303 def exact_text304 options.fetch(:exact_text, session_options.exact_text)305 end306 def describe_within?307 @resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node)308 end309 def document?(node)310 node.is_a?(::Capybara::Node::Document)311 end312 def simple_root?(node)313 node.is_a?(::Capybara::Node::Simple) && node.path == '/'314 end315 def apply_filter?(filter)316 filter.format.nil? || (filter.format == selector_format)317 end318 def matches_locator_filter?(node)319 return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter)320 @selector.locator_filter.matches?(node, @locator, @selector, exact: exact?)321 end322 def matches_system_filters?(node)323 applied_filters << :system324 matches_visibility_filters?(node) &&325 matches_id_filter?(node) &&326 matches_class_filter?(node) &&327 matches_style_filter?(node) &&328 matches_text_filter?(node) &&329 matches_exact_text_filter?(node)330 end...
selector_query_ext.rb
Source:selector_query_ext.rb
...4 applied_filters.clear5 @resolved_node = node6 @resolved_count += 17 node.synchronize do8 children = find_nodes_by_selector_format(node, exact).map(&method(:to_element))9 Capybara::Result.new(children, self)10 end11 end12 private13 # https://github.com/teamcapybara/capybara/blob/a7ebe1216f8d65f2e96c170437a732777353a81d/lib/capybara/queries/selector_query.rb#L22714 def find_nodes_by_selector_format(node, exact)15 hints = {}16 hints[:uses_visibility] = true unless visible == :all17 hints[:texts] = text_fragments unless selector_format == :xpath18 hints[:styles] = options[:style] if use_default_style_filter?19 hints[:position] = true if use_spatial_filter?20 if selector_format == :css21 if node.method(:find_css).arity != 122 node.find_css(css, **hints)23 else24 node.find_css(css)25 end26 elsif selector_format == :xpath27 if node.method(:find_xpath).arity != 128 node.find_xpath(xpath(exact), **hints)29 else30 node.find_xpath(xpath(exact))31 end32 else33 node.find_custom(selector_format, @expression)34 end35 end36end...
selector_format
Using AI Code Generation
1 def selector_format(sel)2 sel.to_s.gsub(/([A-Z])/) { |m| "_" + m.downcase }.gsub(/^_/, "")3puts selector_format(:button)4puts selector_format(:link)5 def selector_format(sel)6 sel.to_s.gsub(/([A-Z])/) { |m| "_" + m.downcase }.gsub(/^_/, "")7puts selector_format(:button)8puts selector_format(:link)9 def self.selector_format(sel)10 sel.to_s.gsub(/([A-Z])/) { |m| "_" + m.downcase }.gsub(/^_/, "")11puts selector_format(:button)12puts selector_format(:link)13 def self.selector_format(sel)14 sel.to_s.gsub(/([A-Z])/) { |m| "_" + m.downcase }.gsub(/^_/, "")
selector_format
Using AI Code Generation
1 Capybara::Poltergeist::Driver.new(app, { js_errors: false })2def selector_format(selector)3 Capybara::Queries::SelectorQuery.new(selector).selector4def find_element(selector)5 find(selector_format(selector))6def find_elements(selector)7 all(selector_format(selector))8def click_element(selector)9 find_element(selector).click10def send_keys_to_element(selector, keys)11 find_element(selector).send_keys(keys)12def is_element_visible?(selector)13 find_element(selector).visible?14def is_element_present?(selector)15 find_element(selector).present?16def is_element_enabled?(selector)17 find_element(selector).enabled?18def is_element_disabled?(selector)19 !is_element_enabled?(selector)20def is_element_checked?(selector)21 find_element(selector).checked?22def is_element_selected?(selector)23 find_element(selector).selected?24def is_element_clickable?(selector)25 find_element(selector).click
selector_format
Using AI Code Generation
1 def selector_format(selector)2 end.join(', ')3Capybara::Queries::SelectorQuery.new.selector_format(:xpath => '//div[@id="content"]//div[@class="page"]')4Capybara::Queries::SelectorQuery.new.selector_format({:xpath => '//div[@id="content"]//div[@class="page"]'})
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!