MichaelR
MichaelR

Reputation: 999

Waiting for an element without throwing an exception if timed out

I know of the method Element#wait_until_present(t), but if this method times out it throws a timeOut exception.

Is there a method that just waits for t seconds and then returns true if the element became present or false otherwise?

I know it can be done with a simple begin..rescue..end statement, but I'm looking for something that doesn't use exceptions.

Upvotes: 3

Views: 1180

Answers (3)

Jarmo Pertman
Jarmo Pertman

Reputation: 1905

You can write a short-hand rescue clause like this:

element_present = browser.element.wait_until_present rescue false
puts "element not present" unless element_present

This does however result in a false value on any Exception at all and not just with TimeoutError. I still prefer to use it since if there's any Exception at all then it would be safer to assume that the element was not present.

Upvotes: 5

MichaelR
MichaelR

Reputation: 999

Looks like there is no other method that will do what i'm looking for ,

so here is the simplest method to achieve this :

#check method for Element#wait_until_present(t) 
def check_if_present(element,t)
    raise ArgumentError, 't must be a number ' unless t.is_a? Numeric
    begin
        element.wait_until_present(t)
        true
    rescue Watir::Wait::TimeoutError
        false
    rescue
        raise "Something wrong with the element"
    end
end

Upvotes: 3

Suriyakanth
Suriyakanth

Reputation: 267

If you do not want an exception the below code can be handy:

sleep 'your time here' eg: sleep 20 - this will wait for 20 secs.

then check for your element now:

'your element'.exists? -this will return true/false

you will not get an exception this way.

Another best way is to write your wait_for_load method based on your needs.

Upvotes: 1

Related Questions