如何在 Capybara 通过匹配元素的精确文本来找到元素

我在 HTML 中有以下两个元素

<a href="/berlin" >Berlin</a>
<a href="/berlin" >Berlin Germany </a>

我试图通过使用下面的 Capybara 方法找到元素

find("a", :text => "berlin")

Above will return two elements because both contains text berlin.

在水豚有没有办法匹配精确的文本?

88777 次浏览

:text键的值使用 regexp 而不是字符串:

find("a", :text => /\ABerlin\z/)

查看 Method: Capybara::Node::Finders#all 文件中的“选项散列”部分。

文本匹配是区分大小写的。您的示例代码实际上引发了一个错误:

find("a", :text => "berlin")
# => Capybara::ElementNotFound:
#    Unable to find css "a" with text "berlin"

使用 Capybara's exact option:

Capybara.exact = true

取决于您使用的 gem 的版本

find('a', text: 'Berlin', exact: true)

在这种情况下,你必须使用

find('a', text: 'Berlin', match: :prefer_exact)

为了在 capybara 中使用 click _ link,您需要在使用它的方法中添加另一个属性。

click_link(link_name, :text => link_name)

这里的 link_name是链接的文本值。 Using 翻译: text keyword we are specifying that we want to click on a link having the text value which is exact matching to our requirement.

My preference is to use the have_selector with text and exact_text: true:

expect(body).to have_selector 'a', text: 'Berlin', exact_text: true

你也可以这样做:

find('a', text: 'Berlin', exact_text: true)

可以找到 CSS。

只使用 exact: true而不使用 exact_text将向您显示一个 msg,即 exact选项仅对 XPATH 有效。