0d56ea5ef7828955d9e582c7805391ccaf3971f7
[feedcatcher.git] / vendor / rails / actionpack / lib / action_controller / assertions / selector_assertions.rb
1 #--
2 # Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
3 # Under MIT and/or CC By license.
4 #++
5
6 module ActionController
7 module Assertions
8 unless const_defined?(:NO_STRIP)
9 NO_STRIP = %w{pre script style textarea}
10 end
11
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.
16 #
17 # Use +css_select+ to select elements without making an assertions, either
18 # from the response HTML or elements selected by the enclosing assertion.
19 #
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.
24 #
25 # Also see HTML::Selector to learn how to use selectors.
26 module SelectorAssertions
27 # :call-seq:
28 # css_select(selector) => array
29 # css_select(element, selector) => array
30 #
31 # Select and return all matching elements.
32 #
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.
36 #
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
40 # match is found.
41 #
42 # The selector may be a CSS selector expression (String), an expression
43 # with substitution values (Array) or an HTML::Selector object.
44 #
45 # ==== Examples
46 # # Selects all div tags
47 # divs = css_select("div")
48 #
49 # # Selects all paragraph tags and does something interesting
50 # pars = css_select("p")
51 # pars.each do |par|
52 # # Do something fun with paragraphs here...
53 # end
54 #
55 # # Selects all list items in unordered lists
56 # items = css_select("ul>li")
57 #
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")
62 # ...
63 # end
64 #
65 def css_select(*args)
66 # See assert_select to understand what's going on here.
67 arg = args.shift
68
69 if arg.is_a?(HTML::Node)
70 root = arg
71 arg = args.shift
72 elsif arg == nil
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?"
74 elsif @selected
75 matches = []
76
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) }
81 end
82 end
83
84 return matches
85 else
86 root = response_from_page_or_rjs
87 end
88
89 case arg
90 when String
91 selector = HTML::Selector.new(arg, args)
92 when Array
93 selector = HTML::Selector.new(*arg)
94 when HTML::Selector
95 selector = arg
96 else raise ArgumentError, "Expecting a selector as the first argument"
97 end
98
99 selector.select(root)
100 end
101
102 # :call-seq:
103 # assert_select(selector, equality?, message?)
104 # assert_select(element, selector, equality?, message?)
105 #
106 # An assertion that selects elements and makes one or more equality tests.
107 #
108 # If the first argument is an element, selects all matching elements
109 # starting from (and including) that element and all its children in
110 # depth-first order.
111 #
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.
114 #
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.
120 #
121 #
122 # ==== Example
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
127 # end
128 # end
129 #
130 # will pass, as will:
131 # assert_select "ol" do
132 # assert_select "li", 8
133 # end
134 #
135 # The selector may be a CSS selector expression (String), an expression
136 # with substitution values, or an HTML::Selector object.
137 #
138 # === Equality Tests
139 #
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
150 # element selected.
151 #
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.
163 #
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.
166 #
167 # ==== Examples
168 #
169 # # At least one form element
170 # assert_select "form"
171 #
172 # # Form element includes four input fields
173 # assert_select "form input", 4
174 #
175 # # Page title is "Welcome"
176 # assert_select "title", "Welcome"
177 #
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"
181 #
182 # # Page contains no forms
183 # assert_select "form", false, "This page must contain no forms"
184 #
185 # # Test the content and style
186 # assert_select "body div.header ul.menu"
187 #
188 # # Use substitution values
189 # assert_select "ol>li#?", /item-\d+/
190 #
191 # # All input fields in the form have a name
192 # assert_select "form input" do
193 # assert_select "[name=?]", /.+/ # Not empty
194 # end
195 def assert_select(*args, &block)
196 # Start with optional element followed by mandatory selector.
197 arg = args.shift
198
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.
202 root = arg
203 arg = args.shift
204 elsif arg == nil
205 # This usually happens when passing a node/element that
206 # happens to be nil.
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?"
208 elsif @selected
209 root = HTML::Node.new(nil)
210 root.children.concat @selected
211 else
212 # Otherwise just operate on the response document.
213 root = response_from_page_or_rjs
214 end
215
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.
219 case arg
220 when String
221 selector = HTML::Selector.new(arg, args)
222 when Array
223 selector = HTML::Selector.new(*arg)
224 when HTML::Selector
225 selector = arg
226 else raise ArgumentError, "Expecting a selector as the first argument"
227 end
228
229 # Next argument is used for equality tests.
230 equals = {}
231 case arg = args.shift
232 when Hash
233 equals = arg
234 when String, Regexp
235 equals[:text] = arg
236 when Integer
237 equals[:count] = arg
238 when Range
239 equals[:minimum] = arg.begin
240 equals[:maximum] = arg.end
241 when FalseClass
242 equals[:count] = 0
243 when NilClass, TrueClass
244 equals[:minimum] = 1
245 else raise ArgumentError, "I don't understand what you're trying to match"
246 end
247
248 # By default we're looking for at least one match.
249 if equals[:count]
250 equals[:minimum] = equals[:maximum] = equals[:count]
251 else
252 equals[:minimum] = 1 unless equals[:minimum]
253 end
254
255 # Last argument is the message we use if the assertion fails.
256 message = args.shift
257 #- message = "No match made with selector #{selector.inspect}" unless message
258 if args.shift
259 raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type"
260 end
261
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|
267 text = ""
268 text.force_encoding(match_with.encoding) if text.respond_to?(:force_encoding)
269 stack = match.children.reverse
270 while node = stack.pop
271 if node.tag?
272 stack.concat node.children.reverse
273 else
274 content = node.content
275 content.force_encoding(match_with.encoding) if content.respond_to?(:force_encoding)
276 text << content
277 end
278 end
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)
282 true
283 end
284 end
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)
291 true
292 end
293 end
294 end
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
303
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?
307 begin
308 in_scope, @selected = @selected, matches
309 yield matches
310 ensure
311 @selected = in_scope
312 end
313 end
314
315 # Returns all matches elements.
316 matches
317 end
318
319 def count_description(min, max) #:nodoc:
320 pluralize = lambda {|word, quantity| word << (quantity == 1 ? '' : 's')}
321
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]}"
326 elsif max
327 "at most #{max} #{pluralize['element', max]}"
328 end
329 end
330
331 # :call-seq:
332 # assert_select_rjs(id?) { |elements| ... }
333 # assert_select_rjs(statement, id?) { |elements| ... }
334 # assert_select_rjs(:insert, position, id?) { |elements| ... }
335 #
336 # Selects content from the RJS response.
337 #
338 # === Narrowing down
339 #
340 # With no arguments, asserts that one or more elements are updated or
341 # inserted by RJS statements.
342 #
343 # Use the +id+ argument to narrow down the assertion to only statements
344 # that update or insert an element with that identifier.
345 #
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>.
350 #
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>.
355 #
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.
358 #
359 # === Using blocks
360 #
361 # Without a block, +assert_select_rjs+ merely asserts that the response
362 # contains one or more RJS statements that replace or update content.
363 #
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
366 # supported.
367 #
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
372 # or JavaScript.
373 #
374 # ==== Examples
375 #
376 # # Replacing the element foo.
377 # # page.replace 'foo', ...
378 # assert_select_rjs :replace, "foo"
379 #
380 # # Replacing with the chained RJS proxy.
381 # # page[:foo].replace ...
382 # assert_select_rjs :chained_replace, 'foo'
383 #
384 # # Inserting into the element bar, top position.
385 # assert_select_rjs :insert, :top, "bar"
386 #
387 # # Remove the element bar
388 # assert_select_rjs :remove, "bar"
389 #
390 # # Changing the element foo, with an image.
391 # assert_select_rjs "foo" do
392 # assert_select "img[src=/images/logo.gif""
393 # end
394 #
395 # # RJS inserts or updates a list with four items.
396 # assert_select_rjs do
397 # assert_select "ol>li", 4
398 # end
399 #
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
405
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
408 # any RJS statement.
409 if rjs_type
410 if rjs_type == :insert
411 position = args.shift
412 id = 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]})"
416 else
417 raise ArgumentError, "Unknown RJS statement type #{rjs_type}" unless RJS_STATEMENTS[rjs_type]
418 statement = "(#{RJS_STATEMENTS[rjs_type]})"
419 end
420 else
421 statement = "#{RJS_STATEMENTS[:any]}"
422 end
423
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
428 )
429
430 # Duplicate the body since the next step involves destroying it.
431 matches = nil
432 case rjs_type
433 when :remove, :show, :hide, :toggle
434 matches = @response.body.match(pattern)
435 else
436 @response.body.gsub(pattern) do |match|
437 html = unescape_rjs(match)
438 matches ||= []
439 matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? }
440 ""
441 end
442 end
443
444 if matches
445 assert_block("") { true } # to count the assertion
446 if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type)
447 begin
448 in_scope, @selected = @selected, matches
449 yield matches
450 ensure
451 @selected = in_scope
452 end
453 end
454 matches
455 else
456 # RJS statement not found.
457 case rjs_type
458 when :remove, :show, :hide, :toggle
459 flunk_message = "No RJS statement that #{rjs_type.to_s}s '#{id}' was rendered."
460 else
461 flunk_message = "No RJS statement that replaces or inserts HTML content."
462 end
463 flunk args.shift || flunk_message
464 end
465 end
466
467 # :call-seq:
468 # assert_select_encoded(element?) { |elements| ... }
469 #
470 # Extracts the content of an element, treats it as encoded HTML and runs
471 # nested assertion on it.
472 #
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
475 # of elements.
476 #
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.
479 #
480 # ==== Examples
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
487 # assert_select "b"
488 # end
489 # end
490 # end
491 #
492 #
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
499 # assert_select "p"
500 # end
501 # end
502 # end
503 def assert_select_encoded(element = nil, &block)
504 case element
505 when Array
506 elements = element
507 when HTML::Node
508 elements = [element]
509 when nil
510 unless elements = @selected
511 raise ArgumentError, "First argument is optional, but must be called from a nested assert_select"
512 end
513 else
514 raise ArgumentError, "Argument is optional, and may be node or array of nodes"
515 end
516
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) }
520 end
521
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]
526 end
527
528 begin
529 old_selected, @selected = @selected, selected
530 assert_select ":root", &block
531 ensure
532 @selected = old_selected
533 end
534 end
535
536 # :call-seq:
537 # assert_select_email { }
538 #
539 # Extracts the body of an email and runs nested assertions on it.
540 #
541 # You must enable deliveries for this assertion to work, use:
542 # ActionMailer::Base.perform_deliveries = true
543 #
544 # ==== Examples
545 #
546 # assert_select_email do
547 # assert_select "h1", "Email alert"
548 # end
549 #
550 # assert_select_email do
551 # items = assert_select "ol>li"
552 # items.each do
553 # # Work with items here...
554 # end
555 # end
556 #
557 def assert_select_email(&block)
558 deliveries = ActionMailer::Base.deliveries
559 assert !deliveries.empty?, "No e-mail in delivery list"
560
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
566 end
567 end
568 end
569 end
570
571 protected
572 unless const_defined?(:RJS_STATEMENTS)
573 RJS_PATTERN_HTML = "\"((\\\\\"|[^\"])*)\""
574 RJS_ANY_ID = "\"([^\"])*\""
575 RJS_STATEMENTS = {
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}\\)"
580 }
581 [:remove, :show, :hide, :toggle].each do |action|
582 RJS_STATEMENTS[action] = "Element\\.#{action}\\(#{RJS_ANY_ID}\\)"
583 end
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} \\}\\)"
587 end
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})/
591 end
592
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
597
598 if content_type && Mime::JS =~ content_type
599 body = @response.body.dup
600 root = HTML::Node.new(nil)
601
602 while true
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
607 ""
608 end
609 break
610 end
611
612 root
613 else
614 html_document.root
615 end
616 end
617
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*')}
628 unescaped
629 end
630 end
631 end
632 end