Cross Browser Automation Testing Using Watir

muthuraja

Muthu Raja

Posted on January 22, 2019

Cross Browser Automation Testing Using Watir

We are living in an era where software development demands for automation. Software development methodologies such as RAD(Rapid Application Development), Agile and so on requires you to incorporate automation testing as a part of your release cycle. There exist numerous test automation frameworks used for automation testing. Today, I will be picking up Watir an open source, selenium-based web driver used for browser automation. Cross browser automation testing using Watir would help you to ensure a good rendering user interface of your web app. If you are a beginner to automation testing and are unaware of basics then don’t worry as I will also be talking about browser automation, [cross browser automation], parallel testing and what makes Watir special than other several tools and libraries. Without further ado, here we go!

What Is Browser Automation?

Browsers have become indispensable to our daily basis productivity. We explore, learn, shop, invest and do a lot more with browsers. There are times when we feel the need for browsers to automate our repetitive tasks. Imagine how cool that would be? Is it possible? Yes, any task you perform in browsers is automatable.

Let us take some considerations based on basic practical scenarios. You can use browser automation if:

  • You need to fill a lot of forms for data entry.
  • You need to generate a report from web portal on daily basis and send email to the team.
  • You navigate to a specific website and upvote on daily basis for a particular candidate on a reality TV show.

In the software industry, testing a web app can demand for a huge investment of time, resources and money. Testing a web app to check how well it renders could be very strenuous if relied upon manual testing alone. The manual testing ensures your application is functioning as expected, based on client requirements and expectations. Browser automation comes to rescue so we could avoid repeated manual testing, regression test cases, and obtaining early feedbacks along with reduced effort.

What Is Cross Browser Automation Testing?

Now, there are thousands of browsers available on the internet and your website may render in a unique manner on every browser or browser version. It could be very complex to test your website across every single one of them. Cross browser automation testing is to verify your application renders seamlessly across different browsers and its combination version. This is primarily performed to check cross browser compatibility of your shippable application’s functionality on combinations of the various OS running separate browsers like Google Chrome, Mozilla Firefox, Edge, IE, Opera, Safari, Yandex and many more.

To run all browsers and its combination of version is time-consuming. For eg., your client asks to perform a regular basis cross browser compatibility check across 5 versions of latest and 5 versions of legacy Chrome, Safari, Firefox and Edge browser that would bring a total number of browser combinations to be of 40 completely different distinctive browsers and its version for one test case. Consider how overwhelmingly time-consuming and tedious it could be to perform a cross browser compatibility check over all those browser combinations and provide sign off, that needed positively proper planning, huge investments in QA resource, handling challenges, time and cost. To deal with this issue, Cross Browser automation testing for parallel test sessions is the solution.

What Is Cross Browser Parallel Test Automation?

Cross Browser Parallel testing is performed to run a single test across multiple browser combinations, simultaneously. This is a very practical and powerful consumption scenario of automation testing. Cross browser parallel test automation allows you to scale back execution time while not compromising with coverage of your check and leading to faster rotation of your test results.

What Is Watir?

Watir is an open source Ruby Libraries which helps to achieve cross browser automation testing. Watir supports Ruby which is object oriented language and typically it’s simpler and faster than other languages. The good thing about Watir is, it supports any web application irrespective of the technology used to develop that application.

Why Watir?

  • It’s a free open source tool belonging to a family of Ruby.
  • It supports headless browser execution.
  • It supports page object design pattern.
  • It supports Cucumber Integration.
  • Tests can be maintained simple and flexible.
  • It supports your web app no matter what technology used to develop your app.
  • It supports multiple browsers on different platforms.
  • It is lightweight and easy to use.
  • It supports execution in Cloud through cloud based cross browser automation testing tools like LambdaTest.

In this article, we will take a look on how to setup test automation environment for Watir with RubyMine IDE and then go ahead with the sample script. I would also show how to run the script and see the failure in RubyMine. Let’s dive right in.

Getting Started With Cross Browser Automation Testing Using Watir

Here are the prerequisite required for performing cross browser automation testing using Watir on Windows:

  • RubyInstaller
  • Watir
  • RubyMine IDE

The RubyInstaller is must because Watir supports Ruby code, so this installation is very important before we proceed with Automation.

Setting Up Automation Environment

This section has detailed steps explaining how to setup automation environment for performing cross browser automation testing using Watir through Windows.

Step 1: Installation of Ruby:

Navigate to Official Ruby Installer page here.

