Skip to content

Instantly share code, notes, and snippets.

@gmcnaughton
Created October 29, 2012 20:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmcnaughton/3976287 to your computer and use it in GitHub Desktop.
Save gmcnaughton/3976287 to your computer and use it in GitHub Desktop.
Add support to Capybara for selectors matching the current node
# spec/support/capybara_node_matchers.rb
# Monkey-patches Capybara to add ```match_css?```, and ```match_selector?``` matchers.
module Capybara::Node::Matchers
# Returns whether this node matches the given selector.
def match_selector?(*args)
result = parent_element.all(*args)
# NOTE: In 1.1.2, ```page.find("#foo") != page.find("#foo")``` (seriously??)
# Instead, check whether the node's native representations match.
# See https://github.com/jnicklas/capybara/issues/542
result.any? { |other| self.eql?(other) or (other.respond_to?(:native) and native == other.native) }
end
# Returns whether this node matches the css selector. The built-in
# ```has_css?``` only applies to *descendants* of the current node,
# not the current node itself (by design).
# See http://stackoverflow.com/questions/8282399/capybara-field-has-css-matcher
def match_css?(path, options={})
match_selector?(:css, path, options)
end
private
# Capybara::Node.parent returns the parent document, not the parent element.
# jnicklas has rejected syntactic sugar patches for this, saying that it's
# simple enough to use selectors to find the parent node.
# See http://stackoverflow.com/questions/4861863/how-to-get-parent-node-in-capybara
#
# WARNING: calling parent_element on the root <html> element causes Capybara
# to freeze and never come back!
def parent_element
find(:xpath, "..")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment