创建测试用例
1.Class 类必须以大写字母开头后面紧跟< Test::Unit::TestCase 2.def 方法必须以 test 开头 3.当一个类里面有多个方法时,ruby 默认会随机运行测试案例,如果需要顺序 执 行 , 需 要 在 test 后 加 上 字 母 或 数 字 来 强 迫 它 顺 序 执 行 , 比 如 “test_a_mytest” 4.测试用例模型: require 'rubygems' require 'watir' require 'test/unit' class TC_myTest < Test::Unit::TestCase def test_ myTestCase #用例内容 end def test_anotherTestCase #用例内容 end def test_aTestCase #用例内容 end end 5.应用举例 require 'rubygems' require 'watir' require 'test/unit' class GoogleHomePage < Test::Unit::TestCase def test_jointest i=1 j=1 for i in 1..10 for j in 1..10 Watir::IE.each do |ie| ie.close end j=j+1 end
ie = Watir::IE.start "google.tw/" ie.text_field(:id, "lst-ib").set "site:jointest.org" ie.button(:value, "Google
搜索").click ie.link(:text, " 自 动 化 测 试 论 坛 - JoinTest - Powered by Discuz!").click i=i+1 end end end
3.2 if 判断和断言
1.用 if 判断事物真假 #判断当前页面是否存在“欢迎您...”这几个连续的字(字符串) if ie.contains_text("欢迎您...") #判断当前页面是否存在 “name“等于“loginname”的控件 if ie.text_field(:name,"loginname").exists? #判断当前页面是否存在 “value “等于“登录”的控件 if ie.button(:value , "登录").exists? #判断当前页面是否存在 “立即购买”这几个连续的字(字符串) if ie.text.include?("立即购买")
2.断言事物的真假 #断言当前页面的标题“ie.title“等于"会员登录/注册",为真继续,为假抛出 错误 assert_equal(ie.title, "
会员登录/
注册") #断言当前页面存在 “name“等于“loginname”的控件,为真继续,为假抛出 错误 assert(ie.text_field(:name,"loginname").exists?)
#断言当前页面存在 “name“等于“loginname”的控件,为假继续
,为真抛出 错误 assert_false(ie.text_field(:name,"loginname").exists?) #断言当前页面存在 “value ”等于“登录”的控件,为真继续,为假抛出错误 assert(ie.button(:value , "登录").exists?) #断言当前页面存在“立即购买“这几个连续的字,为真继续,为假抛出错误 assert(ie.text.include?("立即购买")
四.常见问题及解决方案
我们经常会碰到,且在
网络上至今没有很好的解决方案的三个问题,我研究了几 个解决方案,验证了上百次,次次能成功执行,现分享给大家!
4.1 关闭所有 IE
关于关闭所有打开的 IE 不能关闭完全的
问题,用一个循环搞定 i=1 for i in 1..10 Watir::IE.each do |ie| ie.close end i=i+1 end
4.2 JS 弹出窗口处理
用一个近似死循环的循环搞定 autoit = WIN32OLE.new('AutoItX3.Control') while ie.link(:text , "删除").exists? ie.link(:text , "删除").click_no_wait ret = 1 while ret==1
#切换 #autoit.Send('{TAB}') #取消 #autoit.Send('{ESC}') #删除 autoit.Send('{ENTER}') #第一个''内容为弹出层标题,第二个''内容为提示框包含的内容,可以为 空,9表示检查次数 ret = autoit.WinWait('来自网页的消息', '你确认删除吗', 9) end end
4.3 不能 set 中文的问题(新手建议
方案一)
方案一:可以用 value 代替 set,举例如下 ie.text_field(:name, "loginname").set"中文账号" ie.text_field(:name, "loginname").value = "中文账号" 方案二: 1.当前所有 class 文件编码格式统一选 GB2312(或者 GBK) 2.所有 ruby class 文件代码前面加 require 'win32ole' WIN32OLE.codepage = WIN32OLE::CP_ACP
方案三: 1.当前所有 class 文件编码格式统一选 GB2312(或者 GBK) 2.C:\Ruby187\lib\ruby\gems\1.8\gems\watir-1.6.5\lib\watir 文件下 win32ole.rb 里面的 WIN32OLE.codepage = WIN32OLE::CP_UTF8 改成 WIN32OLE.codepage = WIN32OLE::CP_ACP