-
Notifications
You must be signed in to change notification settings - Fork 220
异步请求
easonhan edited this page May 18, 2013
·
1 revision
处理Ajax请求的秘诀就是一直等,直到页面上我们关注的具体事件发生。page-object
支持两种等待方式——页面级别和元素级别。我们具体看一下。
在PageObject
模块中(也就是在你自定义的页面对象里)提供了下面的方法去等待事件发生。
def wait_until(timeout = 30, message = nil, &block)
这个方法会一直等待下去,直到其后接的代码块返回true为止。如果代码块在timeout
时间内(以秒为单位)没有返回true,那么该方法会抛出一个异常,并打印出错误信息message
,当然了你可以自定义这个出错信息。
@page.wait_until do
@page.text.include? "Success"
end
在上面的例子里我们使用了默认的timeout
和message
。这段代码会一直等下去,直到页面上出现了"Success"字符串为止。我们再看另一个例子。
@page.wait_until(5, "Call not returned within 5 seconds") do
@page.text.include? "Value returned from Ajax call"
end
在这个例子里我们定义了timeout
为5秒并且提供了一个自定义的message
。
Element
类提供了很多等待的方法。
def when_present(timeout = 5)
def when_visible(timeout = 5)
def when_not_visible(timeout = 5)
def wait_until(timeout = 5, message = nil, &block)
前三个方法的用法非常的直观(self explanatory)。它们会一直等,直到某个元素存在、可见、或者消失然后返回该元素。如果等待时间超过了timeout
那么抛出异常。我们看一个简单的例子
@page.foo_element.when_visible.foo
在这段代码里,我们等link(:foo, :id => 'cont')
这个链接可见的时候就去点击它。
有时你需要等除了element之外的东西出现或消失,这时候就可以使用wait_until
方法。该方法会一直等到代码块返回true为止。