Created
February 11, 2015 23:30
-
-
Save darkside/99b534522ed97b4308fb to your computer and use it in GitHub Desktop.
contain and within for capybara
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Must have Nokogiri gem installed and save this file in your spec/support dir | |
# Allows you to write cleaner/faster specs in your views (50% faster than css_select) | |
# Increased readability in your spec doc | |
# ex. | |
# rendered.should contain('my heading').within('h1') # searches all H1 tags for 'my heading' | |
# or | |
# rendered.should contain('my string') # searches entire rendered string for 'my string' | |
class Within | |
def initialize(expected, css_selector) | |
@expected = expected | |
@selector = css_selector | |
end | |
def matches?(actual) | |
@html = Nokogiri.HTML(actual) | |
@html.css(@selector).to_s.include?(@expected) | |
end | |
def failure_message | |
"#{@html.to_s} should have located #{@expected} within '#{@selector}'" | |
end | |
def failure_message_when_negated | |
"#{@html.to_s} should not have located #{@expected} within '#{@selector}'" | |
end | |
def description | |
"contain #{@expected} within #{@selector}" | |
end | |
end | |
class Contain | |
def initialize(expected) | |
@expected = expected | |
end | |
def matches?(actual) | |
@actual = actual | |
@actual.include?(@expected) | |
end | |
def within(selector) | |
Within.new(@expected, selector) | |
end | |
def failure_message | |
"#{@actual} should contain #{@expected}" | |
end | |
def failure_message_when_negated | |
"#{@actual} should not contain #{@expected}" | |
end | |
def description | |
"contain #{@expected}" | |
end | |
end | |
def contain(expected) | |
Contain.new(expected) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment