Capybara出现Ambiguous match匹配2个元素错误,如何选取唯一未知选择器
解决方案
报错原因说明
- 直接加
text参数匹配失败:因为目标文本嵌套在button下属的span标签中,默认严格文本匹配规则不会自动合并子节点的空白字符(空格、换行),导致匹配失败。 - 报
Ambiguous模糊匹配错误:因为你用element定义单个元素,但定位规则匹配到了2个符合条件的元素,element要求唯一匹配,所以需要调整定义方式。
方案1:通过文本特征精准定位(推荐,稳定性更高,不受按钮顺序变化影响)
利用XPath匹配按钮下所有子节点的文本,自动处理空白字符:
类方法文件修改为:
class ProfileMembershipsTab < SitePrism::Page set_url "[webpage url]" element :send_club_assignment_button, :xpath, '//button[contains(@class, "se-button--medium") and normalize-space(.) = "Send Club Assignment"]' element :actionable_redirect_header, "h1", text: "Actionable Redirect" end
测试文件的点击逻辑修改为(去掉重复的点击调用):
profile_memberships_tab.send_club_assignment_button.click
方案2:通过元素集合选择第二个按钮
如果确认按钮顺序不会变化,可以定义元素集合后通过下标取值:
类方法文件修改为:
class ProfileMembershipsTab < SitePrism::Page set_url "[webpage url]" # 用elements定义所有匹配的按钮集合 elements :se_medium_buttons, "button", class: "se-button--medium" element :actionable_redirect_header, "h1", text: "Actionable Redirect" end
测试文件的点击逻辑修改为:
# 数组下标从0开始,第二个元素取索引1 profile_memberships_tab.se_medium_buttons[1].click
额外注意事项
原来的click_on(xxx).click写法有误,click_on是Capybara原生方法,接收文本、id等定位符,不能直接传入SitePrism元素对象,拿到元素对象后直接调用.click即可。
内容的提问来源于stack exchange,提问作者rgorowsky
相关产品推荐
相关产品推荐

