Search code examples
rubycapybara

How to validate if the table is empty with capybara?


I have tried all these commands but none works. I even used some tips from StackOverflow but I wasn't happy yet.. I have tried all these commands but none works. I even used some tips from StackOverflow but I wasn't happy yet.. I have tried all these commands but none works. I even used some tips from StackOverflow but I wasn't happy yet..

expect(find('.tvGrid').has_no_content?).to be true
expect(find('.tvGrid')).to have_no_content
expect(find('.tvGrid > tbody', visible: false)).not_to have_css('td')
expect(find('.tvGrid > tbody')).to have_no_content
<table width="100%" class="tvGrid">
  <tbody>
    <tr>
      <th colspan="1" class="tvHeader">Id</th>
      <th colspan="1" class="tvHeader">Code</th>
      <th colspan="1" class="tvHeader">Description</th>
      <th colspan="1" class="tvHeader">Operational Center</th>
      <th colspan="1" class="tvHeader">Status</th>
    </tr>
    <tr class="tvRowEmpty">
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr class="tvRowEmpty">
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr class="tvRowEmpty">
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr class="tvRowEmpty">
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr class="tvRowEmpty">
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr class="tvRowEmpty">
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr class="tvRowEmpty">
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
     </tr>
  </tbody>
</table> 

Solution

  • The point is that you can check that there is no text inside td nodes. There are many ways to do it

    As example

    expect(all('.tvGrid td').any? { |td| td.text.present? }).to be false
    

    or

    expect(all('.tvGrid td').select { |td| td.text.present? }).to be_empty
    

    or

    expect(all('.tvGrid td').all? { |td| td.text.blank? }).to be true
    

    .blank? and .present? are ActiveSupport methods. In vanilla Ruby you can use .strip.empty? instead of these methods