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

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

问题描述

我正在用 RSpeccapybara-webkit 改进我的测试,试图删除所有的 cssxpath 选择器如

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-selector 或 XPath.

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

对于 CSS 选择器:

For the CSS-selector:

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天全站免登陆