Watir - 在方法之外记录

时间:2010-07-02 21:21:04

标签: ruby testing automation watir logging

我在使用Watir进行自动化测试方面仍然相当新,我遇到了另一个可能非常简单的问题,我需要向社区伸出援手,以便朝着正确的方向发展。

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

以下是我正在玩的示例代码:

    $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

谢谢!

1 个答案:

答案 0 :(得分:0)

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