Watir Recipes Sample

Embed Size (px)

DESCRIPTION

test

Citation preview

  • Watir RecipesThe problem solving guide to Watir

    Zhimin ZhanThis book is for sale at http://leanpub.com/watir_recipes

    This version was published on 2014-03-26

    This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishingprocess. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools andmany iterations to get reader feedback, pivot until you have the right book and build traction onceyou do.

    2013 - 2014 Zhimin Zhan

  • To Xindi for your understanding and support!

  • Contents

    Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iWho should read this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iiHow to read this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iiGet recipe test scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iiSend Me Feedback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii

    1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Watir and its variants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1RSpec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Run recipe scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

    2 Hyperlink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Start browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Click a link by label text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Click Nth link with exact same label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Verify a link present or not? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Getting link data attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Test links open a new browser window . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

    3 Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Click a button by label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Click a button by ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Click a button by name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Click an image button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Assert a button present . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Assert a button enabled or disabled? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

    4 TextField and TextArea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Enter text into a text field by name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Enter text into a text field by ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Enter text into a password field . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Clear a text field . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Enter text into a multi-line text area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Assert value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

  • CONTENTS

    Focus on a control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Set a value to a read-only or disabled text field . . . . . . . . . . . . . . . . . . . . . . . . 17

  • PrefaceTwo years ago, I presented at a software testing conference overseas. I was really impressed withtesters desire to automated test web applications. The audience surrounded me with variousquestions after my sessions. The following year, I was invited to present at the same conference,the enthusiastic atmosphere was the same, if not stronger (Test Automation and Web applicationtesting were listed as No.1 and No.2 of top 10 hot topics in the audience survey). I did recognize acouple of familiar faces.When I asked them casually how test automationwas going in their projects.They either said not so good or shied away. This puzzle was on my mind on the trip back.Not long after, I was coaching test automation on a client site, and the only tester there wascompletely new to test automation, but she was quite keen to learn. At the end of the day, shedid well, developed a dozen of automated test cases. I then asked her: After you read my book orattended one of my presentations, would you go back to try test automation in your project. Sheanswered quickly No. I would believe in it, but I will not have the confidence to give a try at work.Suddenly, I figured out the answer.Everyone in the field understands that, manual testing is the bottleneck of software development,and performing regression testing is practically impossible formany projects. As a result, long releasecycles and poor quality products. Few testers consider manual testing exciting and fun (I can tell youthat test automation is). Motivated managers/testers want to change that. However, the knowledgethey gain from books or presentations would not give them enough confidence and courage to takeaction.Therefore, test automation is rarely done successfully. From executives perspective, they usuallyare more cautious after having seen several failed attempts on test automation. Practically, for amotivated project managers/test team leaders who plan to introduce test automation, they need tohave a secret trial. They usually develop some key tests by following the start guide. However, theysoon will face some challenges such as: how to click this dynamic generated hyperlink?, how to dohandle base authentication pop up?, , and stuck there.This is the motive for me to write this book: to help these motivated test professionals.This book contains over 100 recipes for testing web applications with Watir. If you have read myPractical Web Test Automation, you have probably known my style: being practical. I will let thetest scripts do the most talking. These recipe test scripts are live, as I have created the target website and offline test web pages. By using the the book, recipe test scripts and the test pages (or sites),you can

    1. Identify your issuehttps://leanpub.com/practical_web_test_automation

  • Preface ii

    2. Find the recipe3. Run the test case4. See test execution in your browser

    Who should read this bookTesters or programmers who are writing (or want to learn) Watir automated tests to test webapplications.

    How to read this bookUsually, a recipe book is a reference book. Readers can go directly to the part that interests them.For example, if you are testing a multiple select list and dont know how, you can look up in theTable of Contents, then go to chapter 7. As software testing is so pragmatic, testers can use thisbook to learn test automation in Watir too, by going through recipe one by one. I have arranged therecipes according to the levels of complexity.

    Get recipe test scriptsTo help readers learn more effectively, this book has a dedicated site which contains the recipe testscripts and related resources. Those test scripts with test pages/sites are packaged for easy and quickexecution, which accounts for a large percentage of effort for this book (and made this book unique).All recipe test scripts are Watir 5 compliant, and run on Internet Explorer 9 on Windows 7. I plan tokeep the test scripts updated with the latest stable Watir version.

    Send Me FeedbackI would appreciate hearing from you. Comments, suggestions, errors in the book and test scripts areall welcome. You can submit your feedback on the book site.Zhimin ZhanApril 2013

    http://zhimin.com/books/watir-recipes

  • 1 IntroductionWatir (Web Application Testing in Ruby) is a free and open source library for automated testing webapplications in Internet Explorer. I think it is a fair assumption that you have already known aboutWatir, simply based on the fact that you picked up this book (or opened it in your eBook reader).

    Watir and its variantsThe r in Watir stands for Ruby, a free and powerful dynamic language with concise and elegantsyntax. In other words,Watir test scripts are Ruby scripts. Inspired byWatirs success, there are cloneframeworks in .NET and Java platforms: WatiN and Watij respectively. In my view, these two testframeworks are of not much value. There is a clear reason why creators of Watir included Ruby inthe name: simply because of its importance (the hugely popular web framework Ruby on Rails alsoincludes Ruby in its name). The concise, intuitiveness and flexibility of Ruby programming languagemakes it an ideal choice for automated test scripts. By the way, Ruby is a scripting language, Javaand C# are not.

    Watir-WebDriverWatir-WebDriver isWebDriver-backedWatir, i.e.,Watir syntax test scripts with Selenium-WebDriveras the engine underneath. One major benefit is that Watir-WebDriver test scripts can run on Firefox,Chrome and IE on multiple platforms including Windows, Linux and Mac.In theory, switching Watir to Watir-WebDriver is as simple as changing

    require 'watir'browser = Watir::Browser.new# ....

    to

    require 'watir-webdriver'browser = Watir::Browser.new# ....

    Personally, I like to use classic Watir when Internet Explorer is one of the target browsers. Watir isfast, stable and easy to attach test execution to the existing browser windows (will cover this topiclater).If you are a Mac/Linux User, the recipes are still applicable, just the framework is Watir-WebDriverinstead of Watir. I will cover Watir-WebDriver more specifically in Chapter 16.

  • Introduction 2

    RSpecWatir drives browsers. However, to make the effective use of Watir scripts for testing, we need to putthem in a test framework which defines test structures and provides assertions (to perform checksin test scripts). Typical choices are:

    xUnit Unit Test Frameworks such as JUnit, NUnit. Behaviour Driven Frameworks such as RSpec, Cucumber.

    In this book, I mainly use RSpec, the de facto Behaviour Driven Development (BDD) framework forRuby.

    describe "A grouped collection of test case " dobefore(:all) do

    @browser = Watir::Browser.newend

    after(:all) dobrowser.close unless debugging?end

    before(:each) dobrowser.goto(site_url)end

    it "Check page title" dobrowser.title.should == "Watir Recipes"browser.title.include?("Watir").should be_truebrowser.title.include?("Watir").should_not be_falsebrowser.title.should_not include("Selenium")end

    # more test cases ...

    end

    Run recipe scriptsTest scripts for all recipes can be downloaded from the book site. They are all in ready-to-run state.I include the target web pages/sites as well as Watir test scripts. There are two kinds of target webpages: local HTML files and web pages on a live site.

  • Introduction 3

    Enable IE to allow executing JavaScripts locallyRunning tests against Local HTML files is fast and reliable (no need for Internet Access), and readerscan add or modify web pages to try out new test operations. However, when opening local web pagescontaining JavaScripts, you may see the security warning Internet Explorer restricted this webpagefrom running scripts or ActiveX controls.

    This prevents execution of some JavaScripts in the local files. As a result, it affects the test execution.To disable this warning (to be sure, you may want to inspect the only jquery-1.4.2.min.js and inlinejavascript in the sample HTML files), open Internet Options in Internet Explorer. Go to Advancedtab, scroll down to the security section there should be an option Allow active content to run infiles on My Computer. Enabling this should allow them to run.

    Run tests in TestWise Community EditionTestWise is a functional testing Integration Development Environment (IDE) that supports Watirand Selenium. TestWise community edition is free.In this book, I refer to TestWise when editing or executing test scripts. If youve already had preferredtesting tools/IDE, go for it. It shall not affect your learning this book or running recipe test scripts.Installation of TestWise is easy. It only takes a couple of minutes (unless your Internet speed is veryslow) to download and install. And TestWise is the only software you need to use while learningwith this book (or developing Watir test scripts for your work).To open recipe test scripts, close currently opened project if there is one. Select menu File -> OpenProject,

  • Introduction 4

    select the project file watir-recipes-sources\watir-recipes-samples.tpr

    The TestWise window shall look as below:

    Find the test case

    You can locate the recipe either by following the chapters or searching by names. There are over 100test cases in one test project. Here is the quickest way to find the one you want in TestWise.Select menu Navigation -> Go to Test Case...

    A pop up window appears with all test cases in the project listed for your selection. The findingstarts as you type.

  • Introduction 5

    Within a test script file (opened in the editor), press Ctrl+F12 to show and select test cases inside it.

    Run individual test case

    Move caret to a line within a test case (between it "..." do and end). Right mouse click and selectRun .

    The below is a screenshot of execution panel when one test case failed,

    Run all test cases in a test script file

    You can also run all test cases in currently opened test script file by clicking the blue triangle buttonon the tool bar.

  • Introduction 6

    The below is a screenshot of the execution panel when all test cases in a test script file passed,

    Run tests from command lineOne advantage of open-source test frameworks, such as Watir and Selenium, is FREEDOM. You canedit the test scripts in any text editor and run them from a command line.You need to install Ruby first, then install RSpec and preferred web test driver and library (knownas Gem in Ruby). Basic steps are:

    install Ruby interpreterWindow installer: http://rubyinstaller.org, Linux/Mac: included or compile from source

    install RSpec> gem install rspec

    install test framework gem(s)> gem install watiror> gem install watir-webdriver

    For windows users, you may simply download and install the free pre-packaged RubyShell (basedon Ruby Windows Installer) at http://testwisely.com/en/testwise/downloads.Once the installation (it takes about 1 minute) is complete, we can run a RSpec test from thecommand line. You need to have some knowledge of typing commands in a console (Unix) orcommand window.To run test cases in a test script file (named google_spec.rb), enter command

    > rspec google_spec.rb

    Run multiple test script files in one go:http://testwisely.com/en/testwise/downloads

  • Introduction 7

    > rspec first_spec.rb second_test.rb

    Run individual test case in a test script file, supply a line number in chosen test case range.

    > rspec -l30 google_spec.rb

    To generate a test report (HTML) after test execution:

    > rspec -fh google_spec.html > test_report.html

    The command syntax is the same for Mac OS X and Linux platforms.

  • 2 HyperlinkHyperlinks (or links) are fundamental elements of web pages. As a matter of fact, it is hyperlinksthat makes the World Wide Web possible. A sample link is provided below, along with the HTMLsource.

    HTML SourceRecommend Watir

    Start browserTesting web sites starts with a browser.browser = Watir::Browser.newbrowser.start("http://testwisely.com/demo")

    You can also use goto instead of start.browser = Watir::Browser.newbrowser.goto("http://testwisely.com/en/testwise")

    Click a link by label textUsing label text is probably the most direct way to click a link in Watir, as it is what we see on thepage.browser.link(:text, "Recommend Watir").click

    Click a link by IDUsing IDs is the easiest way (and probably the safest too, as it should be unique if the page is W3CHTML conformed) to identify web controls if the programmers assign IDs to them. In contract toreferring to the link label texts, test scripts that use IDs are less prone to application changes (eg.an application designer or developer may decide to change the label, but would not likely need tochange the ID).

    http://www.w3.org/TR/WCAG20-TECHS/H93.html

  • Hyperlink 9

    browser.link(:id, "sign_in_link").click

    Furthermore, if you are testing a web site with multiple languages, using IDs is probably the onlyfeasible option. You do not want to write test scripts like below:

    if is_chinese? # a helper function determines the localebrowser.link(:text, "").clickelsif is_italian?

    browser.link(:text, "Accedi").clickelse

    browser.link(:text, "Sign in").clickend

    Click a link by partial label textWatir allows you to identify a hyperlink control with a partial text. This can be quite useful whenthe label text is dynamically generated. In other words, the label text on one web page might bedifferent on your next visit. We might be able to use the common text shared by these dynamicallygenerated link labels to identify these links.

    browser.link(:text, /partial/i).click #contains 'partial', case insensitivebrowser.text.should include("This is partial link page")

    Here we use the regular expression in (//), a powerful pattern matching language. If you arenot familiar with the regular expression, dont feel intimidated. The use of regular expression inautomated test scripts is very minimal. Online regular expression testers such as Rubular will makeit easy to learn what you need.

    By URLbrowser.link(:url, "http://testwisely.com/demo").click

    Please note :url only works for Watir Classic (not watir-webdriver).http://rubular.com/

  • Hyperlink 10

    Click Nth link with exact same labelIt is not uncommon that there are more than one link with exactly the same label. By default, Watirwill choose the first one. What if you want to click the second or Nth one?The web page below contains three Show Answer links,

    To click the second one,

    browser.link(:text => "Show Answer", :index => 1).click

    The :index tells Watir which element in appearing order to select, Watir (since version 2.0) uses0-based indexing, i.e. the first one is 0.

    browser.link(:text, "Show Answer").click # this will click first linkbrowser.link(:text => "Show Answer", :index => 0).click # still first link

    If there are multiple links with the same label that have different attribute values, such as class, wecould use the attribute to narrow down the choice, such as

    browser.link(:text => "Same link", :class => "small").click

    Verify a link present or not?browser.link(:text, "Sign in").present?.should be_truebrowser.link(:id, "sign_out_link").present?.should_not be_true

    Besides present?, you may use visible? to check whether an element is visible on the page. Watir-Classic also has another similar method exists?.

    browser.link(:text, "Hide").clickbrowser.link(:text, "Recommend Watir").present?.should be_falsebrowser.link(:text, "Recommend Watir").visible?.should be_false

    Getting link data attributesOnce a control is identified, we can get its other attributes of the element. This is generally applicableto most of the controls.

  • Hyperlink 11

    browser.link(:text, "Recommend Watir").href.should == "http://testwisely.com/demo"browser.link(:text, "Recommend Watir").id.should == "recommend_watir_link"browser.link(:id, "recommend_watir_link").text.should == "Recommend Watir"browser.link(:id, "recommend_watir_link").tag_name.should == "a"

    Also you can get the value of custom attributes of this element and its inline CSS style.

    browser.link(:id, "recommend_watir_link").attribute_value("data-id").should == "1\23"

    Special note on the style attribute, which is different between Watr-Classic and Watir-WebDriver.Watir-Classic

    browser.link(:id, "recommend_watir_link").style.should == "FONT-SIZE: 14px"# Please note using attribute_value("style") won't work in Watir-Classic

    Watir-WebDriver

    browser.link(:id, "recommend_watir_link").attribute_value("style").should == "fon\t-size: 14px;"

    Test links open a new browser windowClicking the link below will open the linked URL in a new browser window or tab.

    Open new window

    While we could use Watir attach method (see chapter 10) to find the new browser window, it willbe easier to perform all testing within one browser window. Here is how:

    current_url = browser.urlnew_window_url = browser.link(:text, "Open new window").hrefbrowser.goto(new_window_url)# ... testing on new sitebrowser.text_field(:name, "name").set "sometext"browser.goto(current_url) # back

    In this test script, we use a local variable (a programming term) current_url to store the currentURL.

  • 3 ButtonThere are mainly two types of buttons: standard buttons and submit/reset buttons in a form. Theyboth work the same way in Watir.

    HTML Source

    \Choose Watir

    Username:

    Please note that some controls look like buttons, but are actually hyperlinks by CSS styling.

    Click a button by labelbrowser.button(:value, "Choose Watir").click

    For an input button (in a HTML input tag) in a form, the label shown on the button is the valueattribute which might contain extra spaces or invisible characters. Watir expects an exact matchwhen searching an input control by value.

  • Button 13

    # the below will fail# browser.button(:value, "Space After").clickbrowser.button(:value, "Space After ").click

    Click a button by IDAs always, a better way to identify a button is to use IDs. This applies to all controls.

    browser.button(:id, "choose_watir_btn").click

    Click a button by nameIn an input button, we can use a new generic attribute to locate a control: name.

    browser.button(:name, "choose_watir").click

    Click an image buttonThere is also another type of button: an image that works as a submit button in a form.

    Besides using ID, the button can be identified by using :src attribute.

    browser.button(:src, /go/).click

    Assert a button presentJust like hyperlinks, we can use present? to check whether a control is present on a web page. Thischeck applies to most of the web controls in Watir.

  • Button 14

    browser.button(:text, "Choose Watir").present?.should be_truebrowser.button(:text, "Choose Selenium").present?.should_not be_truebrowser.button(:id, "choose_watir_btn").present?.should be_true

    Assert a button enabled or disabled?A web control can be in a disabled state. A disabled buttons is un-clickable, and it is displayeddifferently.

    Normally enabling or disabling buttons (or other web controls) are triggered by JavaScripts.

    browser.button(:text, "Choose Watir").enabled?.should be_truebrowser.link(:text, "Disable").clicksleep 0.5browser.button(:id, "choose_watir_btn").enabled?.should be_falsebrowser.link(:text, "Enable").clicksleep 1browser.button(:id, "choose_watir_btn").enabled?.should be_true

  • 4 TextField and TextAreaText fields are commonly used in a form to pass user entered text data to a server. There are twovariants: password fields and text areas. The characters in password fields are masked (shown asasterisks or circles). Text areas allows multiple line texts.

    HTML Source

    Username: Password: Comments:

    Enter text into a text field by namebrowser.text_field(:name, "username").set("new value")

    The name attribute is the identification used by the programmers to process the data, and it appliesto all the web controls in a standard web form.

    Enter text into a text field by IDbrowser.text_field(:id, "user").send_keys("tester1")

    In above test scripts, I use the send_keys here. For common use, testers might treat send_keys thesame as set, but they are different. set clears the text field before populating the text while send_-keys just send keys into text boxes. See the example below:

  • TextField and TextArea 16

    browser.text_field(:id, "user").set("userone")browser.text_field(:id, "user").set("usertwo")# Now value of this text box is 'usertwo'browser.text_field(:id, "user").clearbrowser.text_field(:id, "user").send_keys("userone")browser.text_field(:id, "user").send_keys("usertwo")# The value in text field might have different values# depends on your IE browser version, the value can be#'useroneusertwo', 'userone', 'useroneo' (don't ask me why)

    Enter text into a password fieldInWatir, password text fields are treated as normal text fields, except that the entered text is masked.

    browser.text_field(:id, "pass").set("testisfun")

    HTML5 introduces an e-mail address input control (input type=email), it is also treated as a normalinput text field.

    Clear a text fieldbrowser.text_field(:id, "user").set("testwisely")browser.text_field(:name, "username").clear

    Enter text into a multi-line text areaWatir treats text areas the same as text fields.

    browser.text_field(:id, "comments").set("Automated testing is\r\nFun!")

    The \r\n represents a new line.

    Assert value

  • TextField and TextArea 17

    browser.text_field(:id, "user").set("testwisely")browser.text_field(:id, "user").value.should == "testwisely"

    Focus on a controlOnce we identify a control in Watir, we can set the focus on it.browser.text_field(:id, "user").focus

    Set a value to a read-only or disabled text fieldRead only and disabled text fields are not editable on the page, and they are shown differently inthe browser (typically grayed out).Readonly text field: Disabled text field:

    If a text box is set to be read-only, the following test step wont work.browser.text_field(:name, "readonly_text").set("new value")

    Watir-ClassicHere is a workaround:browser.text_field(:name, "readonly_text").value = "anyuse" # OKbrowser.text_field(:name, "disabled_text").value = "bypass" # OK

    Watir-WebDriverThe above method value = does not work for Watir-WebDriver. But there is another workaround:browser.execute_script("$('#readonly_text').val('bypass');")browser.text_field(:name, "readonly_text").value.should == "bypass"browser.execute_script("$('#disabled_text').val('anyuse');")browser.text_field(:name, "disabled_text").value.should == "anyuse"

    The below is a screenshot of a disabled and read-only text fields that were injected with two valuesby the above Watir test script.

    Table of ContentsPrefaceWho should read this bookHow to read this bookGet recipe test scriptsSend Me Feedback

    IntroductionWatir and its variantsRSpecRun recipe scripts

    HyperlinkStart browserClick a link by label textClick Nth link with exact same labelVerify a link present or not?Getting link data attributesTest links open a new browser window

    ButtonClick a button by labelClick a button by IDClick a button by nameClick an image buttonAssert a button presentAssert a button enabled or disabled?

    TextField and TextAreaEnter text into a text field by nameEnter text into a text field by IDEnter text into a password fieldClear a text fieldEnter text into a multi-line text areaAssert valueFocus on a controlSet a value to a read-only or disabled text field