Using Modules to avoid structures repetition in Geb Test Pages
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.
[java]
class SubmitButtonModule extends Module {
static content = {
button { $("input", type: "submit") }
}
}
[/java]
Page can use modules in following manner:
[java]
class LoginPage extends Page {
static content = {
myModule { module SubmitButtonModule }
}
}
[/java]
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:
[java]
Browser.drive {
to LoginPage
myModule.button.click()
}
[/java]
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
[java]
<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>
[/java]
We can model this with the following
[java]
import geb.*
class CompanyPage extends Page {
static content = {
companyResult { index ->
module CompanyTableRow, $("table tr", index + 1) // +1 is used to avoid header row
}
}
}
[/java]
[java]
class CompanyTableRow extends Module {
static content = {
cell { i -> $("td", i) }
companyName { cell(0).text() }
location { cell(1).text() }
}
}
[/java]
We can now write code like…
[java]
assert companyResult(0).companyName == "ABC Pvt Ltd"
assert companyResult(1).location == "Noida"
[/java]
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
Apart from module() there is also moduleList() method which is pretty helpful when you’re dealing with repeating content on a page: