Skip to Content Collective Idea Home

Clicking any element with Cucumber and Capybara

by Brandon Keepers

Capybara includes handy methods for clicking on links and buttons, but there’s not an easy way to click on any other element. This usually isn’t an issue, unless you’re writing a Javascript-heavy app.

Here is Cucumber step that lets you click on any element:

class Capybara::XPath
  class << self
    def element(locator)
      append("//*[normalize-space(text())=#{s(locator)}]")
    end
  end
end

When 'I click "$locator"' do |locator|
  msg = "No element found with the content of '#{locator}'"
  locate(:xpath, Capybara::XPath.element(locator), msg).click
end

The step looks for any element with the given text. Here it is in use:

Scenario: Creating an item
  Given I am signed in as "[email protected]"
   When I click "Add to your list"
    And I fill in "Description" with "blog about clicking any element"
    And I press enter
   Then I should see "The item was added to your list"
    And I should see "blog about clicking any element"

Comments

Vidmantas
::

Very useful, thanks!


Gordon
::

This is great.


Telefon Schnurloses
::

the useful content u provided do help my investigation for my corporation, appreaciate that.


David Kahn
::

Wanted to thank you for this article. I’m doing a touchscreen app with lots of js and needed this.

I ended up doing a further customization which looks for a certain class in addition to the text to be more specific:

class Capybara::XPath class << self def wavelineup_selector_cell(selector_text) append(“//*[@class=‘selector_cell_nav’ and text()=#{s(selector_text)}]”) end end end

Also, there seems to be a built in method in Capybara to add a selector but I can not figure out where to put it (it works if I put it in a Cucumber step but this seems really wrong):

Capybara::Selector.add(:wavelineup_selector_cell) { |selector_text| “//*[@class=‘selector_cell_nav’ and text()=#{s(selector_text)}]” }

I found the following method


Nicholas
::

Thanks - using this to test my site.


fabio perrella
::

Please, could you show the code of the step “And I press enter” ?


Sharagoz
::

These days you can do: find(selector).click


Ches Martin
::

Here’s an updated version for Capybara 1.0+ and current XPath lib:

https://gist.github.com/1210639


Morten
::

A bit old article but still useful. Hope you can update this one. Thanks!