2

我遇到过几个例子,人们用 来测试 html 元素的内容page.should have_selector "title", content: "my awsome content",但这似乎总是通过。正确的调用似乎是page.should have_selector "title", text: "my awsome content"(注意text:而不是content:)。

content:这个 Rspec 调用 中的选择器是什么?

4

1 回答 1

1

简短的回答:

have_selector不支持:content选项。

长答案:

Rspec 创建将调用转换为的动态方法[].should be_empty[].empty?.should == true在您的情况下,page.should have_selector "title", content: "my awesome content"转换为page.has_selector?("title, content: "my awesome content").should == true.

Capybara提供了has_selector?方法,它基本上只是将其参数传递给其test/unit样式断言assert_selector

def has_selector?(*args)
  assert_selector(*args)
rescue Capybara::ExpectationNotMet
  return false
end

assert_selector然后再次将其参数传递给 Capybara finder 方法,如果找到任何匹配项则all()返回,true如果没有则引发异常(has_selector?捕获然后返回false)。

def assert_selector(*args)
  synchronize do
    result = all(*args)
    result.matches_count? or raise Capybara::ExpectationNotMet, result.failure_message
  end
  return true
end

all方法返回与查询匹配的所有结果。在这里,我们可以找到有关可接受选项的文档:

# @overload all([kind], locator, options)
#   @param [:css, :xpath] kind                 The type of selector
#   @param [String] locator                    The selector
#   @option options [String, Regexp] text      Only find elements which contain this text or match this regexp
#   @option options [Boolean] visible          Only find elements that are visible on the page. Setting this to false
#                                              (the default, unless Capybara.ignore_hidden_elements = true), finds
#                                              invisible _and_ visible elements.
# @return [Array[Capybara::Element]]           The found elements

我们可以看到它content没有被列为有效选项,因此被忽略了。

于 2012-10-13T01:21:54.333 回答