Capybara - assert_selector("tr#1234") doesn't work, but find_by_id(1234) does

611 Views Asked by At

What are possible reasons that doing page.find_by_id(id) works, but doing page.assert_selector("tr##{id}") returns aCapybara::ElementNotFound`?

For background, I am using the Poltergeist driver for Capybara.

I have HTML that is structured like so:

<tbody>
  <tr id="1234">
    <td>Rico Jones</td>
    <td><a href="/price_requests/5678">Price Request</a></td>
  </tr>
  <tr id="2345">
    <td>Rico Jones</td>
    <td><a href=/price_requests/6789">Price Request</a></td>
  </tr>
</tbody>

I have confirmed that my HTML is coming out as expected by using the page.driver.debug feature of Poltergeist and looking at the actual HTML generated by the test.

When I put something like this in my tests, I get a Capybara::Poltergeist::InvalidSelector error with the message The browser raised a syntax error while trying to evaluate the selector.

lead = Lead.first
assert_selector "tr##{lead.id}"

I also get an error when doing this:

lead = Lead.first
within "tr##{lead.id}" do
  click_on "Price Request"
end

However, using find_by_id works:

lead = Lead.first
find_by_id(lead.id).click_on("Price Request")

Based on my understanding of Capybara, this shouldn't be the case. Am I doing something wrong?

1

There are 1 best solutions below

0
On BEST ANSWER

This is because ID's should not begin with numbers, as shown here.

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").