4

I'm a bit new to the whole Selenium/Geb thing, so I'm probably going about this a bit wrong, but I'm trying to get the exists() method in the following code to work properly.

class Question extends Module {
    static base = { $("fieldset") }
    static content = {
        input { $("input[type=text]") }
        name { input.getAttribute("name").toString() }
    }
    boolean exists() {
        return input.isPresent()
    }

Frustratingly, when I try to execute that code (from a Spock Test, "go"ing to a PageObjectm including this module, I get the following:

The required page content 'input - SimplePageContent (owner: question - Question (owner: MyPage, args: [], value: null), args: [], value: null)' is not present

I've tried a number of other things, including:

  • if (input) return true; return false,
  • ... input.size() == 0,
  • Using static at = {...} (doesn't seem to be supported for modules"

Any ideas

Zach Lysobey
  • 14,959
  • 20
  • 95
  • 149

1 Answers1

11

By default Geb ensures that your content definitions return non empty elements. If your content is optional you can tell it using required content option:

name(required: false) { input.getAttribute("name").toString() }

Because Geb utilizes Groovy Truth to redefine how navigator are coerced to boolean values(empty navigators are falsey and non-empty are truthy) you can simplify your exists method to:

boolean exists() {
    input
} 
erdi
  • 6,944
  • 18
  • 28
  • Thank's for your response. I'll give it another go, but not sure why your answer would be different than my `if (input) return true; return false,` (not how the code *actually* looks) attempt. I'll try again shortly. – Zach Lysobey Dec 20 '13 at 15:38
  • The `exist()` implementation is indeed just a cosmetic change, but you need to set `required` to false on the content definition so that you won't get the exception about missing required content. – erdi Dec 20 '13 at 17:02
  • Hmm... maybe. Still haven't gotten a chance to tinker with it again today, but I *do* know (and shouldv'e stated) that the exception occurs on the line I execute the `exists()` method – Zach Lysobey Dec 20 '13 at 18:43
  • And I explained what to do to get rid of it - use `requried` content option. – erdi Dec 23 '13 at 16:01
  • I know. Sorry, was just making sure we were on the same page. I'll take a look at this again today... – Zach Lysobey Dec 23 '13 at 16:07
  • Hah! It works! Sorry I was perhaps a bit reluctant to trust that this answer was in fact correct without testing. I (thought I) tried stuff that was very similar to your answer, but I guess I was off somehow. This is verified as working now, thanks for your help! – Zach Lysobey Dec 23 '13 at 19:21