Click on Latest version With DEVKIT to download. Select your OS architecture type, for e.g., I select (X64) 64 bit operating system.
IMAGE

After download, right click on installer and run as administrator in Windows machine.
IMAGE

The setup window popups to accept license agreement, you need to accept this and move next.

IMAGE

I would recommend selecting all checkboxes and clicking install button to proceed further.

IMAGE

The below progress bar indicates the install is in-progress, which takes few minutes time to install ruby.

IMAGE

After installation is complete, the following window will popup to install updated component. This is optional either you can leave it by closing the window or hit “Enter” button to update all components.

IMAGE

Open command prompt in windows and enter the following command:

  • ruby-version The installation version of Ruby version is displayed in the command prompt, which indicates Ruby installer is success. image

To verify once again the installation is success and Ruby programs works fine. Enter the following commands:

  • irb

irb or IRB stands for Interactive Ruby Shell which is a REPL(read-eval print loop) for programming in the object-oriented scripting language Ruby.

I will write a simple code that will put “lambdatest.com” to print it.

image

Step 2: Installation of Watir:

Installation of Watir is very simple. As I mentioned in the above section to verify Watir, you must first installed Ruby. To install, supply the below gem command:

  • gem install watir

gem indicates RubyGems that is a package manager for the Ruby programming which provides a standard format of disturbing Ruby libraries.

image

Step 3: Installation of RubyMine IDE:

RubyMine is an IDE(Integrated Development Environment) that helps you to write, debug and testing code for your application. Ruby also support multiple OS like Windows, MacOS and Linux etc.

Note: RubyMine comes up with Free 30- day Trial license.

To download the RubyMine, click here.

Click on the following button, which will download in your machine.

Right click on installer and run as Administrator, which pop ups the following windows.

Click next and continue till the installation is complete and launch RubyMine

image

Keep default with existing plugins and click Next until you see the below window.

Click “Create New Project”

image

Enter project name and select “Ruby SDK” which will be available if you install Ruby Installer.

image

Right click on created project and create a new directory called “testsuites”

image

Create a subdirectory called “resources” under testsuites and drop “chromedriver.exe”

To run browser based automation, chromedriver is required which is a separate executable that WebDriver uses to control chrome. Similarly we have different driver for each browser for eg., geckodriver for Mozila firefox, edge driver for Microsoft Edge browsers etc.,

To download chromedriver, please visit here.

Writing Code for Sample Test

To write code in RubyMine is very simple.

Right click on testsuites and select “TestUnit Test Template”
image

Enter file name “my_script.rb” in filename and click ok button.

On the RubyMine window that you are observing now, write the following code.

CODE (Self Explanatory):

require 'watir'
require 'selenium-webdriver'
require 'test/unit'
require 'test/unit/ui/console/testrunner'
 
class Sampletest < Test::Unit::TestCase
 
  "" "
    LambdaTest Watir automation sample example
    Configuration
    ----------
    Download Chrome driver from http://chromedriver.chromium.org/downloads and drop into your resource folder
 
    Result
    -------
    Execute Watir Automation Tests on LambdaTest website
    " ""
 
  def setup
    "" "
        Setup local driver
        Params
        ----------
        platform : Windows 10
        browserName : Supported platform - (chrome in your local box)
 
        Result
        -------
        " ""
    #Initializing chrome driver
    Selenium::WebDriver::Chrome.driver_path = "resources/chromedriver.exe"
    @browser = Watir::Browser.new
  end
 
  def test_verifyLambdapage()
      #Navigate to lambdatest.com website
      @browser.goto 'https://lambdatest.com'
      #Maximize the browser window
      @browser.window.maximize
      #Initializing element with Link text
      ele_starttestingbutton = @browser.link(:text => "START TESTING")
      #Perform click operation
      ele_starttestingbutton.click
      #printing page title
      puts("Actual Page title is: "+@browser.title)
      #Verifying actual and expected title of the page. This examples I intentionally fail the test by adding spell error
      assert_equal("Signup - LambdaTest App | Free Cross Browser Testing To0ol", @browser.title)
  end
 
 
  def teardown
    #Quit the browser
    @browser.quit
  end
end

Right click on the script and select “Run” in IDE to see test results and what is the output

The above test script I intentionally fail to verify results in terms of comparing actual vs. expected page title.

The below snapshot explain the test gets failed and the difference is highlighted in colour.

Using Local WebDriver To Perform Cross Browser Automation Testing Using Watir

Code Explanation:

