Class: RWebSpec::Mechanize::WebBrowser

Inherits:
Object
  • Object
show all
Defined in:
lib/rwebspec-mechanize/web_browser.rb

Overview

Wrapping WATIR IE and FireWatir Firefox

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_url = nil, existing_browser = nil, options = {}) ⇒ WebBrowser

Returns a new instance of WebBrowser.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rwebspec-mechanize/web_browser.rb', line 20

def initialize(base_url = nil, existing_browser = nil, options = {})
  default_options = {:go => false}
  options = default_options.merge options
  @context = Context.new base_url if base_url
			@browser = ::Mechanize.new

			require 'logger'
			# http://mechanize.rubyforge.org/Mechanize.html
			# TODO option to turn off mechanize logging
  #			puts "Max file buffer #{@browser.max_file_buffer}"
  #			puts "Follow redirect? #{@browser.follow_redirect?}"
  #			puts "redirect limit =>  #{@browser.redirection_limit}"
  #			@browser.log = Logger.new("mech.log") 
			@browser.keep_alive = false
			@browser.open_timeout = 15
			@browser.read_timeout = 15
			# @browser.max_file_buffer=(bytes)
			
			if options[:go]
@browser.get(base_url)
			else
@browser
			end
end

Instance Attribute Details

#contextObject

Returns the value of attribute context.



18
19
20
# File 'lib/rwebspec-mechanize/web_browser.rb', line 18

def context
  @context
end

Class Method Details

.attach_browser(how, what, options = {}) ⇒ Object

Attach to existing browser

Usage:

WebBrowser.attach_browser(:title, "iTest2")
WebBrowser.attach_browser(:url, "http://www.itest2.com")
WebBrowser.attach_browser(:url, "http://www.itest2.com", {:browser => "Firefox", :base_url => "http://www.itest2.com"})
WebBrowser.attach_browser(:title, /agileway\.com\.au\/attachment/)  # regular expression


558
559
560
561
562
563
564
565
566
567
568
# File 'lib/rwebspec-mechanize/web_browser.rb', line 558

def self.attach_browser(how, what, options={})
  default_options = {:browser => "IE"}
  options = default_options.merge(options)
  site_context = Context.new(options[:base_url]) if options[:base_url]
  if (options[:browser] == "Firefox")
    ff = FireWatir::Firefox.attach(how, what)        
    return WebBrowser.new_from_existing(ff, site_context)
  else
    return WebBrowser.new_from_existing(Watir::IE.attach(how, what), site_context)
  end
end

.close_all_browsers(browser_type = :ie) ⇒ Object



231
232
233
# File 'lib/rwebspec-mechanize/web_browser.rb', line 231

def self.close_all_browsers(browser_type = :ie)      
  
end

.is_windows?Boolean

is it running in MS Windows platforms?

Returns:

  • (Boolean)


642
643
644
# File 'lib/rwebspec-mechanize/web_browser.rb', line 642

def self.is_windows?
  RUBY_PLATFORM.downcase.include?("mswin") or RUBY_PLATFORM.downcase.include?("mingw")
end

Instance Method Details

#agentObject



50
51
52
# File 'lib/rwebspec-mechanize/web_browser.rb', line 50

def agent
  @browser
end

#area(*args) ⇒ Object

Wrapp of Watir’s area to support Firefox and Watir

Note: FireWatir does not support area directly, treat it as text_field



71
72
73
74
75
76
77
# File 'lib/rwebspec-mechanize/web_browser.rb', line 71

def area(*args)
  if is_firefox?
    text_field(*args)
  else
    @browser.send("area", *args)
  end
end

#base_url=(new_base_url) ⇒ Object



216
217
218
219
220
221
222
# File 'lib/rwebspec-mechanize/web_browser.rb', line 216

def base_url=(new_base_url)
  if @context
    @conext.base_url = new_base_url
    return
  end
  @context = Context.new base_url
end

#begin_at(relative_url) ⇒ Object



