An Overview on Custom Selectors
Let’s understand Custom Selectors. But before that let’s have a look at Capybara. It provides developers to simulate a user on a web page as well as make assertions based on the content and environment of the page. Moreover, it also offers an API to interact with the web page.
It is also possible to define your own custom selectors. This can be very useful when we want to make modular selectors that can be reused in many scripts. Here is an example:
Capybara.add_selector(:my_selector) do
xpath { “actual_xpath” }
end
find(:my_selector)
We can even pass arguments to the selectors (just like they are methods):
Capybara.add_selector(:my_selector) do
xpath { |arg| “//xpath/#{arg}” }
end
find(:my_selector, arg)
or combine custom selectors with scoping:
Capybara.add_selector(:my_selector_area) do
xpath { “actual_xpath” }
end
within(:my_selector_area) do
fill_in ‘Name’, :with => ‘John’
fill_in ‘Email’, :with => ‘[email protected]’
end
Further, here are some best practices around Capybara DSL usage, custom selectors, and scoping and matching:
Scope part of the DOM on which action is performed.
So, inside this scope prefer Capybara DSL when possible.
If it’s not possible, use relative xpath/CSS selectors within the scope.
xpath/CSS selectors should be as shallow as possible inside the scope.
Make your resume stand out and become a Certified Capybara Testing Professional. Try free practice tests here!
A great career is just a certification away. So, practice and validate your skills to become Certified Capybara Testing Professional