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
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>
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"
This was inspired by Laravel Dusk's selectors
Top comments (0)