243
244
245
# File 'lib/rwebspec-mechanize/web_browser.rb', line 243

def begin_at(relative_url)
  @browser.goto full_url(relative_url)
end

#browser_opened?Boolean

Returns:

  • (Boolean)


247
248
249
250
251
252
253
# File 'lib/rwebspec-mechanize/web_browser.rb', line 247

def browser_opened?
  begin
    @browser != nil
  rescue => e
    return false
  end
end

#check_checkbox(checkBoxName, values = nil) ⇒ Object

Check a checkbox Usage:

check_checkbox("agree")
check_checkbox("agree", "true")


469
470
471
472
473
474
475
476
477
478
479
480
481
# File 'lib/rwebspec-mechanize/web_browser.rb', line 469

def check_checkbox(checkBoxName, values=nil)						
  the_form = identify_form
  if values
    values.class == Array ? arys = values : arys = [values]
    arys.each {|cbx_value|
      the_form.checkboxes_with(:name => checkBoxName).each do |cb|
        cb.check if cb.value == cbx_value
      end
    }     
  else
    the_form.checkbox_with(:name => checkBoxName).check
  end
end

#clear_radio_option(radio_group, radio_option) ⇒ Object Also known as: clear_radio_button

Clear a radio button

Usage:
  click_radio_option("country", "Australia")


515
516
517
# File 'lib/rwebspec-mechanize/web_browser.rb', line 515

def clear_radio_option(radio_group, radio_option)
  radio(:name => radio_group, :value => radio_option).uncheck				
end

#click_button_with_caption(caption, opts = {}) ⇒ Object Also known as: click_button, click_button_with_text, click_button_with_value

Click a button with caption Usage:

click_button_with_caption("Confirm payment")


414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'lib/rwebspec-mechanize/web_browser.rb', line 414

def click_button_with_caption(caption, opts={})
the_form = identify_form
    if opts && opts[:index]
      wait_before_and_after { 
        the_form.button_with(:value => caption)[opts[:index]].click
	}
    else
      wait_before_and_after { 
				# button(:caption, caption).click;
			if the_form.button(:value => caption).type == "submit"
				@browser.submit(the_form, the_form.button(:value => caption))
			else
				the_form.button_with(:value => caption).click
			end
	}
    end
end

#click_button_with_id(id, opts = {}) ⇒ Object

Occasionaly, the button with ID exists, but now shown in the form (debug form.inspect), add efault to submit



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/rwebspec-mechanize/web_browser.rb', line 348

def click_button_with_id(id, opts = {})			
  the_form = identify_form			
  the_button = nil
			# puts "[DEBUG] click button with id => #{id} | #{opts.inspect} | #{the_form.inspect}"
  if opts && opts[:index]
      wait_before_and_after {         
        the_button = the_form.buttons_with(:id => id)[opts[:index]]
      }
  else
      wait_before_and_after { 
        the_button = the_form.button_with(:id => id)
      }
  end

			if the_button.nil?
@browser.submit(the_form)
return
			end
			
  # raise "No button with id: #{id} found " unless the_button
  if the_button.type == "submit"				
    @browser.submit(the_form, the_button)
  else
    @browser.submit(the_form, the_button)        
  end
			
end

#click_button_with_name(name, opts = {}) ⇒ Object

Click a button with give name Usage:

click_button_with_name("confirm")


379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# File 'lib/rwebspec-mechanize/web_browser.rb', line 379

def click_button_with_name(name, opts={})
  the_form = identify_form
  if opts && opts[:index]
    wait_before_and_after { 
      the_button = the_form.buttons_with(:name => name)[opts[:index]]
      # button(:name => name, :index => opts[:index]).click 
    }
  else
    wait_before_and_after {
      the_button = the_form.button_with(:name =>  name)
    }
  end

  raise "No button with id: #{id} found " unless the_button
  if the_button.type == "submit"
    @browser.submit(the_form, the_button)
  else
    puts "Warning not submit button"
    @browser.submit(the_form, the_button)        
  end

end

links



