Class: Watir::Browser

Inherits:
Object
  • Object
show all
Includes:
AlertHelper, Container, HasWindow, Waitable
Defined in:
lib/watir-webdriver/browser.rb,
lib/watir-webdriver/extensions/alerts.rb,
lib/watir-webdriver/extensions/nokogiri.rb

Overview

The main class through which you control the browser.

Constant Summary

Constants included from Atoms

Atoms::ATOMS

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from AlertHelper

#confirm, #prompt

Methods included from Waitable

#wait_until, #wait_while

Methods included from HasWindow

#window, #windows

Methods included from Container

#a, #abbr, #abbrs, #address, #addresses, #area, #areas, #article, #articles, #as, #aside, #asides, #audio, #audios, #b, #base, #bases, #bdi, #bdis, #bdo, #bdos, #blockquote, #blockquotes, #body, #bodys, #br, #brs, #bs, #button, #buttons, #canvas, #canvases, #caption, #captions, #checkbox, #checkboxes, #cite, #cites, #code, #codes, #col, #colgroup, #colgroups, #cols, #data, #datalist, #datalists, #datas, #dd, #dds, #del, #dels, #details, #detailses, #dfn, #dfns, #dialog, #dialogs, #div, #divs, #dl, #dls, #dt, #dts, #element, #elements, #em, #embed, #embeds, #ems, #extract_selector, #field_set, #field_sets, #fieldset, #fieldsets, #figcaption, #figcaptions, #figure, #figures, #file_field, #file_fields, #font, #fonts, #footer, #footers, #form, #forms, #frame, #frames, #frameset, #framesets, #h1, #h1s, #h2, #h2s, #h3, #h3s, #h4, #h4s, #h5, #h5s, #h6, #h6s, #head, #header, #headers, #heads, #hgroup, #hgroups, #hidden, #hiddens, #hr, #hrs, #htmls, #i, #iframe, #iframes, #image, #images, #img, #imgs, #input, #inputs, #ins, #inses, #is, #kbd, #kbds, #keygen, #keygens, #label, #labels, #legend, #legends, #li, #link, #links, #lis, #main, #mains, #map, #maps, #mark, #marks, #menu, #menuitem, #menuitems, #menus, #meta, #metas, #meter, #meters, #nav, #navs, #noscript, #noscripts, #object, #objects, #ol, #ols, #optgroup, #optgroups, #option, #options, #output, #outputs, #p, #param, #params, #pre, #pres, #progress, #progresses, #ps, #q, #qs, #radio, #radios, #rp, #rps, #rt, #rts, #rubies, #ruby, #s, #samp, #samps, #script, #scripts, #section, #sections, #select, #select_list, #select_lists, #selects, #small, #smalls, #source, #sources, #span, #spans, #ss, #strong, #strongs, #style, #styles, #sub, #subs, #summaries, #summary, #sup, #sups, #table, #tables, #tbody, #tbodys, #td, #tds, #template, #templates, #text_field, #text_fields, #textarea, #textareas, #tfoot, #tfoots, #th, #thead, #theads, #ths, #time, #times, #titles, #tr, #track, #tracks, #trs, #u, #ul, #uls, #us, #var, #vars, #video, #videos, #wbr, #wbrs

Methods included from Atoms

load

Methods included from XpathSupport

downcase, escape

Constructor Details

#initialize(browser = :firefox, *args) ⇒ Browser

Creates a Watir::Browser instance.

Parameters:

  • browser (Symbol, Selenium::WebDriver) (defaults to: :firefox)

    :firefox, :ie, :chrome, :remote or Selenium::WebDriver instance

  • args

    Passed to the underlying driver



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/watir-webdriver/browser.rb', line 43

def initialize(browser = :firefox, *args)
  case browser
  when Symbol, String
    @driver = Selenium::WebDriver.for browser.to_sym, *args
  when Selenium::WebDriver::Driver
    @driver = browser
  else
    raise ArgumentError, "expected Symbol or Selenium::WebDriver::Driver, got #{browser.class}"
  end

  @error_checkers = []
  @current_frame  = nil
  @closed         = false
end

Instance Attribute Details

#driverObject (readonly) Also known as: wd

Returns the value of attribute driver.



13
14
15
# File 'lib/watir-webdriver/browser.rb', line 13

def driver
  @driver
end

