1

在使用 Watir 进行自动化测试方面,我还是个新手,而且我遇到了另一个可能非常简单的问题,我需要与社区联系,以便朝着正确的方向前进。

我正在尝试在 Watir 中使用记录器,如果我将所有内容都保留在方法中,我可以正常工作。如果我没有定义方法,例如使用循环时,我无法让记录器工作。

这是我正在玩的示例代码:

    $LOAD_PATH << File.dirname(__FILE__)
require 'xls'
require 'watir'

xlFile = XLS.new(Dir.pwd + '/test_XLS_data.xls') #grab the data file in the same dirrectory
myData = xlFile.getRowRecords('Google Search Data','Example')  #pull data records  from excel
xlFile.close


myData.each do |record|
  ie = Watir::IE.start('google.com')
  ie.text_field(:name,'q').set(record['SearchString'])
  ie.button(:value,/Search/i).click
  if ie.contains_text(record['ContainsText'])
    puts "Results of search: '#{record['SearchString']}' contains '#{record['ContainsText']}'"
  else
    puts "Error: could not find text: '#{record['ContainsText']}' in results of search: '#{record['SearchString']}'"
  end
  sleep 3
  ie.close
end

以下是我所做的目前失败的修改:

$LOAD_PATH << File.dirname(__FILE__)

require 'xls'
require 'watir'
require 'example_logger1.rb'

def setup
    filePrefix = "xls_log"
    #create a logger 
    $logger = LoggerFactory.start_xml_logger(filePrefix) 
    $ie.set_logger($logger)
 end


 xlFile = XLS.new(Dir.pwd + '/test_XLS_data.xls') #grab the data file in the same dirrectory
 $logger.log("")
 $logger.log("getting data from Excel")
 myData = xlFile.getRowRecords('Google Search Data','Example')  #pull data records  from excel
 xlFile.close


myData.each do |record|
  ie = Watir::IE.start('google.com')
  ie.text_field(:name,'q').set(record['SearchString'])
  ie.button(:value,/Search/i).click
  if ie.contains_text(record['ContainsText'])
    puts "Results of search: '#{record['SearchString']}' contains '#{record['ContainsText']}'"
  else
    puts "Error: could not find text: '#{record['ContainsText']}' in results of search: '#{record['SearchString']}'"
  end
  sleep 3
  ie.close
end

谢谢!

4

1 回答 1

0

看起来你有一个范围问题。在方法或循环内定义变量时,它是仅存在于该方法或循环内的局部变量。一旦方法或循环退出,变量就消失了。您需要在 setup 方法之外声明 $logger 才能在该方法之外使用它。

于 2010-07-07T00:36:56.607 回答