DEV Community

Ahmad khattab
Ahmad khattab

Posted on

Rails: Easily allow Capybara to find elements with a helper method.

Capybara is the testing framework for writing E2E(end-to-end) tests in Ruby.

It has multiple helper methods to allow you to write neat system specs. You can use id, .class, or any normal valid css selector that you can think off.

But, sometimes Capybara does not find the element, although the selector you wrote is correct.

I have came up with a small helper method that will add an HTML id to the tag that is only used in testing environment. So that it will not be visible in production when being inspected.

# app/helpers/capybara_helper.rb

module CapybaraHelper
  def capybara_can_find_by(id)
    "id='#{id}'".html_safe if Rails.env.test?
  end
end
Enter fullscreen mode Exit fullscreen mode

This method appends an HTML id to the element that is called on. For example, it can be used like this in your erb files.

<div <%= capybara_can_find_by "element-id" %>>

</div>
Enter fullscreen mode Exit fullscreen mode

Now. When writing capybara specs, you can simply use the id selector to easily find the element you are looking for.

within "#element-id" {  }
find "#element-id"
Enter fullscreen mode Exit fullscreen mode

This was inspired by Laravel Dusk's selectors

References

Top comments (0)