Search code examples
seleniumgroovygeb

How to verify error messages using Geb


How do i capture the error messages generated on web page(for example an error message generated when a login button is pressed without inserting any username or password), how do i extract this error message "Username is required" using geb. im using geb groovy based automation


Solution

  • So you would first model your page, and get the locator for the error you want to assert has been displayed. Note that you want to set this to required: false as you would not expect it to be displayed when you first land on the page.

    Page with example page error with ID of #pageError:

    class MyPage extends Page
    {
        static url = "/mypageurl"
        static at = {
            title == "My Page"
        }
    
        static content = {
            pageError (required: false) { $('#pageError') }
            submitButton { $('#mySubmitButton') }
        }
    
        def submitForm() {
          submitButton.click()
         }
    }
    

    Then you have your test:

    def "If I try click Submit without filling out all form details show me an error message"()
    {
        when: "I click Submit without completing all form fields"
    
            def myPage = to(MyPage)
            myPage.submitForm()
    
        then: "I am shown an error message on the same page"
    
            myPage.pageError.displayed
    }
    

    EDIT:

    Noticed you mentioned getting the content of the error, you would call this instead to get the text:

    myPage.pageError.text()