def setup
  "" "
      Setup local driver
      Params
      ----------
      platform : Windows 10
      browserName : Supported platform - (chrome in your local box)
 
      Result
      -------
      " ""
  #Initializing chrome driver
  Selenium::WebDriver::Chrome.driver_path = "resources/chromedriver.exe"
  @browser = Watir::Browser.new
end
def teardown
  #Quit the browser
  @browser.quit
end

In TestUnit template,the IDE automatically create def setup and teardown. These methods actually run before and after test.

Setup: This method is precondition to run the test, you may setup something like initialize browser or any test data setup and

Teardown: This method is after your test run, you may close.quit the browser or delete the data in database etc.,

Selenium::WebDriver::Chrome.driver_path = "resources/chromedriver.exe"
    @browser = Watir::Browser.new

The above code is initializing the chrome driver and create new instance and assign object reference to variable browser.

The next line of code is typical Watir script which actually steps of:

Note: The method name start with “test_” is mandatory which Unit Test Runner actually realize this is test method.

  • Navigate to browser
  • Maximize the Window
  • Click on “Start Testing” button in lambdatest.com
  • Prints Current Page Title
  • Finally verifying whether expected vs actual title
def test_verifyLambdapage()
    #Navigate to lambdatest.com website
    @browser.goto 'https://lambdatest.com'
    #Maximize the browser window
    @browser.window.maximize
    #Initializing element with Link text
    ele_starttestingbutton = @browser.link(:text => "START TESTING")
    #Perform click operation
    ele_starttestingbutton.click
    #printing page title
    puts("Actual Page title is: "+@browser.title)
    #Verifying actual and expected title of the page. This examples I intentionally fail the test by adding spell error
    assert_equal("Signup - LambdaTest App | Free Cross Browser Testing To0ol", @browser.title)
end

Using Remote WebDriver At LambdaTest To Perform Cross Browser Automation Testing Using Watir

The drawback of executing cross browser automation testing using Watir for Local WebDriver is that you only get to test your script over the browsers installed in your local machine. However, it isn’t feasible to install thousands of browsers on your system. This is why, cloud is a more preferred platform to perform cross browser automation testing. Cloud provider offers to run your test scripts with support of Selenium grid. The great factor is, you don’t have to be compelled to maintain or any setup needed, all you wish to try and do is slightly tweak your code to support selenium grid. I’m going to explain how to tweak your same code to run test in Lambdatest. LambdaTest provides an extensive Selenium grid offering more than 2000 browsers to test from. You can even perform cross browser automation testing of your locally hosted web apps using their SSH tunnel. Let me show how you can leverage LambdaTest for browser automation using Watir.

Run Single Instance In LambdaTest Using Watir

LambdaTest provide cross browser parallel test in terms of running your cross browser automation testing scripts parallely to reduce great execution efforts. We will take a look in detail below regarding how to run simple test and how to run same set of test with different browsers in LambdaTest.

I’m using same script which I connected in my previous section in above, except the subsequent changes in setup techniques as mentioned within the below snapshot.

def setup
  "" "
      Setup remote driver
      Params
      ----------
      platform : Supported platform - (Windows 10, Windows 8.1, Windows 8, Windows 7,  macOS High Sierra, macOS Sierra, OS X El Capitan, OS X Yosemite, OS X Mavericks)
      browserName : Supported platform - (chrome, firefox, Internet Explorer, MicrosoftEdge)
      version :  Supported list of version can be found at https://www.lambdatest.com/capabilities-generator/
 
      Result
      -------
      " ""
  username = "USER_NAME"
  accessToken = "PASSWORD"
  gridUrl = "beta-hub.lambdatest.com/wd/hub"
  caps = Selenium::WebDriver::Remote::Capabilities.new
  caps[:browserName] = "chrome"
  caps[:version] = "67.0"
  caps[:platform] = "win10"
  caps[:name] = "LambdaTest Watir Signup Page Name verification"
  caps[:build] = "LambdaTest Watir Signup Page Name verification"
  caps[:network] = true
  caps[:visual] = true
  caps[:video] = true
  caps[:console] = true
  puts(caps)
  # URL: https://{username}:{accessToken}@beta-hub.lambdatest.com/wd/hub
  @browser = Watir::Browser.new(
      :remote,
      :url => "https://" + username + ":" + accessToken + "@" + gridUrl,
      :desired_capabilities => caps)
end

LambdaTest supports Selenium grid, so to run your test in LambdaTest you need to initialize remote webdriver and point where your Selenium hub or server is running.

Template of Selenium Grid URL to run in LambdaTest is:

https://{username}:{accessToken}@beta-hub.lamdatest.com/wd/hub

