如何计算表中的行数。 (RSpec,Capybara)

时间:2014-10-16 05:42:20

标签: ruby-on-rails rspec

我有这段代码:

<table class="table" id="charges_failed">
<tr>
  <th>Customer</th>
  <th>Charge Amount</th>
  <th>Date Failed</th>
  <th colspan="3"></th>
</tr>
<% @charges_failed.each do |charge| %>
  <tr bgcolor="#FF0000">
    <td><%= charge.formatted_customer_name %></td>
    <td><%= number_to_currency(charge.amount.to_s) %></td>
    <td><%= charge.created_at.strftime("%d/%m/%Y") %></td>
  </tr>
<% end %>

我有这个测试:

it "check failed charges" do
  visit root_path
  expect(page).to have_selector('table#charges_failed tr', :count => 6)
end

为什么他只找到表格中的第一行。总计第6页。 (错误:预计会找到css&#34;表#charge_failed tr&#34; 6次,找到1匹配:&#34;客户费用金额日期失败&#34;)

2 个答案:

答案 0 :(得分:5)

我发现最简单的方法是使用xpath。

会是这样的:

within('table#charges_failed') do
    expect(page).to have_xpath(".//tr", :count => 6)
end

你可能也可以放弃&#39;并定义一个完整的xpath,如:&#34; .// table [@id =&#39; charges_failed&#39;] // tr&#34;

据我所知,have_selector只是检查某些东西的存在(css,xpath等)。我以前从来没有见过用过它的计数。

答案 1 :(得分:0)

您还可以编写以下支票:

within('#charges_failed') do
  expect(all('tr').count).to eq(6)
end

这将检查您的表是否正好有6行

相关问题