309
310
311
312
313
314
315
316
317
318
319
# File 'lib/rwebspec-mechanize/web_browser.rb', line 309

def click_link_with_id(link_id, opts = {})
  if opts && opts[:index]
    wait_before_and_after { 
      page.links_with(:id => link_id)[options[:index]].click
    }
  else
    wait_before_and_after {
      page.link_with(:id => link_id).click   				
    }
  end 
end


321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/rwebspec-mechanize/web_browser.rb', line 321

def click_link_with_text(link_text, opts = {})
  if opts && opts[:index]
    wait_before_and_after { 
      page.link_with(:text => link_text)[opts[:index]].click  
    }
  else
    wait_before_and_after {      
  		begin
      	page.link_with(:text => link_text).click  
	rescue => e
		# NOTE
		# e.g. <a href="..."> New client</a>, the link with space
		# puts "exact link #{link_text} not found, just regex"
		page.link_with(:text => /#{link_text}/).click
	end
    }          
  end 
end

#click_radio_option(radio_group, radio_option) ⇒ Object Also known as: click_radio_button

Click a radio button

Usage:
  click_radio_option("country", "Australia")


505
506
507
508
509
# File 'lib/rwebspec-mechanize/web_browser.rb', line 505

def click_radio_option(radio_group, radio_option)
  # radio(:name => radio_group, :value => radio_option).set
  the_form = identify_form
  the_form.radiobutton_with(:name => radio_group, :value => radio_option).check
end

#close_browserObject Also known as: close

Close the browser window. Useful for automated test suites to reduce test interaction.



226
227
228
# File 'lib/rwebspec-mechanize/web_browser.rb', line 226

def close_browser
  @browser = nil
end

#contains_text(text) ⇒ Object



151
152
153
# File 'lib/rwebspec-mechanize/web_browser.rb', line 151

def contains_text(text)
  @browser.contains_text(text);
end

#dump_response(stream = nil) ⇒ Object


For deubgging




591
592
593
# File 'lib/rwebspec-mechanize/web_browser.rb', line 591

def dump_response(stream = nil)
  stream.nil? ?  puts(page_source) : stream.puts(page_source)
end

#element(how, what) ⇒ Object

  • how - symbol - how we access the element. Supports all values except :index and :xpath

  • what - string, integer or regular expression - what we are looking for,

Valid values for ‘how’ are listed in the Watir Wiki - wiki.openqa.org/display/WTR/Methods+supported+by+Element

returns an Watir::Element object

Typical Usage

element(:class, /foo/)      # access the first element with class 'foo'. We can use a string in place of the regular expression
element(:id, "11")          # access the first element that matches an id


95
96
97
# File 'lib/rwebspec-mechanize/web_browser.rb', line 95

def element(how, what)
  return @browser.element(how, what)
end

#element_by_id(elem_id) ⇒ Object

Deprecated: using Watir style directly instead



521
522
523
# File 'lib/rwebspec-mechanize/web_browser.rb', line 521

def element_by_id(elem_id)
  elem = @browser.document.getElementById(elem_id)
end

#element_source(elementId) ⇒ Object



530
531
532
533
534
# File 'lib/rwebspec-mechanize/web_browser.rb', line 530

def element_source(elementId)
  elem = element_by_id(elementId)
  assert_not_nil(elem, "HTML element: #{elementId} not exists")
  elem.innerHTML
end

#element_value(elementId) ⇒ Object



525
526
527
528
# File 'lib/rwebspec-mechanize/web_browser.rb', line 525

def element_value(elementId)
  elem = element_by_id(elementId)
  elem ? elem.invoke('innerText') : nil
end

#elements(how, what) ⇒ Object

this is the main method for accessing generic html elements by an attribute

Returns a HTMLElements object

Typical usage:

elements(:class, 'test').each { |l| puts l.to_s }  # iterate through all elements of a given attribute
elements(:alt, 'foo')[1].to_s                       # get the first element of a given attribute
elements(:id, 'foo').length                        # show how many elements are foung in the collection


109
110
111
# File 'lib/rwebspec-mechanize/web_browser.rb', line 109

def elements(how, what)
  return @browser.elements(how, what)
end

#enter_text_into_field_with_name(name, value) ⇒ Object Also known as: set_form_element, enter_text

text fields



294
295
296
297
298
299
300
301
302
# File 'lib/rwebspec-mechanize/web_browser.rb', line 294

def enter_text_into_field_with_name(name, value)
			the_form = identify_form
  wait_before_and_after { 
the_form.fields_with(:name => name).each do |x|
	next unless x.type == "text" || x.type == "password" || x.type == "hidden" || x.type == "textarea"
	x.value = value
end
			}
end

#expect_page(page_clazz, argument = nil) ⇒ Object

Verify the next page following an operation.

Typical usage:

browser.expect_page HomePage


633
634
635
636
637
638
639
# File 'lib/rwebspec-mechanize/web_browser.rb', line 633

def expect_page(page_clazz, argument = nil)
  if argument
    page_clazz.new(self, argument)
  else
    page_clazz.new(self)
  end
end

#full_url(relative_url) ⇒ Object



235
236
237
238
239
240
241
# File 'lib/rwebspec-mechanize/web_browser.rb', line 235

def full_url(relative_url)
  if @context && @context.base_url
    @context.base_url + relative_url
  else
    relative_url
  end
end

#goto_page(page) ⇒ Object

Go to a page

Usage:
  open_browser("http://www.itest2.com"
  ....
  goto_page("/purchase")  # full url => http://www.itest.com/purchase


283
284
285
# File 'lib/rwebspec-mechanize/web_browser.rb', line 283

def goto_page(page)
  goto_url full_url(page);
end

#goto_url(url) ⇒ Object

Go to a URL directly

goto_url("http://www.itest2.com/downloads")


289
290
291
# File 'lib/rwebspec-mechanize/web_browser.rb', line 289

def goto_url(url)
  @browser.get(url)
end

#identify_formObject



402
403
404
405
406
407
408
409
# File 'lib/rwebspec-mechanize/web_browser.rb', line 402

def identify_form
  the_form = page.forms.first
	if the_form.nil?
		sleep 0.1
	  the_form = page.forms.first				
	end
	return the_form
end

#javascript_dialogObject

Watir 1.9



543
544
545
# File 'lib/rwebspec-mechanize/web_browser.rb', line 543

def javascript_dialog
	@browser.javascript_dialog
end

#locate_input_element(how, what, types, value = nil) ⇒ Object

Returns the specified ole object for input elements on a web page.

This method is used internally by Watir and should not be used externally. It cannot be marked as private because of the way mixins and inheritance work in watir

* how - symbol - the way we look for the object. Supported values are
               - :name
               - :id
               - :index
               - :value etc
* what  - string that we are looking for, ex. the name, or id tag attribute or index of the object we are looking for.
* types - what object types we will look at.
* value - used for objects that have one name, but many values. ex. radio lists and checkboxes


129
130
131
# File 'lib/rwebspec-mechanize/web_browser.rb', line 129

def locate_input_element(how, what, types, value=nil)
  @browser.locate_input_element(how, what, types, value)
end

#map(how, what = nil) ⇒ Object

This is the main method for accessing map tags - msdn.microsoft.com/workshop/author/dhtml/reference/objects/map.asp?frame=true

*  how   - symbol - how we access the map,
*  what  - string, integer or regular expression - what we are looking for,

Valid values for ‘how’ are listed in the Watir Wiki - wiki.openqa.org/display/WTR/Methods+supported+by+Element

returns a map object

Typical Usage

map(:id, /list/)                 # access the first map that matches list.
map(:index,2)                    # access the second map on the page
map(:title, "A Picture")         # access a map using the tooltip text. See http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/title_1.asp?frame=true


147
148
149
# File 'lib/rwebspec-mechanize/web_browser.rb', line 147

def map(how, what=nil)
  @browser.map(how, what)
end

#methodObject

Delegate to Watir



57
58
59
60
61
# File 'lib/rwebspec-mechanize/web_browser.rb', line 57

[:button, :cell, :checkbox, :div, :form, :frame, :h1, :h2, :h3, :h4, :h5, :h6, :hidden, :image, :li, :link, :map, :pre, :row, :radio, :select_list, :span, :table, :text_field, :paragraph, :file_field, :label].each do |method|
  define_method method do |*args|
    @browser.send(method, *args)
  end
end


79
80
81
# File 'lib/rwebspec-mechanize/web_browser.rb', line 79

def modal_dialog(how=nil, what=nil)
  @browser.modal_dialog(how, what)
end

#new_popup_window(options, browser = "ie") ⇒ Object

Attach a Watir::IE instance to a popup window.

Typical usage

new_popup_window(:url => "http://www.google.com/a.pdf")


574
575
576
577
578
579
580
581
582
583
584
585
586
# File 'lib/rwebspec-mechanize/web_browser.rb', line 574

def new_popup_window(options, browser = "ie")
  if is_firefox?
    raise "not implemented"
  else
    if options[:url]
      Watir::IE.attach(:url, options[:url])
    elsif options[:title]
      Watir::IE.attach(:title, options[:title])
    else
      raise 'Please specify title or url of new pop up window'
    end
  end
end

#pageObject



164
165
166
# File 'lib/rwebspec-mechanize/web_browser.rb', line 164

def page
	@browser.current_page
end

#page_sourceObject Also known as: html_body, html

return HTML of current web page



156
157
158
159
# File 'lib/rwebspec-mechanize/web_browser.rb', line 156

def page_source
  @browser.page.body
  #@browser.document.body
end

#page_titleObject



197
198
199
# File 'lib/rwebspec-mechanize/web_browser.rb', line 197

def page_title
  @browser.page.title
end

#save_page(file_name = nil) ⇒ Object

Save current web page source to file

usage:
   save_page("/tmp/01.html")
   save_page()  => # will save to "20090830112200.html"


622
623
624
625
626
# File 'lib/rwebspec-mechanize/web_browser.rb', line 622

def save_page(file_name = nil)
  file_name ||= Time.now.strftime("%Y%m%d%H%M%S") + ".html"
  puts "about to save page: #{File.expand_path(file_name)}" if $DEBUG
  File.open(file_name, "w").puts page_source
end

#select_file_for_upload(file_field, file_path) ⇒ Object



536
537
538
539
540
# File 'lib/rwebspec-mechanize/web_browser.rb', line 536

def select_file_for_upload(file_field, file_path)
  normalized_file_path = RUBY_PLATFORM.downcase.include?("mingw") ? file_path.gsub("/", "\\") : file_path
  the_form = identify_form
  the_form.file_uploads.first.file_name = normalized_file_path
end

#select_option(selectName, optionText) ⇒ Object

Select a dropdown list by name Usage:

select_option("country", "Australia")


439
440
441
442
443
444
445
446
447
448
449
# File 'lib/rwebspec-mechanize/web_browser.rb', line 439

def select_option(selectName, optionText)
  the_form = identify_form
  the_select_list = the_form.field_with(:name => selectName)
  the_select_list.options.each do |option|
    if option.text == optionText
      option.click
      break
    end
  end

end

#set_proxy(address, port, user = nil, password = nil) ⇒ Object

set proxy password



46
47
48
# File 'lib/rwebspec-mechanize/web_browser.rb', line 46

def set_proxy(address, port, user = nil, password = nil)
  @browser.set_proxy(address, port, user, password)
end

#show_all_objectsObject



113
114
115
# File 'lib/rwebspec-mechanize/web_browser.rb', line 113

def show_all_objects
  @browser.show_all_objects
end

#start_clicker(button, waitTime = 9, user_input = nil) ⇒ Object

A Better Popup Handler using the latest Watir version. Posted by [email protected]

wiki.openqa.org/display/WTR/FAQ#FAQ-HowdoIattachtoapopupwindow%3F



599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
# File 'lib/rwebspec-mechanize/web_browser.rb', line 599

def start_clicker( button, waitTime= 9, user_input=nil)
  # get a handle if one exists
  hwnd = @browser.enabled_popup(waitTime)
  if (hwnd)  # yes there is a popup
    w = WinClicker.new
    if ( user_input )
      w.setTextValueForFileNameField( hwnd, "#{user_input}" )
    end
    # I put this in to see the text being input it is not necessary to work
    sleep 3
    # "OK" or whatever the name on the button is
    w.clickWindowsButton_hwnd( hwnd, "#{button}" )
    #
    # this is just cleanup
    w = nil
  end
end

#start_window(url = nil) ⇒ Object



547
548
549
# File 'lib/rwebspec-mechanize/web_browser.rb', line 547

def start_window(url = nil)
  @browser.start_window(url);
end

#submit(buttonName = nil) ⇒ Object

submit first submit button



452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/rwebspec-mechanize/web_browser.rb', line 452

def submit(buttonName = nil)
  if (buttonName.nil?) then
    page.forms.first.submit
    # buttons.each { |button|
    #   next if button.type != 'submit'
    #   button.click
    #   return
    # }
  else
    click_button_with_name(buttonName)
  end
end

#text(squeeze_spaces = true) ⇒ Object

return plain text of current web page



169
170
171
172
173
174
175
176
177
178
179
# File 'lib/rwebspec-mechanize/web_browser.rb', line 169

def text(squeeze_spaces = true)
  require 'nokogiri'
			begin
  	page_text_string = Nokogiri::HTML(html).text
page_text_string = page_text_string.squeeze(" ") if squeeze_spaces# remove duplicated (spaces)
return page_text_string
			rescue => e
puts "failed to santize html source => text, #{e}"
			end
  return html
end

#text_sanitize(squeeze_spaces = true) ⇒ Object

Sanitize gem does not work in Java, return empty spaces back



182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/rwebspec-mechanize/web_browser.rb', line 182

def text_sanitize(squeeze_spaces = true)
  if RUBY_PLATFORM =~ /java/ || RUBY_PLATFORM =~ /jruby/
    require 'sanitize' 
  end

			begin
  	page_text_string = Sanitize.clean(html)
page_text_string = page_text_string.squeeze(" ") if squeeze_spaces# remove duplicated (spaces)
return page_text_string
			rescue => e
puts "failed to santize html source => text, #{e}"
			end
  # @browser.text
end

#uncheck_checkbox(checkBoxName, values = nil) ⇒ Object

UnCheck a checkbox Usage:

uncheck_checkbox("agree")
uncheck_checkbox("agree", "false")


487
488
489
490
491
492
493
494
495
496
497
498
499
# File 'lib/rwebspec-mechanize/web_browser.rb', line 487

def uncheck_checkbox(checkBoxName, values = nil)
  the_form = identify_form
  if values
    values.class == Array ? arys = values : arys = [values]
    arys.each {|cbx_value|
      the_form.checkboxes_with(:name => checkBoxName).each do |cb|
        cb.uncheck if cb.value == cbx_value
      end
    }     
  else
    the_form.checkbox_with(:name => checkBoxName).uncheck
  end
end

#urlObject

current url



212
213
214
# File 'lib/rwebspec-mechanize/web_browser.rb', line 212

def url
  @browser.url
end

#wait_before_and_afterObject

A convenience method to wait at both ends of an operation for the browser to catch up.



263
264
265
266
267
# File 'lib/rwebspec-mechanize/web_browser.rb', line 263

def wait_before_and_after
  wait_for_browser
  yield
  wait_for_browser
end

#wait_for_browserObject

Some browsers (i.e. IE) need to be waited on before more actions can be performed. Most action methods in Watir::Simple already call this before and after.



258
259
# File 'lib/rwebspec-mechanize/web_browser.rb', line 258

def wait_for_browser
end