User Name:You can find it in LambdaTest dashboard page.

Access Token: You can find it on your profile page. In case no token, feel free to click on generate Access Token button.

Grid URL: beta-hub.lamdatest.com where your selenium grid is running.

The other important feature is the Capabilities Generator: To run your test suites in LambdaTest Selenium grid you must set the desired capabilities for example, which browser, which operating system and so on basic configurations that you want to test on.

You can configure which browser, platform etc., and finally it generates a code based upon your selections. Below is the result for Ruby language.
capability-generator

Capabilities Generator also supports Java, JavaScript, C#, Python, and PHP.

That’s all you need to run your tests successfully at LambdaTest for performing cross browser automation testing using Watir.

Run Cross Browser Parallel Testing With Watir Using LambdaTest

So far you have got seen a way to run single instance in LambdaTest, this section is detail about regarding a way to run same set of test with different totally browsers in LambdaTest. This section would assist you to grasp a way to generic code run different browser in Watir.

The below code would facilitate to realize the parallel execution:

require 'watir'
require 'selenium-webdriver'
require 'test/unit'

class DumTest < Test::Unit::TestCase

  "" "
    LambdaTest Watir automation sample example with Cross Browsers
    Configuration
    ----------
    username: Username can be found at automation dashboard or profile page
    accessToken:  AccessToken can be generated from automation dashboard or profile section

    Result
    -------
    Execute Watir Automation Tests on LambdaTest using Selenium Grid
    " ""

 #Confuring Multiple browser and its versions
  BROWSERS = {firefox: '64',
              chrome: '67'}


  def setup (browser_name, browser_version)
    username = "USER_NAME"
    accessToken = "PASSWORD"
    gridUrl = "beta-hub.lambdatest.com/wd/hub"

    #Initializing Capabilities
    caps = Selenium::WebDriver::Remote::Capabilities.new
    caps[:browserName] = browser_name
    caps[:version] = browser_version
    caps[:platform] = "win10"
    caps[:name] = "LambdaTest Watir Signup Page Name verification"
    caps[:build] = "LambdaTest Watir Signup Page Name verification"
    caps[:network] = true
    caps[:visual] = true
    caps[:video] = true
    caps[:console] = true

    puts(caps)
    # URL: https://{username}:{accessToken}@beta-hub.lambdatest.com/wd/hub
    Thread.current[:@driver] = Watir::Browser.new(
        :remote,
        :url => "https://" + username + ":" + accessToken + "@" + gridUrl,
        :desired_capabilities => caps)
  end


  #Using Thread to achieve parallel execution
  def runthreads
    threads = []
    BROWSERS.each_pair do |browser, browser_version|
      threads << Thread.new do
        setup(browser, browser_version)
        yield
        teardown
      end
    end
    threads.each {|thread| thread.join}
  end


  # Called after every test method runs. Can be used to tear
  # down fixture information.

  def teardown
    Thread.current[:@driver].quit
  end
end

#Test Runner
#Instantiate test method and use threads to run paralle execution
mytest = DumTest.new(self)
mytest.runthreads do
  Thread.current[:@driver].goto "https://lambdatest.com"
  Thread.current[:@driver].window.maximize
  Thread.current[:@driver].link(:text => "START TESTING").click
  if "Signup - LambdaTest App | Free Cross Browser Testing Tool" == Thread.current[:@driver].title
    puts("Test is passed")
  else
    puts("Test is failed")
  end
end


The logic is simple, used Thread concepts to run the same set of test scripts in parallel. The thread creates dynamic based on how many browsers and its version are added in BROWSERS variable.

I passed argument username, password in setup method for demo purpose but for more customization please embody multiple parameters and replace with capabilities.

Well, now you have your test results look in LambdaTest Cloud platform. Please take a look on below snapshot.

Kudos! We made it, with this you have successfully run your first script for cross browser automation testing using Watir at LamdaTest cloud platform.

LambdaTest offers great in-depth detail for every test. If you look at the screenshot below, you will be able to notice the environment details, status, start time, end time and many more information that is automatically represented. You would also find a video log of your test session and analytics related tab alongside, timeline.

That was all you need to know for getting started with cross browser automation using Watir at LambdaTest to perform UI test for your website or web-app. I would be interested to know your thoughts and feedbacks on this tutorial in the comment section. I would appreciate if you have got any questions for me. Happy Testing!

Original Source: lambdatest.com

💖 💪 🙅 🚩
muthuraja
Muthu Raja

Posted on January 22, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related