开发者

How to detect if an element exists in 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/re开发者_开发技巧viewertools/editreview.jpg").exists? then...

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


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