Using Modules to avoid structures repetition in Geb Test Pages

28 / Aug / 2012 by Gunpreet 1 comments

Using modules in Geb testing can help to avoid repetition of same code/ sections in Geb test pages. In this blog I want to talk about repeating data structures such as tables and how to avoid this repition by modelling them.In Geb testing if there is some content which is used in multiple pages then we can make its definition reusable by creating a module.They are similar to pages, but unlike pages they extend Module.

class SubmitButtonModule extends Module {
    static content = {
        button { $("input", type: "submit") }
    }
}

Page can use modules in following manner:

class LoginPage extends Page {
    static content = {
        myModule { module SubmitButtonModule }
    }
}

This module method is only available in content template definitions. The content is set as an instance of module. Now we can use this module in following manner:

Browser.drive {
    to LoginPage
    myModule.button.click()
}

Repeating Structures

A more interesting usage of modules which I used in my project is to deal with repeating sections that are present on one page, such as table rows. Consider the following HTML

<table>
    <tr>
        <th>Company Name</th><th>Location</th>
    </tr>
    <tr>
        <td>ABC Pvt Ltd</td><td>Banglore</td>
    </tr>
    <tr>
        <td>XYZ Pvt Ltd</td><td>Noida</td>
    </tr>
</table>

We can model this with the following

import geb.*

class CompanyPage extends Page {
    static content = {
        companyResult { index ->
            module CompanyTableRow, $("table tr", index + 1) // +1 is used to avoid header row
        }
    }
}
class CompanyTableRow extends Module {
    static content = {
         cell { i -> $("td", i) }
        companyName { cell(0).text() }
        location { cell(1).text() }
    }
}

We can now write code like…

assert companyResult(0).companyName == "ABC Pvt Ltd"
assert companyResult(1).location == "Noida"

I tried to explain with simple examples. We can use it with multi-level navigation structures as well.
Hope this will help you.
Gunpreet Bedi
gunpreet@intelligrape.com

https://twitter.com/gunpreet_ginny

FOUND THIS USEFUL? SHARE IT

comments (1 “Using Modules to avoid structures repetition in Geb Test Pages”)

  1. Marcin Erdmann

    Apart from module() there is also moduleList() method which is pretty helpful when you’re dealing with repeating content on a page:

    Reply

Leave a comment -