如何检查元素是否存在并在 Geb/Groovy 的单个表达式中获取它的内容?

How to check element exists and take it's content in single expression in Geb/Groovy?

我有一个 table 元素可以是正常模式下的文本或编辑模式下的输入字段。

目前我正在使用以下代码查找数据(参见firstName):

class UserRow extends Module {

    static content = {

        cell { i -> $("td", i) }

        id {
            cell(0)
        }

...
        firstName {

            if( cell(2).find("input").length ) {
                cell(2).find("input")
            }
            else {
                cell(2)
            }

        }

在 Groovy 的单个表达式中不能做到这一点吗?

Tim 在他的评论中似乎提出了一个很好的解决方案:

cell(2).$('input') ?: cell(2)

这将起作用,因为 AbstractNavigator implements asBoolean() 因此空导航器(不匹配任何元素的导航器)在布尔表达式中计算为 false。