views:

35

answers:

1

I'm still fairly new in using Watir for automation testing and I've hit another possibly insanely easy problem that I need to reach out to the community for a little bump in the right direction.

I'm trying to use logger in Watir, which I can get to work fine if I keep everything within methods. If I don't have a method defined, for instance when using a loop, I can't get logger to work.

Here is an example code I'm playing with:

    $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

Here are the modifications I made which are currently failing:

$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

Thanks!

A: 

It looks like you have a scoping problem. When you define a variable inside of a method or loop, it's a local variable that exists only within that method or loop. Once the method or loop exits, the variable is gone. You'll need to declare $logger outside of the setup method for it to be available outside of that method.

redjen
Yeah I tried that as well but I keep getting an error which leads me to believe that I must put this in a method for it to work:BoxDemo.rb:29:in `<class:TC_SearchSKUs>': undefined method `set_logger' for nil:NilClass (NoMethodError) from BoxDemo.rb:8:in `<main>'Keep in mind if I define this within a variable and use it within other methods it does work. This is the only situation where I've not had it work.
r3nrut