Making Web Tests Readable, Robust and Rapid
Tutorial: Groovy Functional Testing with Geb - Part 5
Revisiting our Functional Test
With our login page and user home page defined, let us revisit our previous functional test. Listing 4 contains a rewritten LoginSpec that utilizes our LoginPage and UserHomePage objects.
Listing 4 - LoginSpec.groovy
import geb.spock.GebSpec
class LoginSpec extends GebSpec{
def "should login with valid username and password"(){
when:
to LoginPage
then:
at LoginPage
when:
username = "user1@example.com"
password = "goodpassword"
submitButton.click()
then:
at UserHomePage
}
def "should redisplay form with an error message when password is bad"(){
when:
to LoginPage
then:
at LoginPage
when:
username = "user1@example.com"
password = "badpassword"
submitButton.click()
then:
at LoginPage
errors.size() == 1
invalidUsernameOrPasswordError.present
}
}
There are a few differences between SimpleLoginSpec and LoginSpec that merit explanation. First note that, rather than use the go() method to navigate to our login page, the new test makes use of the Browser’s to() method. The to() method takes a Page class as its argument, and uses the page’s static url property to determine where to navigate to. Additionally, invoking the to() method tells the Browser that it should treat the specified page as the current page. Invoking the Browser’s at() method calls the at closure defined on the page object to determine whether navigating to the page was successful.
As the GebSpec delegates method and property calls to the Browser object, so too does the Browser delegate method and property calls to the current Page object. Because our first “when”/”then” blocks set the current page to LoginPage, we can access its content as though it is defined in the test class itself. The second “when” block accesses the LoginPage’s username and password content, using Geb form control shortcuts to set their values as though they are properties (the use of this syntax is identical to calling the value() method on the content). We then instruct the browser to click on the page’s submitButton content before verifying the page has been successfully changed. Recall that because we specified the UserHomePage as a value for the “to” option in the submitButton’s options map, the Browser knows that clicking on the content should take us to that page without us needing to state it explicitly.
In the second test case, we manually verify that the optional errors content is present after submitting the form containing the bad password. Every Navigator instance has a present property that can be used to check its existence on the page, which we invoke manually here to verify the specific error we are expecting is actually there.
Pages
- Intro
- What is Geb?
- Writing a Functional Test
- Understanding the Page Object Pattern
- Revisiting our Functional Test
- Comparisons and Conclusions
Follow us