通过数据属性查找元素 [英] Find elements by data attributes

查看:75
本文介绍了通过数据属性查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 RSpec capybara-webkit 改进测试,试图删除所有 css xpath 选择器,例如

I'm improving my tests with RSpec and capybara-webkit, trying to delete all the css and xpath selectors like

find('#edit_user > div:nth-child(7) > div > div > button').click

,我正在寻找替换它们的最佳选择。


我打算使用 css类的元素,但是某些专业水豚测试人员说这不是最佳选择。

and I'm looking for the best option to replace them.

I was going to use the css class of the elements but some "pro" capybara tester said this is not the best option.

所以我的问题是:我可以使用 data 是我的测试中的属性吗?
如果我有元素

So my question is: can I use the dataattributes in my tests?
If I have an element

<button name="button" type="submit" class="button last" data-test="edit.update">Update/button>

我将能够做到

find('edit.update').click

您认为这是个好主意吗?如果您对此主题有更多想法/信息,请随时发表评论!

And do you think it is a good idea? If you have more ideas/infos about this topic, feel free to comment!

推荐答案

通过data- *属性查找元素,则需要使用CSS选择器或XPath。

To locate elements by their data-* attribute, you need to use a CSS-selector or XPath.

对于CSS选择器:

find('button[data-test="edit.update"]').click

对于XPath:

find('//button[@data-test="edit.update"]').click

这是否好取决于应用程序。您想选择可以唯一标识元素的东西。如果 edit.update不是唯一的,则不是一个好选择。如果按钮具有唯一的类,则 class 属性会很好,而 button和 last不太可能是这样。

Whether or not it is a good idea really depends on the application. You want to pick something that uniquely identifies the element. If "edit.update" is not going to be unique, it would not be a good choice to use. The class attribute would be fine if the button had a unique class, which "button" and "last" are not likely to be.

最好的方法实际上是使用静态 id 属性,因为它们在页面中应该是唯一的,并且更改的可能性较小。 find 方法还支持按id定位元素,这意味着您不必编写CSS选择器或XPath。

The best approach is really to use static id attributes as they should be unique within the page and are less likely to change. The find method also supports locating elements by id, which means you do not have to write CSS-selectors or XPath.

这篇关于通过数据属性查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