Watir – 页面对象
Watir – 页面对象
Watir 中的页面对象帮助我们以类的形式重用代码。使用页面对象功能,我们可以自动化我们的应用程序,而无需复制任何代码,并使代码易于管理。
测试时,我们可以为要测试的每个页面创建页面对象。然后,我们将使用页面对象访问方法和属性。
使用页面对象背后的原因 –
-
如果在更改更改时对页面进行了任何更改,则不需要重新编写代码。
-
避免代码冗余。
我们将使用 RSpec 在 Watir 中使用页面对象。如果您不熟悉 RSpec,这里有一个完整的RSpec教程供您学习。
我们要执行测试的页面在这里给出 –
文本框.html
<html>
<head>
<title>Testing UI using Watir</title>
</head>
<body>
<script type = "text/javascript">
function wsentered() {
console.log("inside wsentered");
var firstname = document.getElementById("firstname");
if (firstname.value != "") {
document.getElementById("displayfirstname").innerHTML =
"The name entered is : " + firstname.value;
document.getElementById("displayfirstname").style.display = "";
}
}
</script>
<div id = "divfirstname">
Enter First Name :
<input type = "text" id = "firstname" name = "firstname" onchange = "wsentered()" />
</div>
<br/>
<br/>
<div style = "display:none;" id = "displayfirstname"></div>
</body>
</html>
输出

我们现在将为上述页面创建页面对象,如下所示 –
页面对象测试.rb
class InitializeBrowser
def initialize(browser)
@browser = browser
end
end
class TestPage lt; InitializeBrowser
def textbox
@textbox = TestTextbox.new(@browser)
end
def close
@browser.screenshot.save 'usingpageobject.png'
@browser.close
end
end # TestPage
class TestTextbox < InitializeBrowser
URL = "http://localhost/uitesting/textbox.html"
def open
@browser.goto URL
self
end
def enterdata_as(name)
name_field.set name
name_field.fire_event('onchange')
end
private
def name_field
@browser.text_field(:id > "firstname")
end
end # TestTextbox
定义了三个类 – InitializeBrowser、TestPage 和 TestTextbox –
-
InitializeBrowser – 这将初始化打开的浏览器并与 TestPage 和 TestTextbox 类共享浏览器对象。
-
TestPage – 此类将具有对 TestTextbox 的对象引用,并包含捕获屏幕截图和关闭浏览器的方法。
-
TestTextbox – 此类将具有打开页面 url、引用文本字段、设置数据和触发 onchange 事件的方法。
执行上面显示的代码后,您可以看到如下所示的输出 –
