The Issue
Trying to find and interact with the correct element can be a frustrating process. A common issue is trying to execute a Selenium or Watir Webdriver command on an element that shares the identifier you are using with other elements. Determining if a specific identifier is shared is important to troubleshooting your automated test script. How can we best determine this?
The Answer
We can check the count of elements with a shared identifier using the following Watir Webdriver command:
1 |
browser.elements(:text,"example").count |
We would replace elements and text with our respective identifiers. We require a plural element type when using the .count command. After entering the command, we are returned a value that indicates the element count on our page.
The Code
We can use the 3Qi Labs homepage for our example here:
1 2 3 4 5 6 7 |
#ElementCount.rb require 'watir-webdriver' require 'rubygems' browser = Watir::Browser.new :chrome browser.goto "https://3qilabs.com/" browser.links(:title,"Learn More").count puts "Learn More Link Count: #{browser.links(:title,"Learn More").count}" |
The Result
We save and run the automated test script (ElementCount.rb) and it runs the following:
- Browser opens
- Navigates to 3Qi Labs homepage
- Checks for count of Learn More link
- Count output is displayed
Here we see the count output displayed:
The Takeaway
You can now implement the .count command into your automated test scripts or debugging process. Using Selenium & Watir you can help troubleshoot an issue with element interaction, or simply confirm that the correct number of specified elements are displaying.