Capybara - Click element by class name

King picture King · Apr 13, 2017 · Viewed 24.7k times · Source

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.

Answer

Thomas Walpole picture Thomas Walpole · Apr 13, 2017

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')