Rspec和watir-webdriver;断言元素不存在

时间:2016-07-25 21:49:10

标签: rspec watir-webdriver assertions

我正在使用Rspec和watir-webdriver并且正在努力编写一个通过测试,以便当一个项目在屏幕上被删除时,它不是存在 - 因此通过这里是什么我正在尝试:

# this method gets the specific item I want to interact with
def get_item(title)
    foo = @browser.div(:text, title).parent.parent
    return foo
end

# This method looks at an element grid that contains all the items
def item_grid_contents
    grid = @browser.div(:class, 'items-grid')
    return grid
end

当我删除该项目时,这些是我尝试编写断言的一些方法:

expect(get_item(title)).not_to be_present # => fails, unable to locate element
expect(item_grid_contents).not_to include(get_item(title)) # => fails, same error

在这种情况下,我希望确保元素不能定位,并且应该通过。 有没有其他方法来写这个,所以它被认为是一个传递?

2 个答案:

答案 0 :(得分:1)

这是因为#parent方法使用javascript来查找从中创建Watir元素的Selenium元素。对于大多数元素,Watir创建一个xpath定位器,但是懒惰加载它,以便在它与之交互之前不必存在。通过此javascript调用,它会立即进行评估,因此无法立即失败,无法回复#exists?#present?方法。

这是一个很好的例子,说明为什么我不喜欢我们当前的父母实施。我已经坐在代码上改变了一段时间,因为我没有一个令人信服的理由去推动它。这是一个令人信服的理由。

目前,我认为这对您有用:

@browser.div(:text, title).element(xpath: './ancestor::*[2]')

答案 1 :(得分:1)

为什么不检查div(:text, title)是否存在?毕竟如果外部容器(父级)消失了,那么内容(子级)也是如此。

expect(@browser.div(text: title)).not_to be_present

或(不确定我的语法是否在这里......)

expect(@browser.div(text: title).present?.to be_false

小注意重复红宝石...你可以通过不打扰中间变量使这些方法更清洁。事实上你甚至可以消除“回归”。因为它暗示着(但是我们有些人喜欢它的可读性)大多数编写Ruby代码的人都使用两个空格缩进。所以对于上面的方法,你可以使用

def get_item(title)
  return @browser.div(:text, title).parent.parent
end

甚至

def item_grid_contents
  @browser.div(:class, 'items-grid')
end