代码之家  ›  专栏  ›  技术社区  ›  Bogdan Gusiev

Webrat+Selenium WebDriver:等待Ajax完成

  •  5
  • Bogdan Gusiev  · 技术社区  · 15 年前

    在我们的应用程序中,我们运行的webrat带有selenium2.0,即webdriver。

    WebDriver可以很好地处理页面重新加载,如果浏览器正在重新加载整个页面,则不要启动下一步。问题是这个机制不适用于Ajax请求。WebDriver不会在单击()或更改()后执行任何空闲操作。

    有人能建议如何使WebDriver在页面上所有Ajax请求结束之前保持空闲吗?

    3 回复  |  直到 14 年前
        1
  •  3
  •   zcrar70    14 年前

    最后,我们在Selenium上编写了一个层,通过将调用包装在可选循环中来处理这个场景。所以当你这样做的时候:

    @browser.click "#my_button_id"
    

    它的作用类似于Automatedtester上面所建议的:

    class Browser
      def click(locator)
        wait_for_element(locator, :timeout => PAGE_EVENT_TIMEOUT)
        @selenium.click(locator)
      end
    
      def wait_for_element(locator, options)
        timeout = options[:timeout] || PAGE_LOAD_TIMEOUT
        selenium_locator = locator.clone
        expression = <<EOF 
          var element;
          try {
            element = selenium.browserbot.findElement('#{selenium_locator}');
          } catch(e) {
            element = null;
          };
          element != null;
    EOF
        begin
          selenium.wait_for_condition(expression, timeout)
        rescue ::Selenium::SeleniumException
          raise "Couldn't find element with locator '#{locator}' on the page: #{$!}.\nThe locator passed to selenium was '#{selenium_locator}'"
        end
      end
    end
    

    包装器还做了其他的事情,比如允许通过按钮/输入标签等进行搜索(所以包装器不仅存在于时间问题上,这只是我们放在其中的一件事情)。

        2
  •  1
  •   AutomatedTester    15 年前

    对不起,我的红宝石,但是你需要做的是试着找到这个物体,如果它不在那里,就等它回来。下面的代码应该做的是每隔一秒等待一分钟,尝试查看驱动程序是否可以找到具有ID的元素。 idOfElement 如果不行的话,它应该抛出一个错误

    assert !60.times{ break if (driver.find_element(:id, "idOfElement) rescue false); sleep 1 }
    
        3
  •  0
  •   dmp    14 年前

    一个单独的mtd(包装器)来检查元素是否等待应该会有所帮助。