ruby+watir--随机而不重复获取Menu菜单的元素
测试用例是类似上面的Menu菜单,共9个
先看看元素定义(yaml):
#频道切换-美食 channel_0_link: div(:class,'navMenuBg').li(:id,'num_2').link(:href,'http://beijing.xxxx.com/xxxshi') channel_0_link_on: div(:class,'navMenuBg').li(:id,'num_2').span(:class,'curCorner') #频道切换-娱乐 channel_1_link: div(:class,'navMenuBg').li(:id,'num_4').link(:href,'http://beijing.xxxx.com/xxxxian') channel_1_link_on: div(:class,'navMenuBg').li(:id,'num_4').span(:class,'curCorner') #频道切换-生活服务 channel_2_link: div(:class,'navMenuBg').li(:id,'num_5').link(:href,'http://beijing.xxxx.com/xxxxxhuo') channel_2_link_on: div(:class,'navMenuBg').li(:id,'num_5').span(:class,'curCorner') #频道切换-商品div(:class,'navMenuBg').li(:id,'num_6'). channel_3_link: link(:index,21) channel_3_link_on: span(:class,'curCorner') #频道切换-酒店div(:class,'navMenuBg').li(:id,'num_7'). channel_4_link: link(:index,22) channel_4_link_on: span(:class,'curCorner') #频道切换-旅游div(:class,'navMenuBg').li(:id,'num_8'). channel_5_link: link(:index,23) channel_5_link_on: span(:class,'curCorner') #频道切换-抽奖 channel_6_link: div(:class,'navMenuBg').li(:id,'num_9').link(:href,'http://www.xxxx.com/xxxxjiang') channel_6_link_on: div(:class,'navMenuBg').li(:id,'num_9').span(:class,'curCorner') #频道切换-促销 channel_7_link: div(:class,'navMenuBg').li(:id,'num_10').link(:href,'http://www.xxxx.com/xxxxxiao') channel_7_link_on: div(:class,'navMenuBg').li(:id,'num_10').span(:class,'curCorner') #频道切换-往期团购div(:class,'navMenuBg').li(:id,'num_12'). channel_8_link: link(:index,26) channel_8_link_on: span(:class,'curCorner')
测试用例:使用循环,随机获取9个Menu菜单,每个都必须点击到,并验证
def channel @b.goto URL channel = 0 while channel <= 8 times = rand(9).to_s AutoTest("channel_#{times}_link").click sleep 1 assert_true(AutoTest("channel_#{times}_link_on").exists?) channel += 1 end end
脚本中循环9次,每次都取一个随机值,随机数rand()是从0开始,所以我在元素定义时从0开始对这9个Menu菜单的元素进行编码,如:channel_0_link。
但是这里有个问题rand()函数中取的有重复值,即有些Menu菜单被点击2次或者多次,这就与我们的要求相驳。我几乎找遍了API,没有找到按顺序或者随机而不重复的方法。下一步我决定使用另外一种随机的方法来解决,其实随机播放分为两种,random和shuffle
def channel_food @b.goto URL linkid=[0,1,2,3,4,5,6,7,8] linkid.shuffle.each{ |i| times = i AutoTest("channel_#{times}_link").click sleep 1 assert_true(AutoTest("channel_#{times}_link_on").exists?) } end
以上的代码,可以实现随机获取9个Menu菜单,每个都必须点击到,并验证的需求。each的方法是从数组中获取数据;shuffle的方法是对获取的值进行重新排列,在洗牌程序中也是使用这种方法来做的(不会产生重复)。
a=[1,2,3,4,5,6,7,8,9] a.shuffle.each{ |i| b = i puts b }
大家可以去试试