Geb: Get Selected Text From A Select Dropdown

Nov 22, 2013

gebMy current client has decided to migrate their automated ui tests over to Geb, thus, I've been busily ramping up on it for the last couple weeks. Geb, written in Groovy, sits atop Selenium Webdriver and provides some great conveniences, including elegant css selectors and page object support. Additionally, using Spock as your test runner allows you to write your tests in a given/when/then dsl.

I'm finding Geb to be a great tool but like all tools, it has its quirks. Take getting the currently selected text from a select box... Geb does not currently (0.9.2) have an api for this. It has support for getting the currently selected value but you'll have to do a little work to get the selected text. With a little trial and error (heavy on error), I was able to craft a reasonable solution to this problem in a page object selector. Here's my example code...

Page Object Code (TestyPage.groovy):

package pages

import geb.Page

class TestyPage extends Page {
    static url = ''
    static at = {pageTitle}
    static content = {
        pageTitle(wait:true) {title == 'craigslist: madison classifieds for jobs, apartments, personals, for sale, services, community, and events'}
        dropdown(wait:true) {$('select', name:'catAbb')}
        // workaround for getting the selected text from the dropdown....
        dropdownSelectedText {dropdown.find('option', value:dropdown.value()).text()}


Test Code (testy.groovy):

import geb.spock.GebReportingSpec
import pages.TestyPage

class Testy extends GebReportingSpec {
    def 'this is a test...'() {
        to TestyPage

        when: 'select gigs from dropdown...'
        dropdown = 'gigs'

        // assert the currently selected text...
        dropdownSelectedText == 'gigs'
        // you can also assert the selected value...
        dropdown.value() == 'ggg'

The trick here is in the page object. In the selector dropdownSelectedText, we use .find to get the first option tag, down the dom from dropdown, that has a value of dropdown.value() (in this case 'ggg') and then get the text from that option tag.

Reasonably clever...