perpetuum mobile
17. 11. 2014. ruby gem * bdd / tdd

Capybara

Waiting (with timeout)

MAX_WAIT_TIME = 30
MAX_WAIT_TIME_SHORT = MAX_WAIT_TIME / 3

def wait_until_page_has_content(content, method, call=1)
  sleep 1
  Selenium::WebDriver::Wait.new(timeout: MAX_WAIT_TIME_SHORT).until do
    if content.is_a?(Array)
      content.any? { |c| page.body.match c }
    else
      page.body.match content
    end
  end
  return ''
rescue
  wait_until_page_has_content(content, method, call+1) unless call == 3
  return "; Action timed out at: #{method}"
end

def wait_until_page_has_selector(selector)
  t = Time.now.to_i
  until page.has_css?(selector) || Time.now.to_i - t > MAX_WAIT_TIME
    sleep 1
  end
end

Accept confirmation dialog

  def if_alert_accept_it
    wait = Selenium::WebDriver::Wait.new ignore: Selenium::WebDriver::Error::NoAlertPresentError
    alert = wait.until { page.driver.browser.switch_to.alert }
    alert.accept
  end

This would not work in Safari. The exact situation was that the tested site had a HTTP form within HTTPS page, and the workaround was to navigate to the HTTP version of the page, so that no dialog would be triggered.

Click first

page.first('.product-size.enabled').click

Hover

Hover does not for for Safari, so JS needs to be executed manually:

page.execute_script("jQuery('#{product[:menu_level_1]}').trigger('mouseenter')")

Resources