确保Capybara不存在元素

mic*_*ish 32 ruby capybara

使用Capybara,我需要声明表单元素不存在,例如,'然后我不应该看到"用户名"文本字段'.如果找不到元素,find会抛出异常,这是我提出的最好的.有没有更好的办法?

Then /^I should not see the "([^\"]+)" ([^\s]+) field$/ do |name, type|
  begin
    # Capybara throws an exception if the element is not found
    find(:xpath, "//input[@type='#{type}' and @name='#{name}']")
    # We get here if we find it, so we want this step to fail
    false
  rescue Capybara::ElementNotFound
    # Return true if there was an element not found exception
    true
  end 
end
Run Code Online (Sandbox Code Playgroud)

我是Capybara的新手,所以我可能会遗漏一些明显的东西.

Der*_*ins 52

你可以通过使用capybaras has_no_selector来做到这一点?方法结合rspecs魔术匹配器.然后您可以这样使用它:

 page.should have_no_selector(:xpath, "//input[@type='#{type}' and @name='#{name}']")
Run Code Online (Sandbox Code Playgroud)

您可以在标题查询部分的capybara文档页面上查看可以执行的断言的更多详细信息


5_n*_*d_5 26

您实际上可以使用Capybara匹配器定义的现有方法.

assert has_no_field?('Username')
Run Code Online (Sandbox Code Playgroud)

此外,还有其他方法可以帮助您在页面中查找不同类型的元素

has_link? , has_no_link?
has_button?, has_no_button?
has_field?, has_no_field?
has_checked_field?, has_no_checked_field?
has_select?, has_no_select?
Run Code Online (Sandbox Code Playgroud)

还有很多 ...

  • 这个答案比公认的要好得多。 (2认同)

nro*_*ose 10

这是我正在使用的:

expect(page).to have_no_css('.test')
Run Code Online (Sandbox Code Playgroud)