Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if an element exists in Watir

Tags:

ruby

watir

I'm relatively new to Watir but can find no good documentation (examples) regarding how to check if an element exists. There are the API specs, of course, but these make precious little sense to me if I don't find an example.

I've tried both combinations but nothing seems to work... if browser.image (:src "/media/images/icons/reviewertools/editreview.jpg").exists then... if browser.image (:src "/media/images/icons/reviewertools/editreview.jpg").exists? then...

If anyone has a concrete suggestion as per how to implement this, please help! Thanks!

like image 855
Rijksband Avatar asked Mar 18 '11 22:03

Rijksband


2 Answers

It seems you are missing a comma between parameters.

Should be

if browser.image(:src, "/media/images/icons/reviewertools/editreview.jpg").exists?

Also you can find this page useful in future to know what attributes are supported.

like image 76
katmoon Avatar answered Oct 06 '22 13:10

katmoon


Seems like you are using it correctly. Here is an old RDoc of Watir.

Does it not work because Watir cannot find it? Hard to tell because there is no source or link to the page that is being tested. I think that I only use image.exists?. In general, errors that come from when the image exists but is not found are:

  1. The how is not compatible with the element type. There is a cheatsheet to help you see which object types can be found with different attributes here.
  2. The what is not correct. You may have to play with that a little bit. Consider trying a regex string to match it such as browser.image(:src, /editreview.jpg/). As a last resort, maybe use element_by_xpath, but there are maintenance costs with that.
  3. The location is not correct. Maybe the element is in a frame or something like that. browser.frame("detail").image(:src, /editreview.jpg/).

Try those, but please let me know what worked. One more thing, what are you checking for? If it's part of the test criteria, you can handle it that way. If you need to click on it, then forget the .exists? and just click on it. Ruby will let you know if it's not there. If you need it to be grace, learn about begin/rescue.

Good luck,

Dave

like image 21
Dave McNulla Avatar answered Oct 06 '22 12:10

Dave McNulla