Search code examples
groovyspockgeb

Re-using tests among Geb Specs


I am trying to re-use a Geb Spec test I wrote in another Geb Spec so I won't need to re-write code. I always need the product number in different pages so I would like to do something similar to the following;

class BasePageGebSpec extends GebReportingSpec {
     def firstProductOnBrowsePage(){
        when:
        to BrowsePage
        then:
        waitFor { BrowsePage }
        productId { $("meta", 0, itemprop: "mpn").@content }
        return productID // ???
    } 
}

And in another GebSpec I wish to use the above firstProductOnBrowsePage like below:

 class ProductDetailsPageGebSpec extends BasePageGebSpec {
     def "See first products details page"(){
        when:
        to ProductDetailsPage, productId: firstProductOnBrowsePage()

       then:
       waitFor { $("h2", class:"title").size() != 0 }
       assert true
    }
}

Any help would be appreciated,

Thank you!


Solution

  • With traits you can almost get what you want (tests don't work within a trait however). You might also consider creating a spec class that tests the product number for every page you have, and then not worrying about testing this functionality within each individual page's spec class.

    trait BasePageGebSpec extends GebReportingSpec {
     def testingFirstBrowse() {
        waitFor { BrowsePage }
        productId { $("meta", 0, itemprop: "mpn").@content }
        return productID
     }
    }
    
     class ProductDetailsPageGebSpec implements BasePageGebSpec {
        def firstProductOnBrowsePage(){
            when:
                to BrowsePage
            then:
                testingFirstBrowse()
        } 
    }