Class Method Details

.start(url, browser = :firefox, *args) ⇒ Watir::Browser

Creates a Watir::Browser instance and goes to URL.

Examples:

browser = Watir::Browser.start "www.google.com", :chrome
#=> #<Watir::Browser:0x..fa45a499cb41e1752 url="http://www.google.com" title="Google">

Parameters:

  • url (String)
  • browser (Symbol, Selenium::WebDriver) (defaults to: :firefox)

    :firefox, :ie, :chrome, :remote or Selenium::WebDriver instance

Returns:



28
29
30
31
32
33
# File 'lib/watir-webdriver/browser.rb', line 28

def start(url, browser = :firefox, *args)
  b = new(browser, *args)
  b.goto url

  b
end

Instance Method Details

#add_checker(checker = nil) {|| ... } ⇒ Object

Adds new checker.

Checkers are generally used to ensure application under test does not encounter any error. They are automatically executed after following events:

1. Open URL
2. Refresh page
3. Click, double-click or right-click on element

Examples:

browser.add_checker do |page|
  page.text.include?("Server Error") and puts "Application exception or 500 error!"
end
browser.goto "www.mywebsite.com/page-with-error"
"Server error! (RuntimeError)"

Parameters:

  • checker (#call) (defaults to: nil)

    Object responding to call

Yields:

  • Checker block

Yield Parameters:



310
311
312
313
314
315
316
317
318
# File 'lib/watir-webdriver/browser.rb', line 310

def add_checker(checker = nil, &block)
  if block_given?
    @error_checkers << block
  elsif checker.respond_to? :call
    @error_checkers << checker
  else
    raise ArgumentError, "expected block or object responding to #call"
  end
end

#alertWatir::Alert

Handles JavaScript alerts, confirms and prompts.

Returns:



193
194
195
# File 'lib/watir-webdriver/browser.rb', line 193

def alert
  Alert.new driver.switch_to
end

#assert_existsObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Protocol shared with Watir::Element



363
364
365
366
367
368
369
370
# File 'lib/watir-webdriver/browser.rb', line 363

def assert_exists
  if @closed
    raise Exception::Error, "browser was closed"
  else
    driver.switch_to.default_content
    true
  end
end

#backObject

Navigates back in history.



87
88
89
# File 'lib/watir-webdriver/browser.rb', line 87

def back
  @driver.navigate.back
end

#browserObject



376
377
378
# File 'lib/watir-webdriver/browser.rb', line 376

def browser
  self
end

#closeObject Also known as: quit

Closes browser.



134
135
136
137
138
# File 'lib/watir-webdriver/browser.rb', line 134

def close
  return if @closed
  @driver.quit
  @closed = true
end

#cookiesWatir::Cookies

Handles cookies.

Returns:



147
148
149
# File 'lib/watir-webdriver/browser.rb', line 147

def cookies
  @cookies ||= Cookies.new driver.manage
end

#disable_checker(checker) ⇒ Object

Deletes checker.

Examples:

checker = lambda do |page|
  page.text.include?("Server Error") and puts "Application exception or 500 error!"
end
browser.add_checker checker
browser.goto "www.mywebsite.com/page-with-error"
"Server error! (RuntimeError)"
browser.disable_checker checker
browser.refresh


334
335
336
# File 'lib/watir-webdriver/browser.rb', line 334

def disable_checker(checker)
  @error_checkers.delete(checker)
end

#execute_script(script, *args) ⇒ Object

Executes JavaScript snippet.

If you are going to use the value snippet returns, make sure to use ‘return` explicitly.

Examples:

Check that Ajax requests are completed with jQuery

browser.execute_script("return jQuery.active") == '0'
#=> true

Get inner HTML of element

span = browser.span(class: "someclass")
browser.execute_script "return arguments[0].innerHTML", span
#=> "Span innerHTML"

Parameters:

  • script (String)

    JavaScript snippet to execute

  • *args

    Arguments will be available in the given script in the ‘arguments’ pseudo-array



258
259
260
261
262
263
# File 'lib/watir-webdriver/browser.rb', line 258

def execute_script(script, *args)
  args.map! { |e| e.kind_of?(Watir::Element) ? e.wd : e }
  returned = @driver.execute_script(script, *args)

  wrap_elements_in(returned)
end

#exist?Boolean Also known as: exists?

Returns true if browser is not closed and false otherwise.

Returns:

  • (Boolean)


352
353
354
# File 'lib/watir-webdriver/browser.rb', line 352

def exist?
  not @closed
end

#forwardObject

Navigates forward in history.



95
96
97
# File 'lib/watir-webdriver/browser.rb', line 95

def forward
  @driver.navigate.forward
end

#goto(uri) ⇒ String

Goes to the given URL.

Examples:

browser.goto "www.google.com"

Parameters:

  • uri (String)

    The url.

Returns:

  • (String)

    The url you end up at.



74
75
76
77
78
79
80
81
# File 'lib/watir-webdriver/browser.rb', line 74

def goto(uri)
  uri = "http://#{uri}" unless uri =~ URI.regexp

  @driver.navigate.to uri
  run_checkers

  url
end

#htmlString

Returns HTML code of current page.

Returns:

  • (String)


182
183
184
185
# File 'lib/watir-webdriver/browser.rb', line 182

def html
  # use body.html instead?
  @driver.page_source
end

#inspectObject



58
59
60
61
62
# File 'lib/watir-webdriver/browser.rb', line 58

def inspect
  '#<%s:0x%x url=%s title=%s>' % [self.class, hash*2, url.inspect, title.inspect]
rescue
  '#<%s:0x%x closed=%s>' % [self.class, hash*2, @closed.to_s]
end

#nameSymbol

Returns browser name.

Examples:

browser = Watir::Browser.new :chrome
browser.name
#=> :chrome

Returns:

  • (Symbol)


162
163
164
# File 'lib/watir-webdriver/browser.rb', line 162

def name
  @driver.browser
end

#ready_stateString

Returns readyState of document.

Returns:

  • (String)


225
226
227
# File 'lib/watir-webdriver/browser.rb', line 225

def ready_state
  execute_script 'return document.readyState'
end

#refreshObject

Refreshes current page.



201
202
203
204
# File 'lib/watir-webdriver/browser.rb', line 201

def refresh
  @driver.navigate.refresh
  run_checkers
end

#reset!Object



372
373
374
# File 'lib/watir-webdriver/browser.rb', line 372

def reset!
  # no-op
end

#run_checkersObject

Runs checkers.



342
343
344
# File 'lib/watir-webdriver/browser.rb', line 342

def run_checkers
  @error_checkers.each { |e| e.call(self) }
end

#screenshotWatir::Screenshot

Handles screenshots of current pages.

Returns:



285
286
287
# File 'lib/watir-webdriver/browser.rb', line 285

def screenshot
  Screenshot.new driver
end

#send_keys(*args) ⇒ Object

Sends sequence of keystrokes to currently active element.

Examples:

browser.goto "http://www.google.com"
browser.send_keys "Watir", :return

Parameters:

  • *args (String, Symbol)


275
276
277
# File 'lib/watir-webdriver/browser.rb', line 275

def send_keys(*args)
  @driver.switch_to.active_element.send_keys(*args)
end

#statusString

Returns the text of status bar.

Returns:

  • (String)


235
236
237
# File 'lib/watir-webdriver/browser.rb', line 235

def status
  execute_script "return window.status;"
end

#textString

Returns text of page body.

Returns:

  • (String)


172
173
174
# File 'lib/watir-webdriver/browser.rb', line 172

def text
  @driver.find_element(:tag_name, "body").text
end

#titleString

Returns title of current page.

Examples:

browser.goto "http://www.google.com"
browser.title
#=> "Google"

Returns:

  • (String)


126
127
128
# File 'lib/watir-webdriver/browser.rb', line 126

def title
  @driver.title
end

#urlString

Returns URL of current page.

Examples:

browser.goto "http://www.google.com"
browser.url
#=> "http://www.google.com"

Returns:

  • (String)


110
111
112
113
# File 'lib/watir-webdriver/browser.rb', line 110

def url
  assert_exists
  @driver.current_url
end

#wait(timeout = 5) ⇒ Object

Waits until readyState of document is complete.

Parameters:

  • timeout (Fixnum) (defaults to: 5)

Raises:



213
214
215
216
217
# File 'lib/watir-webdriver/browser.rb', line 213

def wait(timeout = 5)
  wait_until(timeout, "waiting for document.readyState == 'complete'") do
    ready_state == "complete"
  end
end