debugrubyMinor
Ruby selenium script waiting for an element to disappear
Viewed 0 times
scriptwaitingseleniumdisappearforelementruby
Problem
I'm a Java developer, I'm new to Ruby and I'm worried that I'm forcing or not-so-well using the goodness of the Ruby syntax.
- What do you think about the Exception catching and how to print it in error messages?
- What about the code block (closure?) I'm passing to the "until" method?
- Is it ok to implicitly rely on what the last executed sentence of the block will be, regarding what would be its returned value?
def waitUntilDisappears(type, name) #Waits for a particular element to disappear
begin
puts "Waiting for element #{name} to disappear..."
wait = Selenium::WebDriver::Wait.new(:timeout => 5)
wait.until do
element = driver.find_element(type, name)
if element != nil
displayValue = element.css_value("display")
puts "Element #{name} has displayValue #{displayValue}."
displayValue != "block"
end
end
puts "Element #{name} disappeared or not present. OK."
rescue Exception => e
puts "Error: Could not wait for element #{name} to disappearDetails: #{e.inspect}"
end
end
Solution
Some notes:
I'd write:
waitUntilDisappears. In Ruby, always:wait_until_disappears.
if element != nil->if element.
if element != nil. I think find_element never returnsnil, it raises exception if not found, so this is not needed.
rescue Exception => e. A rescue that covers a whole method can omit thebegin.
rescue Exception => e. Rescuing fromExceptionis bad practice. Rescue fromStandardError, which is the same asrescue => e.
puts "Error". It's bad practice to catch an exception (even worse ifit's all exceptions), just print to the screen and return as if nothing happened. Raise an exception or return a value that signals the error.
- Is Element#visible? not enough?
I'd write:
def wait_until_disappears(type, name, timeout: 5)
wait = Selenium::WebDriver::Wait.new(timeout: timeout)
wait.until { !driver.find_element(type, name).visible? }
endCode Snippets
def wait_until_disappears(type, name, timeout: 5)
wait = Selenium::WebDriver::Wait.new(timeout: timeout)
wait.until { !driver.find_element(type, name).visible? }
endContext
StackExchange Code Review Q#77433, answer score: 4
Revisions (0)
No revisions yet.