Watir - Working with Browsers


Advertisements

By default, Watir will open chrome browser in-case the browser name is not specified. The required browser drivers are installed along with Watir installation. In case you face any issues working with browsers, install the driver as shown in the Browsers drivers chapter and update the location in PATH variable.

In this chapter, we will understand how to open the browser using Watir.

Steps to Open a Browser using Watir

Open the IDE RubyMine and create a new file: test1.rb

Browser Using Watir

IDE RubyMine

Select OK and click the file pattern as ruby as shown below −

File Pattern

Click on OK to create the file.

Now we will write a simple code that will open the browser as shown below −

test1.rb

require 'watir'
Watir::Browser.new
Simple Code

Click on the Run button that is highlighted in the IDE as shown above. On-click of Run, it will open browser as shown below −

Run Button

The browser will open and close automatically. Let us now add some more code to the test1.rb.

We can specify the name of the browser as shown below −

Example for Chrome

require 'watir'
Watir::Browser.new :chrome

Now let us open a page-url in our test case.

Example

require 'watir'
browser = Watir::Browser.new
browser.goto("https://www.google.com")

Click on Run to see the output as shown below −

Test Case Output

Similarly, you can open firefox, safari, Internet explorer browser.

Example for Firefox

require 'watir'
Watir::Browser.new :firefox
Example for Firefox

Example for Internet Explorer

Watir Code

require 'watir'
browser = Watir::Browser.new :ie
browser.goto("https://www.google.com")

When we run the code following error is displayed −

Unable to find IEDriverServer. Please download the server from
(Selenium::WebDriver::Error::WebDriverError)

http://selenium-release.storage.googleapis.com/index.html and place it
somewhere on your PATH.

More info at
https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver.

This means that watir package does not have InternetExplorer Driver. We have downloaded the same from here − https://docs.seleniumhq.org/download/ and updated in PATH variable.

Now run it again to see the Internet Explorer browser opening as shown below −

Explorer Browser Opening

Watir code to open Safari Browser

require 'watir'
browser = Watir::Browser.new :safari
browser.goto("https://www.google.com")

Watir code to Microsoft Edge browser

require 'watir'
browser = Watir::Browser.new :edge
browser.goto("https://www.google.com")
Advertisements