Geb & Spock - If/Then/Else logic - How to check for a record and do one thing if it exists but continue on if it doesn't

蓝咒 提交于 2019-12-23 01:42:03

问题


I'm testing the creation and then removal of a record on my site using Geb/Spock. However I can't create the record if it already exists and so I check for the existence of the record and remove it if it exists in the beginning of the test. The problem occurs when the record does not exist, causing the test to fail. Is there a way to incorporate some if/then/else logic so the test will continue if it does not find the record in the beginning and remove it if it does find it?

Edit for example code:

/**
 * Integration test for Create Record
**/
class CreateAndRemoveRecordSpec extends GebSpec {

def 'check to make sure record 999 does not exist'() {

    given: 'user is at Account Page'
    to MyAccountPage

    when: 'the user clicks the sign in link'
    waitFor { header.signInLink.click() }

    and: 'user logs on with credentials'
    at LoginPage
    loginWith(TEST_USER)

    then: 'user is at landing page.'
    at MyAccountPage

    and: 'list of saved records is displayed'
    myList.displayed

    /* I would like some sort of if here so the test doesn't fail if there is no record*/
    when: 'record 999 exists'
    record(999).displayed

    then: 'remove record 999'
    deleteRecord(999).click()

    /* continue on with other tests without failing whether or not the record exists */
}

def 'test to create record 999'() {}

def 'test to remove record 999'() {}

回答1:


You could do something like:

when: 'record 999 exists'
def displayed = record(999).displayed

then: 'remove record 999'
!displayed || deleteRecord(999).click()

If record(999) isn't displayed then the !displayed statement will evaluate to true, and so the deleteRecord(999).click() shouldn't get evaluated, therefore causing the test to pass.

When the record is displayed, !displayed will evaluate to false, and so spock will have to evaluate the deleteRecord(999).click() statement, providing the desired behavior.

This works based on short-circuit evaluation (which Java and Groovy both use) http://en.wikipedia.org/wiki/Short-circuit_evaluation



来源:https://stackoverflow.com/questions/25368067/geb-spock-if-then-else-logic-how-to-check-for-a-record-and-do-one-thing-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!