2 # Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
3 # Under MIT and/or CC By license.
6 require 'rexml/document'
7 require 'html/document'
9 module ActionController
11 unless const_defined?(:NO_STRIP)
12 NO_STRIP = %w{pre script style textarea}
15 # Adds the #assert_select method for use in Rails functional
18 # Use #assert_select to make assertions on the response HTML of a controller
19 # action. You can also call #assert_select within another #assert_select to
20 # make assertions on elements selected by the enclosing assertion.
22 # Use #css_select to select elements without making an assertions, either
23 # from the response HTML or elements selected by the enclosing assertion.
25 # In addition to HTML responses, you can make the following assertions:
26 # * #assert_select_rjs -- Assertions on HTML content of RJS update and
27 # insertion operations.
28 # * #assert_select_encoded -- Assertions on HTML encoded inside XML,
29 # for example for dealing with feed item descriptions.
30 # * #assert_select_email -- Assertions on the HTML body of an e-mail.
32 # Also see HTML::Selector for learning how to use selectors.
33 module SelectorAssertions
35 # css_select(selector) => array
36 # css_select(element, selector) => array
38 # Select and return all matching elements.
40 # If called with a single argument, uses that argument as a selector
41 # to match all elements of the current page. Returns an empty array
42 # if no match is found.
44 # If called with two arguments, uses the first argument as the base
45 # element and the second argument as the selector. Attempts to match the
46 # base element and any of its children. Returns an empty array if no
49 # The selector may be a CSS selector expression (+String+), an expression
50 # with substitution values (+Array+) or an HTML::Selector object.
53 # forms = css_select("form")
54 # forms.each do |form|
55 # inputs = css_select(form, "input")
59 # See assert_select to understand what's going on here.
62 if arg.is_a?(HTML::Node)
66 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?"
70 @selected.each do |selected|
71 subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup))
72 subset.each do |match|
73 matches << match unless matches.any? { |m| m.equal?(match) }
79 root = response_from_page_or_rjs
84 selector = HTML::Selector.new(arg, args)
86 selector = HTML::Selector.new(*arg)
89 else raise ArgumentError, "Expecting a selector as the first argument"
96 # assert_select(selector, equality?, message?)
97 # assert_select(element, selector, equality?, message?)
99 # An assertion that selects elements and makes one or more equality tests.
101 # If the first argument is an element, selects all matching elements
102 # starting from (and including) that element and all its children in
105 # If no element if specified, calling #assert_select will select from the
106 # response HTML. Calling #assert_select inside an #assert_select block will
107 # run the assertion for each element selected by the enclosing assertion.
110 # assert_select "ol>li" do |elements|
111 # elements.each do |element|
112 # assert_select element, "li"
116 # assert_select "ol>li" do
120 # The selector may be a CSS selector expression (+String+), an expression
121 # with substitution values, or an HTML::Selector object.
125 # The equality test may be one of the following:
126 # * <tt>true</tt> -- Assertion is true if at least one element selected.
127 # * <tt>false</tt> -- Assertion is true if no element selected.
128 # * <tt>String/Regexp</tt> -- Assertion is true if the text value of at least
129 # one element matches the string or regular expression.
130 # * <tt>Integer</tt> -- Assertion is true if exactly that number of
131 # elements are selected.
132 # * <tt>Range</tt> -- Assertion is true if the number of selected
133 # elements fit the range.
134 # If no equality test specified, the assertion is true if at least one
137 # To perform more than one equality tests, use a hash with the following keys:
138 # * <tt>:text</tt> -- Narrow the selection to elements that have this text
139 # value (string or regexp).
140 # * <tt>:html</tt> -- Narrow the selection to elements that have this HTML
141 # content (string or regexp).
142 # * <tt>:count</tt> -- Assertion is true if the number of selected elements
143 # is equal to this value.
144 # * <tt>:minimum</tt> -- Assertion is true if the number of selected
145 # elements is at least this value.
146 # * <tt>:maximum</tt> -- Assertion is true if the number of selected
147 # elements is at most this value.
149 # If the method is called with a block, once all equality tests are
150 # evaluated the block is called with an array of all matched elements.
154 # # At least one form element
155 # assert_select "form"
157 # # Form element includes four input fields
158 # assert_select "form input", 4
160 # # Page title is "Welcome"
161 # assert_select "title", "Welcome"
163 # # Page title is "Welcome" and there is only one title element
164 # assert_select "title", {:count=>1, :text=>"Welcome"},
165 # "Wrong title or more than one title element"
167 # # Page contains no forms
168 # assert_select "form", false, "This page must contain no forms"
170 # # Test the content and style
171 # assert_select "body div.header ul.menu"
173 # # Use substitution values
174 # assert_select "ol>li#?", /item-\d+/
176 # # All input fields in the form have a name
177 # assert_select "form input" do
178 # assert_select "[name=?]", /.+/ # Not empty
180 def assert_select(*args, &block)
181 # Start with optional element followed by mandatory selector.
184 if arg.is_a?(HTML::Node)
185 # First argument is a node (tag or text, but also HTML root),
186 # so we know what we're selecting from.
190 # This usually happens when passing a node/element that
192 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?"
194 root = HTML::Node.new(nil)
195 root.children.concat @selected
197 # Otherwise just operate on the response document.
198 root = response_from_page_or_rjs
201 # First or second argument is the selector: string and we pass
202 # all remaining arguments. Array and we pass the argument. Also
203 # accepts selector itself.
206 selector = HTML::Selector.new(arg, args)
208 selector = HTML::Selector.new(*arg)
211 else raise ArgumentError, "Expecting a selector as the first argument"
214 # Next argument is used for equality tests.
216 case arg = args.shift
224 equals[:minimum] = arg.begin
225 equals[:maximum] = arg.end
228 when NilClass, TrueClass
230 else raise ArgumentError, "I don't understand what you're trying to match"
233 # By default we're looking for at least one match.
235 equals[:minimum] = equals[:maximum] = equals[:count]
237 equals[:minimum] = 1 unless equals[:minimum]
240 # Last argument is the message we use if the assertion fails.
242 #- message = "No match made with selector #{selector.inspect}" unless message
244 raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type"
247 matches = selector.select(root)
248 # If text/html, narrow down to those elements that match it.
249 content_mismatch = nil
250 if match_with = equals[:text]
251 matches.delete_if do |match|
253 stack = match.children.reverse
254 while node = stack.pop
256 stack.concat node.children.reverse
261 text.strip! unless NO_STRIP.include?(match.name)
262 unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s)
263 content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, text)
267 elsif match_with = equals[:html]
268 matches.delete_if do |match|
269 html = match.children.map(&:to_s).join
270 html.strip! unless NO_STRIP.include?(match.name)
271 unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s)
272 content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, html)
277 # Expecting foo found bar element only if found zero, not if
278 # found one but expecting two.
279 message ||= content_mismatch if matches.empty?
280 # Test minimum/maximum occurrence.
281 min, max = equals[:minimum], equals[:maximum]
282 message = message || %(Expected #{count_description(min, max)} matching "#{selector.to_s}", found #{matches.size}.)
283 assert matches.size >= min, message if min
284 assert matches.size <= max, message if max
286 # If a block is given call that block. Set @selected to allow
287 # nested assert_select, which can be nested several levels deep.
288 if block_given? && !matches.empty?
290 in_scope, @selected = @selected, matches
297 # Returns all matches elements.
301 def count_description(min, max) #:nodoc:
302 pluralize = lambda {|word, quantity| word << (quantity == 1 ? '' : 's')}
304 if min && max && (max != min)
305 "between #{min} and #{max} elements"
306 elsif min && !(min == 1 && max == 1)
307 "at least #{min} #{pluralize['element', min]}"
309 "at most #{max} #{pluralize['element', max]}"
314 # assert_select_rjs(id?) { |elements| ... }
315 # assert_select_rjs(statement, id?) { |elements| ... }
316 # assert_select_rjs(:insert, position, id?) { |elements| ... }
318 # Selects content from the RJS response.
322 # With no arguments, asserts that one or more elements are updated or
323 # inserted by RJS statements.
325 # Use the +id+ argument to narrow down the assertion to only statements
326 # that update or insert an element with that identifier.
328 # Use the first argument to narrow down assertions to only statements
329 # of that type. Possible values are <tt>:replace</tt>, <tt>:replace_html</tt>,
330 # <tt>:show</tt>, <tt>:hide</tt>, <tt>:toggle</tt>, <tt>:remove</tt> and
331 # <tt>:insert_html</tt>.
333 # Use the argument <tt>:insert</tt> followed by an insertion position to narrow
334 # down the assertion to only statements that insert elements in that
335 # position. Possible values are <tt>:top</tt>, <tt>:bottom</tt>, <tt>:before</tt>
336 # and <tt>:after</tt>.
338 # Using the <tt>:remove</tt> statement, you will be able to pass a block, but it will
339 # be ignored as there is no HTML passed for this statement.
343 # Without a block, #assert_select_rjs merely asserts that the response
344 # contains one or more RJS statements that replace or update content.
346 # With a block, #assert_select_rjs also selects all elements used in
347 # these statements and passes them to the block. Nested assertions are
350 # Calling #assert_select_rjs with no arguments and using nested asserts
351 # asserts that the HTML content is returned by one or more RJS statements.
352 # Using #assert_select directly makes the same assertion on the content,
353 # but without distinguishing whether the content is returned in an HTML
358 # # Replacing the element foo.
359 # # page.replace 'foo', ...
360 # assert_select_rjs :replace, "foo"
362 # # Replacing with the chained RJS proxy.
363 # # page[:foo].replace ...
364 # assert_select_rjs :chained_replace, 'foo'
366 # # Inserting into the element bar, top position.
367 # assert_select_rjs :insert, :top, "bar"
369 # # Remove the element bar
370 # assert_select_rjs :remove, "bar"
372 # # Changing the element foo, with an image.
373 # assert_select_rjs "foo" do
374 # assert_select "img[src=/images/logo.gif""
377 # # RJS inserts or updates a list with four items.
378 # assert_select_rjs do
379 # assert_select "ol>li", 4
382 # # The same, but shorter.
383 # assert_select "ol>li", 4
384 def assert_select_rjs(*args, &block)
388 # If the first argument is a symbol, it's the type of RJS statement we're looking
389 # for (update, replace, insertion, etc). Otherwise, we're looking for just about
394 if rjs_type == :insert
396 insertion = "insert_#{arg}".to_sym
397 raise ArgumentError, "Unknown RJS insertion type #{arg}" unless RJS_STATEMENTS[insertion]
398 statement = "(#{RJS_STATEMENTS[insertion]})"
400 raise ArgumentError, "Unknown RJS statement type #{rjs_type}" unless RJS_STATEMENTS[rjs_type]
401 statement = "(#{RJS_STATEMENTS[rjs_type]})"
405 statement = "#{RJS_STATEMENTS[:any]}"
408 # Next argument we're looking for is the element identifier. If missing, we pick
411 id = Regexp.quote(arg)
419 when :chained_replace, :chained_replace_html
420 Regexp.new("\\$\\(\"#{id}\"\\)#{statement}\\(#{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE)
421 when :remove, :show, :hide, :toggle
422 Regexp.new("#{statement}\\(\"#{id}\"\\)")
424 Regexp.new("#{statement}\\(\"#{id}\", #{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE)
427 # Duplicate the body since the next step involves destroying it.
430 when :remove, :show, :hide, :toggle
431 matches = @response.body.match(pattern)
433 @response.body.gsub(pattern) do |match|
434 html = unescape_rjs($2)
436 matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? }
442 if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type)
444 in_scope, @selected = @selected, matches
452 # RJS statement not found.
453 flunk args.shift || "No RJS statement that replaces or inserts HTML content."
458 # assert_select_encoded(element?) { |elements| ... }
460 # Extracts the content of an element, treats it as encoded HTML and runs
461 # nested assertion on it.
463 # You typically call this method within another assertion to operate on
464 # all currently selected elements. You can also pass an element or array
467 # The content of each element is un-encoded, and wrapped in the root
468 # element +encoded+. It then calls the block with all un-encoded elements.
472 # assert_select_feed :rss, 2.0 do
473 # # Select description element of each feed item.
474 # assert_select "channel>item>description" do
475 # # Run assertions on the encoded elements.
476 # assert_select_encoded do
481 def assert_select_encoded(element = nil, &block)
488 unless elements = @selected
489 raise ArgumentError, "First argument is optional, but must be called from a nested assert_select"
492 raise ArgumentError, "Argument is optional, and may be node or array of nodes"
495 fix_content = lambda do |node|
496 # Gets around a bug in the Rails 1.1 HTML parser.
497 node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { CGI.escapeHTML($1) }
500 selected = elements.map do |element|
501 text = element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join
502 root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root
503 css_select(root, "encoded:root", &block)[0]
507 old_selected, @selected = @selected, selected
508 assert_select ":root", &block
510 @selected = old_selected
515 # assert_select_email { }
517 # Extracts the body of an email and runs nested assertions on it.
519 # You must enable deliveries for this assertion to work, use:
520 # ActionMailer::Base.perform_deliveries = true
524 # assert_select_email do
525 # assert_select "h1", "Email alert"
527 def assert_select_email(&block)
528 deliveries = ActionMailer::Base.deliveries
529 assert !deliveries.empty?, "No e-mail in delivery list"
531 for delivery in deliveries
532 for part in delivery.parts
533 if part["Content-Type"].to_s =~ /^text\/html\W/
534 root = HTML::Document.new(part.body).root
535 assert_select root, ":root", &block
542 unless const_defined?(:RJS_STATEMENTS)
544 :replace => /Element\.replace/,
545 :replace_html => /Element\.update/,
546 :chained_replace => /\.replace/,
547 :chained_replace_html => /\.update/,
548 :remove => /Element\.remove/,
549 :show => /Element\.show/,
550 :hide => /Element\.hide/,
551 :toggle => /Element\.toggle/
553 RJS_INSERTIONS = [:top, :bottom, :before, :after]
554 RJS_INSERTIONS.each do |insertion|
555 RJS_STATEMENTS["insert_#{insertion}".to_sym] = Regexp.new(Regexp.quote("new Insertion.#{insertion.to_s.camelize}"))
557 RJS_STATEMENTS[:any] = Regexp.new("(#{RJS_STATEMENTS.values.join('|')})")
558 RJS_STATEMENTS[:insert_html] = Regexp.new(RJS_INSERTIONS.collect do |insertion|
559 Regexp.quote("new Insertion.#{insertion.to_s.camelize}")
561 RJS_PATTERN_HTML = /"((\\"|[^"])*)"/
562 RJS_PATTERN_EVERYTHING = Regexp.new("#{RJS_STATEMENTS[:any]}\\(\"([^\"]*)\", #{RJS_PATTERN_HTML}\\)",
564 RJS_PATTERN_UNICODE_ESCAPED_CHAR = /\\u([0-9a-zA-Z]{4})/
567 # #assert_select and #css_select call this to obtain the content in the HTML
568 # page, or from all the RJS statements, depending on the type of response.
569 def response_from_page_or_rjs()
570 content_type = @response.content_type
572 if content_type && content_type =~ /text\/javascript/
573 body = @response.body.dup
574 root = HTML::Node.new(nil)
577 next if body.sub!(RJS_PATTERN_EVERYTHING) do |match|
578 html = unescape_rjs($3)
579 matches = HTML::Document.new(html).root.children.select { |n| n.tag? }
580 root.children.concat matches
592 # Unescapes a RJS string.
593 def unescape_rjs(rjs_string)
594 # RJS encodes double quotes and line breaks.
595 unescaped= rjs_string.gsub('\"', '"')
596 unescaped.gsub!(/\\\//, '/')
597 unescaped.gsub!('\n', "\n")
598 unescaped.gsub!('\076', '>')
599 unescaped.gsub!('\074', '<')
600 # RJS encodes non-ascii characters.
601 unescaped.gsub!(RJS_PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')}