Sometimes you might wish to implement a QTP-like ‘object repository’. I’ve had most success implementing this via Ruby modules.
To ‘learn’ all the objects on a page using firewatir you can use a simple script like this:
require 'rubygems'
require 'firewatir'
class NilClass
def length
0
end
end
class DiscoverObjects
include FireWatir
def initialize(url)
if url
# attach to specific url
@b = Firefox.start(url)
else
# attach to existing window
@b = Firefox.new
end
end
def all
@objects = {}
[:links, :text_fields, :buttons, :select_lists].each do |type|
@b.send(type).each do |element|
@objects[element] = {}
@objects[element][:type] = type.to_s[0..-2]
# omitted :href, :url, :class
[:id, :name, :value, :text, :index, :xpath, :title, :action, :src, :for].each do |attrib|
value = element.send(attrib)
@objects[element][attrib] = value unless value.empty?
end
end
end
end
def print_objects
puts "module #{@b.title.to_s.gsub(/[^\d\w]/,'').capitalize}"
puts "# Objects learned from: #{@b.url}\n# #{Time.now}"
@objects.each do |key,val|
val.each do |k,v|
unless k.to_s =~ /type/
method_name = "#{val[:type]}_#{k}_#{v.to_s.gsub(/[^\d\w]/,'_').downcase}"
puts "\tdef #{method_name.gsub('__','_').gsub(/_$/,'')}"
puts "\t\treturn @b.#{val[:type]}(:#{k}, \"#{v}\")\n\tend\n\n"
end
end
end
puts "end"
end
end
url = ARGV[0]
discover = DiscoverObjects.new(url)
discover.all
discover.print_objects
Which will produce results like this:
module Firefoxwebbrowserfastermoresecurecustomizable
# Objects learned from: http://www.mozilla.com/en-US/firefox/
# Sat Sep 27 07:40:08 +1000 2008
def link_text_qmo
return @b.link(:text, "QMO")
end
def link_text_press_center
return @b.link(:text, "Press Center")
end
def link_text_other_systems_and_languages
return @b.link(:text, "Other Systems and Languages")
end
end
Feel free to modify to suit (for watir or the like). I develop on a Mac, so firewatir is easiest for me. The manual way is to just use the IE Developer Toolbar or Firebug depending on your platform.