How to detect if an element exists in Watir

2020-08-26 04:01发布

问题:

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!

回答1:

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.



回答2:

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



回答3:

The code you posted should work just fine. Edit: Oops, wrong. As Katmoon pointed out, there is a missing comma.

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

One problem you may get caught up in is if the browser variable you specified is actually an element that doesn't exist.

e.g.

b = Watir::IE.start(ipAddress)
b.frame(:name, "doesntExist).image(:src "/media/images/icons/reviewertools/editreview.jpg").exists?

The above code will throw a Watir::UnknownFrameException. You can get around this by first verifying the frame exists or by surrounding the code in a begin/rescue block.



标签: ruby watir