问题
From the Watir API, I've derived two assertions (which of course might not be correct):
- I can use
exists?
if I simply want to verify that the element is in the HTML. I don't care if it's visible or not. - I can use
visible?
if I want to be able to see it on the page.
So, when do I use present?
?
It seems to me that I could answer my own question by saying:
- I can use
present?
if I want to be able to see it on the page, but I don't want it to be in the HTML.
So, if I write something on the screen using a marker pen, would that be present?
?
(Sorry if I seem to be irreverent.)
So - another way to ask the question in the title - when should I use visible?
and when should I use present?
?
回答1:
The difference between visible?
and present?
is when the element does not exist in the HTML.
When the element is not in the HTML (ie exists?
is false):
visible?
will throw an exception.present?
will return false.
I tend to stick with present?
since I only care if a user can see the element. I do not care if it cannot be seen due to it being hidden via style, eg display:none;
, or not being in the DOM, eg it got deleted. I would only use visible?
if the application actually treats the element not being in the DOM as a different meaning than being in the DOM but not visible.
For example, given the page:
<html>
<body>
<div id="1" style="block:display;">This text is displayed</div>
<div id="2" style="block:none;">This text is not displayed</div>
</body>
</html>
You can see the difference when looking for a div that is not on the page:
browser.div(:id => '3').visible?
#=> Watir::Exception::UnknownObjectException
browser.div(:id => '3').present?
#=> false
For elements on the page, the two methods will be the same:
browser.div(:id => '1').visible?
#=> true
browser.div(:id => '1').present?
#=> true
browser.div(:id => '2').visible?
#=> false
browser.div(:id => '2').present?
#=> false
A comparison of these two methods along with exists?
can be found in the Watirways book.
来源:https://stackoverflow.com/questions/25877525/whats-the-difference-between-visible-and-present