Zac*_*ack 6 html ruby ruby-on-rails capybara
我有一个用户表,列出用户的ID,姓名,电子邮件和用户名.我试图做的是验证该表中的特定条目.
基本上我想要做的是找到ID = 22的行,然后验证name = John Smith,email = john@smith.com和username = jsmith.该功能设置如下所示.我不明白的是几件事......
我以为我可以做一种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
Run Code Online (Sandbox Code Playgroud)
表格代码
<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>
Run Code Online (Sandbox Code Playgroud)
一个很好的干净方法是为每个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')
Run Code Online (Sandbox Code Playgroud)
或者仅使用xpath查找行
tr = page.find(:xpath, ".//tr[./td[@class='id'][text()='22']]")
expect(tr).to have_css('td.name', text: 'John Smith')
Run Code Online (Sandbox Code Playgroud)
应该做你想做的事.如果你想坚持使用循环方法(不推荐,因为它会很慢 - 以及你的循环结构的方式,它可能无法验证任何东西)它将是
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5603 次 |
| 最近记录: |