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 "brandon@example.com"
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
Very useful, thanks!
This is great.
the useful content u provided do help my investigation for my corporation, appreaciate that.
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):
I found the following method
Thanks - using this to test my site.
Please, could you show the code of the step “And I press enter” ?
These days you can do:
find(selector).click
These days you can do:
find(selector).click
Here’s an updated version for Capybara 1.0+ and current XPath lib:
https://gist.github.com/1210639
A bit old article but still useful. Hope you can update this one. Thanks!