Capybara - Click Element by Class Name

For what seems to be a simple question I've been on this for a stupidly long time and can't seem to find anything on Google. I have this button I need to click which has no id but a class is included

<button class="filter-case-studies" onclick="initBootpag(filterForContentType('CASE STUDIES', searchHits))" type="button">
<b>CASE STUDIES</b>
(2)
</button>

I've tried using click_on which I now know is only for links and buttons so of course won't work. This is what I have so far:

When(/^I filter the results to only see case studies$/) do
  click_on('filter-case-studies')
end

I've also tried page.find('filter-case-studies').click, this too doesn't work.

page.find(:class, 'filter-case-studies').click defualts to :css so this also failed for me.

Is there no way to click an element by the class name in Capybara?

Thanks in advance for the help.

5 Answers

The standard way of doing this in Capybara is

find('button.filter-case-studies').click

In relatively recent versions of Capybara you should also be able to do

click_on(class: 'filter-case-studies')
1

find('.filter-case-studies').click as recommended here

I had a button that could not be found (Unable to find visible link or button nil with classes [close-modal]) using the methods above.

This worked for me: page.execute_script('$.find(".close-modal")[0].click()')

click_on('.filter-case-studies')

You need the . selector for classes, and # for ids.

3

Thanks to Mr Schutte for the idea to use . selectors.

I had to use page.find(:class, '.filter-case-studies').click in the end. The absolute navbar got in the way of the button so I then had to include page.execute_script "window.scrollBy(0,500)" to complete the test.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest