gpt4 book ai didi

html - 使用 capybara 查找表中的特定行

转载 作者:数据小太阳 更新时间:2023-10-29 07:27:59 25 4
gpt4 key购买 nike

我有一个用户表,其中列出了用户的 ID、姓名、电子邮件和用户名。我试图做的是验证特定条目是否在该表中。

基本上我想做的是找到 ID = 22 的行,然后验证 name = John Smithemail = john@smith.comusername = jsmith。能够设置如下所示。我不明白的是一些事情......

  1. 如何获取包含特定文本的行,即 I.E.即 user.id = 22。
  2. 获得该行后,如何使用它获取每个元素。

我以为我可以做一种 for 循环,但不知道如何设置 has_selector? 条件。 (以下为伪代码)

page.all('tr').each do |tr|
next unless tr.has_selector?('td.id = 22') #psuedocode

expect(tr.get('td.name').to eq("John Smith")
#other expects here...
end

表格代码

<table class="table table-striped table-condensed">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<% @users.each do |user| %>
<tr>
<td class="id"><%= user.id %></td>
<td class="name"><%= link_to user.name, user %></td>
<td class="email"><%= user.base_name %></td>
<td class="username"><%= user.username %></td>
</tr>
<% end %>
</tbody>
</table>

最佳答案

一种干净利落的方法是为每个 tr 元素添加一个“data-user-id”属性,然后使用 tr = find('tr[data-user-id="22 "]'),但如果这不是一个选项,则有多种方法可以做到这一点。无论是

td = page.find(:css, 'td.id', text: /^22$/) # find the id td with text of exactly 22
tr = td.find(:xpath, './parent::tr') # get the parent tr of the td
expect(tr).to have_css('td.name', text: 'John Smith')

或仅使用类似 xpath 的方式查找行

tr = page.find(:xpath, ".//tr[./td[@class='id'][text()='22']]")
expect(tr).to have_css('td.name', text: 'John Smith')

应该做你想做的。如果您想坚持使用循环方法(不推荐,因为它会很慢 - 而且您的循环结构方式可能无法验证任何内容)它会是

page.all('tr').each do |tr|
next unless tr.has_css?('td.id', text: /^22$/)
expect(tr).to have_css('td.name', text: "John Smith")
#other expects here...
end

关于html - 使用 capybara 查找表中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39479485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com