Understanding Selectors
Let’s start by Understanding Selectors. A simple selector is either a type selector or universal selector followed immediately by zero or more attribute selectors, ID selectors, or pseudo-classes, in any order. Moreover, it matches only if all of its components match. Therefore, a selector is a chain of one or more simple selectors separated by combinators. Not to mention, combinators are white space, “>”, and “+”. However, white space may appear between a combinator and the simple selectors around it.
In the same vein, the elements of the document tree that match a selector are called subjects of the selector. Moreover, a selector consists of a single simple selector matches any element satisfying its requirements. Further, prepending a simple selector and combinator to a chain imposes additional matching constraints, so the subjects of a selector are always a subset of the elements matching the last simple selector.
Selectors
Certainly, Capybara does not try to guess what kind of selector you are going to give it, and will always use CSS by default. If you want to use XPath, you’ll need to do:
within(:xpath, ‘//ul/li’) { … }
find(:xpath, ‘//ul/li’).text
find(:xpath, ‘//li[contains(.//a[@href = “#”]/text(), “foo”)]’).value
Alternatively you can set the default selector to XPath:
Capybara.default_selector = :xpath
find(‘//ul/li’).text
Moreover, Capybara allows you to add custom selectors, which can be very useful if you find yourself using the same kinds of selectors very often:
Capybara.add_selector(:id) do
xpath { |id| XPath.descendant[XPath.attr(:id) == id.to_s] }
end
Capybara.add_selector(:row) do
xpath { |num| “.//tbody/tr[#{num}]” }
end
Capybara.add_selector(:flash_type) do
css { |type| “#flash.#{type}” }
end
So, The block given to xpath must always return an XPath expression as a String, or an XPath expression generated through the XPath gem. Moreover, you can now use these selectors like this:
find(:id, ‘post_123’)
find(:row, 3)
find(:flash_type, :notice)
The above example clearly explains working with windows. We hope this is section is now clear to you. But, in case you need more assistance, we’re always here to help. So, try the links below for further assistance.
Make your resume stand out and become a Certified Capybara Testing Professional. So,Try free practice tests here!
A great career is just a certification away. So, practice and validate your skills to become a Certified Capybara Testing Professional.