2 # Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
3 # Under MIT and/or CC By license.
6 module ActionController
8 unless const_defined
?(:NO_STRIP)
9 NO_STRIP
= %w
{pre script style textarea
}
12 # Adds the +assert_select+ method for use in Rails functional
13 # test cases, which can be used to make assertions on the response HTML of a controller
14 # action. You can also call +assert_select+ within another +assert_select+ to
15 # make assertions on elements selected by the enclosing assertion.
17 # Use +css_select+ to select elements without making an assertions, either
18 # from the response HTML or elements selected by the enclosing assertion.
20 # In addition to HTML responses, you can make the following assertions:
21 # * +assert_select_rjs+ - Assertions on HTML content of RJS update and insertion operations.
22 # * +assert_select_encoded+ - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions.
23 # * +assert_select_email+ - Assertions on the HTML body of an e-mail.
25 # Also see HTML::Selector to learn how to use selectors.
26 module SelectorAssertions
28 # css_select(selector) => array
29 # css_select(element, selector) => array
31 # Select and return all matching elements.
33 # If called with a single argument, uses that argument as a selector
34 # to match all elements of the current page. Returns an empty array
35 # if no match is found.
37 # If called with two arguments, uses the first argument as the base
38 # element and the second argument as the selector. Attempts to match the
39 # base element and any of its children. Returns an empty array if no
42 # The selector may be a CSS selector expression (String), an expression
43 # with substitution values (Array) or an HTML::Selector object.
46 # # Selects all div tags
47 # divs = css_select("div")
49 # # Selects all paragraph tags and does something interesting
50 # pars = css_select("p")
52 # # Do something fun with paragraphs here...
55 # # Selects all list items in unordered lists
56 # items = css_select("ul>li")
58 # # Selects all form tags and then all inputs inside the form
59 # forms = css_select("form")
60 # forms.each do |form|
61 # inputs = css_select(form, "input")
66 # See assert_select to understand what's going on here.
69 if arg
.is_a
?(HTML
::Node)
73 raise ArgumentError
, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
77 @selected.each
do |selected
|
78 subset
= css_select(selected
, HTML
::Selector.new(arg
.dup
, args
.dup
))
79 subset
.each
do |match
|
80 matches
<< match
unless matches
.any
? { |m
| m
.equal
?(match
) }
86 root
= response_from_page_or_rjs
91 selector
= HTML
::Selector.new(arg
, args
)
93 selector
= HTML
::Selector.new(*arg
)
96 else raise ArgumentError
, "Expecting a selector as the first argument"
103 # assert_select(selector, equality?, message?)
104 # assert_select(element, selector, equality?, message?)
106 # An assertion that selects elements and makes one or more equality tests.
108 # If the first argument is an element, selects all matching elements
109 # starting from (and including) that element and all its children in
112 # If no element if specified, calling +assert_select+ selects from the
113 # response HTML unless +assert_select+ is called from within an +assert_select+ block.
115 # When called with a block +assert_select+ passes an array of selected elements
116 # to the block. Calling +assert_select+ from the block, with no element specified,
117 # runs the assertion on the complete set of elements selected by the enclosing assertion.
118 # Alternatively the array may be iterated through so that +assert_select+ can be called
119 # separately for each element.
123 # If the response contains two ordered lists, each with four list elements then:
124 # assert_select "ol" do |elements|
125 # elements.each do |element|
126 # assert_select element, "li", 4
130 # will pass, as will:
131 # assert_select "ol" do
132 # assert_select "li", 8
135 # The selector may be a CSS selector expression (String), an expression
136 # with substitution values, or an HTML::Selector object.
140 # The equality test may be one of the following:
141 # * <tt>true</tt> - Assertion is true if at least one element selected.
142 # * <tt>false</tt> - Assertion is true if no element selected.
143 # * <tt>String/Regexp</tt> - Assertion is true if the text value of at least
144 # one element matches the string or regular expression.
145 # * <tt>Integer</tt> - Assertion is true if exactly that number of
146 # elements are selected.
147 # * <tt>Range</tt> - Assertion is true if the number of selected
148 # elements fit the range.
149 # If no equality test specified, the assertion is true if at least one
152 # To perform more than one equality tests, use a hash with the following keys:
153 # * <tt>:text</tt> - Narrow the selection to elements that have this text
154 # value (string or regexp).
155 # * <tt>:html</tt> - Narrow the selection to elements that have this HTML
156 # content (string or regexp).
157 # * <tt>:count</tt> - Assertion is true if the number of selected elements
158 # is equal to this value.
159 # * <tt>:minimum</tt> - Assertion is true if the number of selected
160 # elements is at least this value.
161 # * <tt>:maximum</tt> - Assertion is true if the number of selected
162 # elements is at most this value.
164 # If the method is called with a block, once all equality tests are
165 # evaluated the block is called with an array of all matched elements.
169 # # At least one form element
170 # assert_select "form"
172 # # Form element includes four input fields
173 # assert_select "form input", 4
175 # # Page title is "Welcome"
176 # assert_select "title", "Welcome"
178 # # Page title is "Welcome" and there is only one title element
179 # assert_select "title", {:count=>1, :text=>"Welcome"},
180 # "Wrong title or more than one title element"
182 # # Page contains no forms
183 # assert_select "form", false, "This page must contain no forms"
185 # # Test the content and style
186 # assert_select "body div.header ul.menu"
188 # # Use substitution values
189 # assert_select "ol>li#?", /item-\d+/
191 # # All input fields in the form have a name
192 # assert_select "form input" do
193 # assert_select "[name=?]", /.+/ # Not empty
195 def assert_select(*args
, &block
)
196 # Start with optional element followed by mandatory selector.
199 if arg
.is_a
?(HTML
::Node)
200 # First argument is a node (tag or text, but also HTML root),
201 # so we know what we're selecting from.
205 # This usually happens when passing a node/element that
207 raise ArgumentError
, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
209 root
= HTML
::Node.new(nil)
210 root
.children
.concat
@selected
212 # Otherwise just operate on the response document.
213 root
= response_from_page_or_rjs
216 # First or second argument is the selector: string and we pass
217 # all remaining arguments. Array and we pass the argument. Also
218 # accepts selector itself.
221 selector
= HTML
::Selector.new(arg
, args
)
223 selector
= HTML
::Selector.new(*arg
)
226 else raise ArgumentError
, "Expecting a selector as the first argument"
229 # Next argument is used for equality tests.
231 case arg
= args
.shift
239 equals
[:minimum] = arg
.begin
240 equals
[:maximum] = arg
.end
243 when NilClass
, TrueClass
245 else raise ArgumentError
, "I don't understand what you're trying to match"
248 # By default we're looking for at least one match.
250 equals
[:minimum] = equals
[:maximum] = equals
[:count]
252 equals
[:minimum] = 1 unless equals
[:minimum]
255 # Last argument is the message we use if the assertion fails.
257 #- message = "No match made with selector #{selector.inspect}" unless message
259 raise ArgumentError
, "Not expecting that last argument, you either have too many arguments, or they're the wrong type"
262 matches
= selector
.select(root
)
263 # If text/html, narrow down to those elements that match it.
264 content_mismatch
= nil
265 if match_with
= equals
[:text]
266 matches
.delete_if
do |match
|
268 text
.force_encoding(match_with
.encoding
) if text
.respond_to
?(:force_encoding)
269 stack
= match
.children
.reverse
270 while node
= stack
.pop
272 stack
.concat node
.children
.reverse
274 content
= node
.content
275 content
.force_encoding(match_with
.encoding
) if content
.respond_to
?(:force_encoding)
279 text
.strip
! unless NO_STRIP
.include?(match
.name
)
280 unless match_with
.is_a
?(Regexp
) ? (text
=~ match_with
) : (text
== match_with
.to_s
)
281 content_mismatch
||= build_message(message
, "<?> expected but was\n<?>.", match_with
, text
)
285 elsif match_with
= equals
[:html]
286 matches
.delete_if
do |match
|
287 html
= match
.children
.map(&:to_s).join
288 html
.strip
! unless NO_STRIP
.include?(match
.name
)
289 unless match_with
.is_a
?(Regexp
) ? (html
=~ match_with
) : (html
== match_with
.to_s
)
290 content_mismatch
||= build_message(message
, "<?> expected but was\n<?>.", match_with
, html
)
295 # Expecting foo found bar element only if found zero, not if
296 # found one but expecting two.
297 message
||= content_mismatch
if matches
.empty
?
298 # Test minimum/maximum occurrence.
299 min
, max
= equals
[:minimum], equals
[:maximum]
300 message
= message
|| %(Expected #{count_description(min, max)} matching "#{selector.to_s}", found #{matches.size}.)
301 assert matches.size >= min, message if min
302 assert matches.size <= max, message if max
304 # If a block is given call that block. Set @selected to allow
305 # nested assert_select, which can be nested several levels deep.
306 if block_given? && !matches.empty?
308 in_scope, @selected = @selected, matches
315 # Returns all matches elements.
319 def count_description(min, max) #:nodoc:
320 pluralize = lambda {|word, quantity| word << (quantity == 1 ? '' : 's')}
322 if min && max && (max != min)
323 "between #{min} and #{max} elements"
324 elsif min && !(min == 1 && max == 1)
325 "at least #{min} #{pluralize['element', min]}"
327 "at most #{max} #{pluralize['element', max]}"
332 # assert_select_rjs(id?) { |elements| ... }
333 # assert_select_rjs(statement, id?) { |elements| ... }
334 # assert_select_rjs(:insert, position, id?) { |elements| ... }
336 # Selects content from the RJS response.
340 # With no arguments, asserts that one or more elements are updated or
341 # inserted by RJS statements.
343 # Use the +id+ argument to narrow down the assertion to only statements
344 # that update or insert an element with that identifier.
346 # Use the first argument to narrow down assertions to only statements
347 # of that type. Possible values are <tt>:replace</tt>, <tt>:replace_html</tt>,
348 # <tt>:show</tt>, <tt>:hide</tt>, <tt>:toggle</tt>, <tt>:remove</tt> and
349 # <tt>:insert_html</tt>.
351 # Use the argument <tt>:insert</tt> followed by an insertion position to narrow
352 # down the assertion to only statements that insert elements in that
353 # position. Possible values are <tt>:top</tt>, <tt>:bottom</tt>, <tt>:before</tt>
354 # and <tt>:after</tt>.
356 # Using the <tt>:remove</tt> statement, you will be able to pass a block, but it will
357 # be ignored as there is no HTML passed for this statement.
361 # Without a block, +assert_select_rjs+ merely asserts that the response
362 # contains one or more RJS statements that replace or update content.
364 # With a block, +assert_select_rjs+ also selects all elements used in
365 # these statements and passes them to the block. Nested assertions are
368 # Calling +assert_select_rjs+ with no arguments and using nested asserts
369 # asserts that the HTML content is returned by one or more RJS statements.
370 # Using +assert_select+ directly makes the same assertion on the content,
371 # but without distinguishing whether the content is returned in an HTML
376 # # Replacing the element foo.
377 # # page.replace 'foo', ...
378 # assert_select_rjs :replace, "foo"
380 # # Replacing with the chained RJS proxy.
381 # # page[:foo].replace ...
382 # assert_select_rjs :chained_replace, 'foo'
384 # # Inserting into the element bar, top position.
385 # assert_select_rjs :insert, :top, "bar"
387 # # Remove the element bar
388 # assert_select_rjs :remove, "bar"
390 # # Changing the element foo, with an image.
391 # assert_select_rjs "foo" do
392 # assert_select "img[src=/images/logo.gif""
395 # # RJS inserts or updates a list with four items.
396 # assert_select_rjs do
397 # assert_select "ol>li", 4
400 # # The same, but shorter.
401 # assert_select "ol>li", 4
402 def assert_select_rjs(*args, &block)
403 rjs_type = args.first.is_a?(Symbol) ? args.shift : nil
404 id = args.first.is_a?(String) ? args.shift : nil
406 # If the first argument is a symbol, it's the type of RJS statement we're looking
407 # for (update, replace, insertion, etc). Otherwise, we're looking for just about
410 if rjs_type == :insert
411 position = args.shift
413 insertion = "insert_#{position}".to_sym
414 raise ArgumentError, "Unknown RJS insertion type #{position}" unless RJS_STATEMENTS[insertion]
415 statement = "(#{RJS_STATEMENTS[insertion]})"
417 raise ArgumentError, "Unknown RJS statement type #{rjs_type}" unless RJS_STATEMENTS[rjs_type]
418 statement = "(#{RJS_STATEMENTS[rjs_type]})"
421 statement = "#{RJS_STATEMENTS[:any]}"
424 # Next argument we're looking for is the element identifier. If missing, we pick
425 # any element, otherwise we replace it in the statement.
426 pattern = Regexp.new(
427 id ? statement.gsub(RJS_ANY_ID, "\"#{id}\"") : statement
430 # Duplicate the body since the next step involves destroying it.
433 when :remove, :show, :hide, :toggle
434 matches = @response.body.match(pattern)
436 @response.body.gsub(pattern) do |match|
437 html = unescape_rjs(match)
439 matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? }
445 assert_block("") { true } # to count the assertion
446 if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type)
448 in_scope, @selected = @selected, matches
456 # RJS statement not found.
458 when :remove, :show, :hide, :toggle
459 flunk_message = "No RJS statement that #{rjs_type.to_s}s '#{id}' was rendered."
461 flunk_message = "No RJS statement that replaces or inserts HTML content."
463 flunk args.shift || flunk_message
468 # assert_select_encoded(element?) { |elements| ... }
470 # Extracts the content of an element, treats it as encoded HTML and runs
471 # nested assertion on it.
473 # You typically call this method within another assertion to operate on
474 # all currently selected elements. You can also pass an element or array
477 # The content of each element is un-encoded, and wrapped in the root
478 # element +encoded+. It then calls the block with all un-encoded elements.
481 # # Selects all bold tags from within the title of an ATOM feed's entries (perhaps to nab a section name prefix)
482 # assert_select_feed :atom, 1.0 do
483 # # Select each entry item and then the title item
484 # assert_select "entry>title" do
485 # # Run assertions on the encoded title elements
486 # assert_select_encoded do
493 # # Selects all paragraph tags from within the description of an RSS feed
494 # assert_select_feed :rss, 2.0 do
495 # # Select description element of each feed item.
496 # assert_select "channel>item>description" do
497 # # Run assertions on the encoded elements.
498 # assert_select_encoded do
503 def assert_select_encoded(element = nil, &block)
510 unless elements = @selected
511 raise ArgumentError, "First argument is optional, but must be called from a nested assert_select"
514 raise ArgumentError, "Argument is optional, and may be node or array of nodes"
517 fix_content = lambda do |node|
518 # Gets around a bug in the Rails 1.1 HTML parser.
519 node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { CGI.escapeHTML($1) }
522 selected = elements.map do |element|
523 text = element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join
524 root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root
525 css_select(root, "encoded:root", &block)[0]
529 old_selected, @selected = @selected, selected
530 assert_select ":root", &block
532 @selected = old_selected
537 # assert_select_email { }
539 # Extracts the body of an email and runs nested assertions on it.
541 # You must enable deliveries for this assertion to work, use:
542 # ActionMailer::Base.perform_deliveries = true
546 # assert_select_email do
547 # assert_select "h1", "Email alert"
550 # assert_select_email do
551 # items = assert_select "ol>li"
553 # # Work with items here...
557 def assert_select_email(&block)
558 deliveries = ActionMailer::Base.deliveries
559 assert !deliveries.empty?, "No e-mail in delivery list"
561 for delivery in deliveries
562 for part in delivery.parts
563 if part["Content-Type"].to_s =~ /^text\/html\W/
564 root = HTML::Document.new(part.body).root
565 assert_select root, ":root", &block
572 unless const_defined?(:RJS_STATEMENTS)
573 RJS_PATTERN_HTML = "\"((\\\\\"|[^\"])*)\""
574 RJS_ANY_ID = "\"([^\"])*\""
576 :chained_replace => "\\$\\(#{RJS_ANY_ID}\\)\\.replace\\(#{RJS_PATTERN_HTML}\\)",
577 :chained_replace_html => "\\$\\(#{RJS_ANY_ID}\\)\\.update\\(#{RJS_PATTERN_HTML}\\)",
578 :replace_html => "Element\\.update\\(#{RJS_ANY_ID}, #{RJS_PATTERN_HTML}\\)",
579 :replace => "Element\\.replace\\(#{RJS_ANY_ID}, #{RJS_PATTERN_HTML}\\)"
581 [:remove, :show, :hide, :toggle].each do |action|
582 RJS_STATEMENTS[action] = "Element\\.#{action}\\(#{RJS_ANY_ID}\\)"
584 RJS_INSERTIONS = ["top", "bottom", "before", "after"]
585 RJS_INSERTIONS.each do |insertion|
586 RJS_STATEMENTS["insert_#{insertion}".to_sym] = "Element.insert\\(#{RJS_ANY_ID}, \\{ #{insertion}: #{RJS_PATTERN_HTML} \\}\\)"
588 RJS_STATEMENTS[:insert_html] = "Element.insert\\(#{RJS_ANY_ID}, \\{ (#{RJS_INSERTIONS.join('|')}): #{RJS_PATTERN_HTML} \\}\\)"
589 RJS_STATEMENTS[:any] = Regexp.new("(#{RJS_STATEMENTS.values.join('|')})")
590 RJS_PATTERN_UNICODE_ESCAPED_CHAR = /\\u([0-9a-zA-Z]{4})/
593 # +assert_select+ and +css_select+ call this to obtain the content in the HTML
594 # page, or from all the RJS statements, depending on the type of response.
595 def response_from_page_or_rjs()
596 content_type = @response.content_type
598 if content_type && Mime::JS =~ content_type
599 body = @response.body.dup
600 root = HTML::Node.new(nil)
603 next if body.sub!(RJS_STATEMENTS[:any]) do |match|
604 html = unescape_rjs(match)
605 matches = HTML::Document.new(html).root.children.select { |n| n.tag? }
606 root.children.concat matches
618 # Unescapes a RJS string.
619 def unescape_rjs(rjs_string)
620 # RJS encodes double quotes and line breaks.
621 unescaped= rjs_string.gsub('\"', '"')
622 unescaped.gsub!(/\\\//, '/')
623 unescaped.gsub!('\n', "\n")
624 unescaped.gsub!('\076', '>')
625 unescaped.gsub!('\074', '<')
626 # RJS encodes non-ascii characters.
627 unescaped.gsub!(RJS_PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')}