Jquery 是当下比较流行的 1 个 js 框架,通过使用 webdriver 的 execute_script 方法,我们可以将 jquery 库结合到自动化测试中去.
结合 jquery 进行自动化测试的思想是这样的:首先将 jquery 的源码读到 1 个 string 中去,然后使用 execute_script 执行该 string.执行完毕后我们就可以通过 execute_script 方法来调用 jquery 库了.
下面的 html 代码中有一个隐藏的 div,当鼠标移动到 (mouseover) 页面上名为 Mouse Over Here 的链接时,隐藏的 div 将会显示出来.
<html>
<head>
<title>
FireEvent
</title>
<style>
.mo {color: blue;} .tips {display:none;border: 1px solid #ccc; background-color:#EFEFEF;width:
100px;height:100px}
</style>
<script>
function show_tips() {
document.getElementById("t").style.display = "block";
}
function hide_tips() {
document.getElementById("t").style.display = "none";
}
</script>
</head>
<body>
<a class="mo" href="#" onmouseover="show_tips()" onmouseout="hide_tips()">
Mouse Over Here
</a>
<div id="t" class="tips">
This is the tips of link
</div>
</body>
</html>
下面的代码使用 jquery 的库函数实现了不去触发 Mouse Over Here 链接而直接显示隐藏 div 的效果 (仅在 ruby1.9.2 下测试过,ruby1.8x 应该都不支持)
jquery_helper.rb#encoding: utf - 8 module JqueryHelper def load_jquery dr,
jquery_path jq = read_jquery(jquery_path) jq.force_encoding('utf-8') dr.execute_script jq end def read_jquery(jquery_path) js = ''File.open(File.expand_path(jquery_path), 'r') do | f | js = f.read end js end end
fire_event.rb require 'rubygems'require 'selenium-webdriver'require './jquery_helper'include JqueryHelper dr = Selenium: :WebDriver.
for: firefox select_file = 'file:///'.concat File.expand_path(File.join(File.dirname(__FILE__), 'fire_event.html')) dr.navigate.to select_file jquery_path = './jquery-1.6.4.min.js'load_jquery dr,
jquery_path jq = <<JQ $("#t").show();
JQ dr.execute_script jq
使用 jquery 来辅助测试实用性应该不是很强,不过有些时候可以使用 jquery 方法来获得 dom 节点的 CSS 属性,从而达到简化脚本的目的.
来源: http://lib.csdn.net/article/jquery/36416