Clicking any element with Cucumber and Capybara

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"
brandon@opensoul.org

Comments

  1. August 16, 2010 at 11:00 AM

    Very useful, thanks!

  2. August 20, 2010 at 14:38 PM

    This is great.

  3. August 20, 2010 at 23:00 PM

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

  4. dk@structuralartistry.com
    David Kahn
    October 08, 2010 at 22:42 PM

    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

  5. February 14, 2011 at 19:14 PM

    Thanks - using this to test my site.

  6. April 11, 2011 at 11:26 AM

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

  7. July 21, 2011 at 18:49 PM

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

  8. July 21, 2011 at 18:49 PM

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

  9. September 12, 2011 at 5:32 AM

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

    https://gist.github.com/1210639

  10. December 06, 2016 at 12:55 PM

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