# Scripting Web Tests

with Watir and Ruby

Workbook / Labs / 4. Verifying Behavior

## Lab 4: Verifying Behavior

You’ve written some scripts that demonstrate how to automate a browser. But they aren’t really tests. Because they don’t really check the results. Now it is time to take care of that.

One common technique is to use the “text” method. This method will return the text contents of the specified page element. In this lab we also use the “should” methods that are packaged with Rspec. This automates validation.

    require 'spec'
    browser.div(:id, 'banner').text.should == 'Pragmatic Bookshelf'

Add validations to your scripts from the previous exercise.

1. Add Book to Cart. Verify that the browser indicates that the book was successfully added to the cart.
2. Purchase Books. Verify that the browser indicates that the books were ordered.

Now that your scripts have validations, you need to reset the state of the application before each test. Specifically, you will need to ensure that your tests begin with an empty cart. The easiest way to do this is to go to the empty cart url.

    browser.goto('http://localhost:3000/store/empty_cart')

Force your tests to fail by seeding them with incorrect expected results. Observe that the script terminates upon the first failure and an error message is printed. The exit code is 1 (instead of 0), also indicating that the script failed. In the next lab we will learn a better way to capture and report test failures such as these.

### Verifying Tables (optional)

Tables and table cells can be referenced like other elements. In addition, table cells can be referenced relative to their position in a table.

In the case of the Depot application, the tables don’t have names or id’s and must be referenced by index.

    browser.table(:index, 1)

Since there is no more than one table on a given Depot page, this does not represent a problem for us. Table rows and cells can be referenced by row and column index. For example, the second cell in the third row can be referenced thus:

    browser.table(:index, 1)[3][2]

Like other elements, cells have a text method that returns the text in the cell.

    browser.table(:index, 1)[3][2].text

If you wish, you can add verification of the information in the tables to your scripts.

### Completion

At the completion of this exercise you should know how to:

- Verify the contents of a div or table cell.
- Use “should” commands from Rspec.
- Understand how test failures will be reported.

You can compare your scripts to sample solutions for this lab