rspec-html

0.3.5
Light Mode Dark Mode

Selectors

Each method in the chain can receive arguments to specify selectors on attributes of each element.

To select an <input> element with a name attribute whose value is email, pass name: 'email' to the input method:

Attribute Selectors

it 'renders a name field' do
  get '/users/new'
  expect(document.form.input(name: 'user[email]')).to exist
end
<form action="/users" method="POST">
  <label>Email:</label>
  <input name="user[email]" />
</form>

CSS Selectors

Since class is an attribute just like name you can specify the exact class string to match elements as document.table(class: 'table users'):

However, this test is very fragile - any change to the class attribute will cause the test to break, even if the order of the classes changes.

Instead, you can match using CSS selectors by passing a string directly to each element method:

it 'renders a users table' do
  get '/users'
  expect(document.table('.users')).to exist
end
<table id="users-table" class="table users">
  <thead>
    <tr>
      <th>Email</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="email">
        user@example.org
      </td>
      <td class="name">
        Example User #1
      </td>
    </tr>
    <tr>
      <td class="email">
        user@example.com
      </td>
      <td class="name">
        Example User #2
      </td>
    </tr>
  </tbody>
</table>
Email Name
Example User #1
Example User #2

Any valid CSS selector is permitted:

it 'renders a users table' do
  get '/users'
  expect(document.table('#users-table')).to exist
end
<table id="users-table" class="table users">
  <thead>
    <tr>
      <th>Email</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="email">
        user@example.org
      </td>
      <td class="name">
        Example User #1
      </td>
    </tr>
    <tr>
      <td class="email">
        user@example.com
      </td>
      <td class="name">
        Example User #2
      </td>
    </tr>
  </tbody>
</table>
Email Name
Example User #1
Example User #2
it 'renders a users table' do
  get '/users'
  expect(document.table('tr td[class="name"]')).to exist
end
<table id="users-table" class="table users">
  <thead>
    <tr>
      <th>Email</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="email">
        user@example.org
      </td>
      <td class="name">
        Example User #1
      </td>
    </tr>
    <tr>
      <td class="email">
        user@example.com
      </td>
      <td class="name">
        Example User #2
      </td>
    </tr>
  </tbody>
</table>
Email Name
Example User #1
Example User #2

Documentation generated by rspec-documentation