Talking testing, automation... and anything else.


A Better Way To Handle Checkboxes in Geb

checkboxGeb is a great automation tool with a lean API but in some cases, perhaps a bit too lean. Case-in-point, checkboxes. Here’s how you handle checkboxes in Geb:

// check checkbox...
picCheckbox.value(true)
// verify checkbox is checked...
picCheckbox.value() == "1"

Not the end of the world but IMO, not good enough. It doesn’t read overly well and requiring you to know the value of the checkbox to verify it’s checked, is less than ideal. We can do better… by using modules.

Using a module, we can add methods for handling checkboxes, that are, IMO, easier to read and use.

CheckboxModule

package modules

import geb.Module

class CheckboxModule extends Module {
    def check() {
        this.value(true)
    }

    def uncheck() {
        this.value(false)
    }

    def isUnchecked() {
        this.value() == false
    }

    def isChecked() {
        !isUnchecked()
    }
}

Pretty simple; create a module and add four methods to it. Two that let us check or uncheck a checkbox, and two that verify it’s checked or unchecked. Because isChecked() would require knowing the value of the checkbox (lame), we simply check that is not, not checked (yeah, it hurts my head too).

Now we add the module to our page object and then use the methods in a test…

CLSearchResultsPage

static content = {
  picCheckbox {module CheckboxModule, $("input", name:"hasPic")}
}

CLSearchSpec

 when: 'filter results with pics'
  picCheckbox.check()
  searchButton.click()

  then:
  picCheckbox.isChecked()

As usual, this code is available on GitHub

1 comment

  1. This is a great little class!

Leave a Reply