Jquery是當下比較流行的1個js框架,通過使用webdriver的execute_script方法,我們可以將jquery庫結(jié)合到自動化測試中去。
結(jié)合jquery進行自動化測試的思想是這樣的:首先將jquery的源碼讀到1個string中去,然后使用execute_script執(zhí)行該string。執(zhí)行完畢后我們可以通過execute_script方法來調(diào)用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的庫函數(shù)實現(xiàn)了不去觸發(fā)Mouse Over Here鏈接而直接顯示隱藏div的效果(僅在ruby1.9.2下測試過,ruby1.8x應(yīng)該都不支持)
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來輔助測試實用性應(yīng)該不是很強,不過有些時候可以使用jquery方法來獲得dom節(jié)點的css屬性,從而達到簡化腳本的目的。