Upgraded Rails and RSpec
[monkeycharger.git] / vendor / rails / actionpack / lib / action_controller / assertions / selector_assertions.rb
blobf70186fe173f96f222a37cc34630ad07248f64f5
1 #--
2 # Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
3 # Under MIT and/or CC By license.
4 #++
6 require 'rexml/document'
7 require 'html/document'
9 module ActionController
10   module Assertions
11     unless const_defined?(:NO_STRIP)
12       NO_STRIP = %w{pre script style textarea}
13     end
15     # Adds the #assert_select method for use in Rails functional
16     # test cases.
17     #
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.
21     #
22     # Use #css_select to select elements without making an assertions, either
23     # from the response HTML or elements selected by the enclosing assertion.
24     #
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.
31     #
32     # Also see HTML::Selector for learning how to use selectors.
33     module SelectorAssertions
34       # :call-seq:
35       #   css_select(selector) => array
36       #   css_select(element, selector) => array
37       #
38       # Select and return all matching elements.
39       #
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.
43       #
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
47       # match is found.
48       #
49       # The selector may be a CSS selector expression (+String+), an expression
50       # with substitution values (+Array+) or an HTML::Selector object.
51       #
52       # For example:
53       #   forms = css_select("form")
54       #   forms.each do |form|
55       #     inputs = css_select(form, "input")
56       #     ...
57       #   end
58       def css_select(*args)
59         # See assert_select to understand what's going on here.
60         arg = args.shift
62         if arg.is_a?(HTML::Node)
63           root = arg
64           arg = args.shift
65         elsif arg == nil
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?"
67         elsif @selected
68           matches = []
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) }
74             end
75           end
77           return matches
78         else
79           root = response_from_page_or_rjs
80         end
82         case arg
83           when String
84             selector = HTML::Selector.new(arg, args)
85           when Array
86             selector = HTML::Selector.new(*arg)
87           when HTML::Selector
88             selector = arg
89           else raise ArgumentError, "Expecting a selector as the first argument"
90         end
92         selector.select(root)
93       end
95       # :call-seq:
96       #   assert_select(selector, equality?, message?)
97       #   assert_select(element, selector, equality?, message?)
98       #
99       # An assertion that selects elements and makes one or more equality tests.
100       #
101       # If the first argument is an element, selects all matching elements
102       # starting from (and including) that element and all its children in
103       # depth-first order.
104       #
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.
108       #
109       # For example:
110       #   assert_select "ol>li" do |elements|
111       #     elements.each do |element|
112       #       assert_select element, "li"
113       #     end
114       #   end
115       # Or for short:
116       #   assert_select "ol>li" do
117       #     assert_select "li"
118       #   end
119       #
120       # The selector may be a CSS selector expression (+String+), an expression
121       # with substitution values, or an HTML::Selector object.
122       #
123       # === Equality Tests
124       #
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
135       # element selected.
136       #
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.
148       #
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.
151       #
152       # === Examples
153       #
154       #   # At least one form element
155       #   assert_select "form"
156       #
157       #   # Form element includes four input fields
158       #   assert_select "form input", 4
159       #
160       #   # Page title is "Welcome"
161       #   assert_select "title", "Welcome"
162       #
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"
166       #
167       #   # Page contains no forms
168       #   assert_select "form", false, "This page must contain no forms"
169       #
170       #   # Test the content and style
171       #   assert_select "body div.header ul.menu"
172       #
173       #   # Use substitution values
174       #   assert_select "ol>li#?", /item-\d+/
175       #
176       #   # All input fields in the form have a name
177       #   assert_select "form input" do
178       #     assert_select "[name=?]", /.+/  # Not empty
179       #   end
180       def assert_select(*args, &block)
181         # Start with optional element followed by mandatory selector.
182         arg = args.shift
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.
187           root = arg
188           arg = args.shift
189         elsif arg == nil
190           # This usually happens when passing a node/element that
191           # happens to be nil.
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?"
193         elsif @selected
194           root = HTML::Node.new(nil)
195           root.children.concat @selected
196         else
197           # Otherwise just operate on the response document.
198           root = response_from_page_or_rjs
199         end
200         
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.
204         case arg
205           when String
206             selector = HTML::Selector.new(arg, args)
207           when Array
208             selector = HTML::Selector.new(*arg)
209           when HTML::Selector
210             selector = arg
211           else raise ArgumentError, "Expecting a selector as the first argument"
212         end
213         
214         # Next argument is used for equality tests.
215         equals = {}
216         case arg = args.shift
217           when Hash
218             equals = arg
219           when String, Regexp
220             equals[:text] = arg
221           when Integer
222             equals[:count] = arg
223           when Range
224             equals[:minimum] = arg.begin
225             equals[:maximum] = arg.end
226           when FalseClass
227             equals[:count] = 0
228           when NilClass, TrueClass
229             equals[:minimum] = 1
230           else raise ArgumentError, "I don't understand what you're trying to match"
231         end
233         # By default we're looking for at least one match.
234         if equals[:count]
235           equals[:minimum] = equals[:maximum] = equals[:count]
236         else
237           equals[:minimum] = 1 unless equals[:minimum]
238         end
240         # Last argument is the message we use if the assertion fails.
241         message = args.shift
242         #- message = "No match made with selector #{selector.inspect}" unless message
243         if args.shift
244           raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type"
245         end
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|
252             text = ""
253             stack = match.children.reverse
254             while node = stack.pop
255               if node.tag?
256                 stack.concat node.children.reverse
257               else
258                 text << node.content
259               end
260             end
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)
264               true
265             end
266           end
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)
273               true
274             end
275           end
276         end
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?
289           begin
290             in_scope, @selected = @selected, matches
291             yield matches
292           ensure
293             @selected = in_scope
294           end
295         end
297         # Returns all matches elements.
298         matches
299       end
300       
301       def count_description(min, max) #:nodoc:
302         pluralize = lambda {|word, quantity| word << (quantity == 1 ? '' : 's')}
303         
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]}"
308         elsif max
309           "at most #{max} #{pluralize['element', max]}"
310         end
311       end
312       
313       # :call-seq:
314       #   assert_select_rjs(id?) { |elements| ... }
315       #   assert_select_rjs(statement, id?) { |elements| ... }
316       #   assert_select_rjs(:insert, position, id?) { |elements| ... }
317       #
318       # Selects content from the RJS response.
319       #
320       # === Narrowing down
321       #
322       # With no arguments, asserts that one or more elements are updated or
323       # inserted by RJS statements.
324       #
325       # Use the +id+ argument to narrow down the assertion to only statements
326       # that update or insert an element with that identifier.
327       #
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>.
332       #
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>.
337       #
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.
340       #
341       # === Using blocks
342       #
343       # Without a block, #assert_select_rjs merely asserts that the response
344       # contains one or more RJS statements that replace or update content.
345       #
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
348       # supported.
349       #
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
354       # or JavaScript.
355       #
356       # === Examples
357       #
358       #   # Replacing the element foo.
359       #   # page.replace 'foo', ...
360       #   assert_select_rjs :replace, "foo"
361       #
362       #   # Replacing with the chained RJS proxy.
363       #   # page[:foo].replace ...
364       #   assert_select_rjs :chained_replace, 'foo'
365       #
366       #   # Inserting into the element bar, top position.
367       #   assert_select_rjs :insert, :top, "bar"
368       #
369       #   # Remove the element bar
370       #   assert_select_rjs :remove, "bar"
371       #
372       #   # Changing the element foo, with an image.
373       #   assert_select_rjs "foo" do
374       #     assert_select "img[src=/images/logo.gif""
375       #   end
376       #
377       #   # RJS inserts or updates a list with four items.
378       #   assert_select_rjs do
379       #     assert_select "ol>li", 4
380       #   end
381       #
382       #   # The same, but shorter.
383       #   assert_select "ol>li", 4
384       def assert_select_rjs(*args, &block)
385         rjs_type = nil
386         arg      = args.shift
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
390         # any RJS statement.
391         if arg.is_a?(Symbol)
392           rjs_type = arg
394           if rjs_type == :insert
395             arg = args.shift
396             insertion = "insert_#{arg}".to_sym
397             raise ArgumentError, "Unknown RJS insertion type #{arg}" unless RJS_STATEMENTS[insertion]
398             statement = "(#{RJS_STATEMENTS[insertion]})"
399           else
400             raise ArgumentError, "Unknown RJS statement type #{rjs_type}" unless RJS_STATEMENTS[rjs_type]
401             statement = "(#{RJS_STATEMENTS[rjs_type]})"
402           end
403           arg = args.shift
404         else
405           statement = "#{RJS_STATEMENTS[:any]}"
406         end
408         # Next argument we're looking for is the element identifier. If missing, we pick
409         # any element.
410         if arg.is_a?(String)
411           id = Regexp.quote(arg)
412           arg = args.shift
413         else
414           id = "[^\"]*"
415         end
417         pattern =
418           case rjs_type
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}\"\\)")
423             else
424               Regexp.new("#{statement}\\(\"#{id}\", #{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE)
425           end
427         # Duplicate the body since the next step involves destroying it.
428         matches = nil
429         case rjs_type
430           when :remove, :show, :hide, :toggle
431             matches = @response.body.match(pattern)
432           else
433             @response.body.gsub(pattern) do |match|
434               html = unescape_rjs($2)
435               matches ||= []
436               matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? }
437               ""
438             end
439         end
441         if matches
442           if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type)
443             begin
444               in_scope, @selected = @selected, matches
445               yield matches
446             ensure
447               @selected = in_scope
448             end
449           end
450           matches
451         else
452           # RJS statement not found.
453           flunk args.shift || "No RJS statement that replaces or inserts HTML content."
454         end
455       end
457       # :call-seq:
458       #   assert_select_encoded(element?) { |elements| ... }
459       #
460       # Extracts the content of an element, treats it as encoded HTML and runs
461       # nested assertion on it.
462       #
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
465       # of elements.
466       #
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.
469       #
470       # === Example
471       #
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
477       #         assert_select "p"
478       #       end
479       #     end
480       #   end
481       def assert_select_encoded(element = nil, &block)
482         case element
483           when Array
484             elements = element
485           when HTML::Node
486             elements = [element]
487           when nil
488             unless elements = @selected
489               raise ArgumentError, "First argument is optional, but must be called from a nested assert_select"
490             end
491           else
492             raise ArgumentError, "Argument is optional, and may be node or array of nodes"
493         end
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) }
498         end
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]
504         end
506         begin
507           old_selected, @selected = @selected, selected
508           assert_select ":root", &block
509         ensure
510           @selected = old_selected
511         end
512       end
514       # :call-seq:
515       #   assert_select_email { }
516       #
517       # Extracts the body of an email and runs nested assertions on it.
518       #
519       # You must enable deliveries for this assertion to work, use:
520       #   ActionMailer::Base.perform_deliveries = true
521       #
522       # === Example
523       #
524       # assert_select_email do
525       #   assert_select "h1", "Email alert"
526       # end
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
536             end
537           end
538         end
539       end
541       protected
542         unless const_defined?(:RJS_STATEMENTS)
543           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/
552           }
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}"))
556           end
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}")
560           end.join('|'))
561           RJS_PATTERN_HTML = /"((\\"|[^"])*)"/
562           RJS_PATTERN_EVERYTHING = Regexp.new("#{RJS_STATEMENTS[:any]}\\(\"([^\"]*)\", #{RJS_PATTERN_HTML}\\)",
563                                               Regexp::MULTILINE)
564           RJS_PATTERN_UNICODE_ESCAPED_CHAR = /\\u([0-9a-zA-Z]{4})/
565         end
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)
576             while true
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
581                 ""
582               end
583               break
584             end
586             root
587           else
588             html_document.root
589           end
590         end
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*')}
602           unescaped
603         end
604     end
605   end