Question

I want to select a random HTML select option in my test, however the options are generated dynamically and their IDs aren't necessarily clear at the time of running the test.

I am using page objects and content DSL (actually just defining the form as form { $("form") } as I had issues otherwise), and I know that I can assign a particular ID or text value to the form.dropdown control, but I'm not sure what's the easiest way to obtain a list of all dropdown value IDs (or better yet their mapping to names) for this dropdown.

I've so far tried just to check the type of form.dropdown but it is reported as ArrayList and contains null values so that's not very useful.

I've read through the Geb guide but didn't manage to find a good solution in what I believe is the relevant section:

http://www.gebish.org/manual/current/all.html#setting_values

FWIW I'm using Groovy/Grails with Firefox WebRunner.

Was it helpful?

Solution 2

Not sure if there is a 'gebish' way to do this, but you can get the values and labels using a selector

$('form select[name="dropdown"] option').each {
        println it.text() + ' :: ' + it.value()
}

OTHER TIPS

This is the way I did it. Having this form:

<form id="myform">
    <select name="dropdown">
        <option value="a">A</option>
        <option value="b">B</option>
        <option value="c">C</option>
    </select>
</form>

First get the options, for simplicity:

def options = $('#myform select[name="dropdown"] option')

Then, generate a random index this way:

int numOptions = options.size()
int randomIndex = System.currentTimeMillis() % numOptions

Finally, because I haven't yet found how to set the option by index, I set it by value:

String randomValue = options[randomIndex].value()
$('#myform').dropdown = randomValue

Or, to make a long story short,

def options = $('#myform select[name="dropdown"] option')
$('#myform').dropdown = options[(System.currentTimeMillis() % options.size()) as int].value()

We can also reference the SELECT from the OPTION, avoiding unnecessary CSS selections:

def options = $('#myform select[name="dropdown"] option')
options.parent().value( options[(System.currentTimeMillis() % options.size()) as int].value() )

Hope it works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top