Module | ActionController::Assertions::SelectorAssertions |
In: |
vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb
|
Adds the assert_select method for use in Rails functional test cases, which can be used to make assertions on the response HTML of a controller action. You can also call assert_select within another assert_select to make assertions on elements selected by the enclosing assertion.
Use css_select to select elements without making an assertions, either from the response HTML or elements selected by the enclosing assertion.
In addition to HTML responses, you can make the following assertions:
insertion operations.
for example for dealing with feed item descriptions.
Also see HTML::Selector to learn how to use selectors.
RJS_STATEMENTS | = | { :replace => /Element\.replace/, :replace_html => /Element\.update/, :chained_replace => /\.replace/, :chained_replace_html => /\.update/, :remove => /Element\.remove/, :show => /Element\.show/, :hide => /Element\.hide/, :toggle => /Element\.toggle/ |
RJS_INSERTIONS | = | [:top, :bottom, :before, :after] |
RJS_PATTERN_HTML | = | /"((\\"|[^"])*)"/ |
RJS_PATTERN_EVERYTHING | = | Regexp.new("#{RJS_STATEMENTS[:any]}\\(\"([^\"]*)\", #{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE) |
RJS_PATTERN_UNICODE_ESCAPED_CHAR | = | /\\u([0-9a-zA-Z]{4})/ |
An assertion that selects elements and makes one or more equality tests.
If the first argument is an element, selects all matching elements starting from (and including) that element and all its children in depth-first order.
If no element if specified, calling assert_select will select from the response HTML. Calling assert_select inside an assert_select block will run the assertion for each element selected by the enclosing assertion.
assert_select "ol>li" do |elements| elements.each do |element| assert_select element, "li" end end
Or for short:
assert_select "ol>li" do assert_select "li" end
The selector may be a CSS selector expression (String), an expression with substitution values, or an HTML::Selector object.
The equality test may be one of the following:
If no equality test specified, the assertion is true if at least one element selected.
To perform more than one equality tests, use a hash with the following keys:
If the method is called with a block, once all equality tests are evaluated the block is called with an array of all matched elements.
# At least one form element assert_select "form" # Form element includes four input fields assert_select "form input", 4 # Page title is "Welcome" assert_select "title", "Welcome" # Page title is "Welcome" and there is only one title element assert_select "title", {:count=>1, :text=>"Welcome"}, "Wrong title or more than one title element" # Page contains no forms assert_select "form", false, "This page must contain no forms" # Test the content and style assert_select "body div.header ul.menu" # Use substitution values assert_select "ol>li#?", /item-\d+/ # All input fields in the form have a name assert_select "form input" do assert_select "[name=?]", /.+/ # Not empty end
# File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 193 193: def assert_select(*args, &block) 194: # Start with optional element followed by mandatory selector. 195: arg = args.shift 196: 197: if arg.is_a?(HTML::Node) 198: # First argument is a node (tag or text, but also HTML root), 199: # so we know what we're selecting from. 200: root = arg 201: arg = args.shift 202: elsif arg == nil 203: # This usually happens when passing a node/element that 204: # happens to be nil. 205: 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?" 206: elsif @selected 207: root = HTML::Node.new(nil) 208: root.children.concat @selected 209: else 210: # Otherwise just operate on the response document. 211: root = response_from_page_or_rjs 212: end 213: 214: # First or second argument is the selector: string and we pass 215: # all remaining arguments. Array and we pass the argument. Also 216: # accepts selector itself. 217: case arg 218: when String 219: selector = HTML::Selector.new(arg, args) 220: when Array 221: selector = HTML::Selector.new(*arg) 222: when HTML::Selector 223: selector = arg 224: else raise ArgumentError, "Expecting a selector as the first argument" 225: end 226: 227: # Next argument is used for equality tests. 228: equals = {} 229: case arg = args.shift 230: when Hash 231: equals = arg 232: when String, Regexp 233: equals[:text] = arg 234: when Integer 235: equals[:count] = arg 236: when Range 237: equals[:minimum] = arg.begin 238: equals[:maximum] = arg.end 239: when FalseClass 240: equals[:count] = 0 241: when NilClass, TrueClass 242: equals[:minimum] = 1 243: else raise ArgumentError, "I don't understand what you're trying to match" 244: end 245: 246: # By default we're looking for at least one match. 247: if equals[:count] 248: equals[:minimum] = equals[:maximum] = equals[:count] 249: else 250: equals[:minimum] = 1 unless equals[:minimum] 251: end 252: 253: # Last argument is the message we use if the assertion fails. 254: message = args.shift 255: #- message = "No match made with selector #{selector.inspect}" unless message 256: if args.shift 257: raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type" 258: end 259: 260: matches = selector.select(root) 261: # If text/html, narrow down to those elements that match it. 262: content_mismatch = nil 263: if match_with = equals[:text] 264: matches.delete_if do |match| 265: text = "" 266: text.force_encoding(match_with.encoding) if text.respond_to?(:force_encoding) 267: stack = match.children.reverse 268: while node = stack.pop 269: if node.tag? 270: stack.concat node.children.reverse 271: else 272: content = node.content 273: content.force_encoding(match_with.encoding) if content.respond_to?(:force_encoding) 274: text << content 275: end 276: end 277: text.strip! unless NO_STRIP.include?(match.name) 278: unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s) 279: content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, text) 280: true 281: end 282: end 283: elsif match_with = equals[:html] 284: matches.delete_if do |match| 285: html = match.children.map(&:to_s).join 286: html.strip! unless NO_STRIP.include?(match.name) 287: unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s) 288: content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, html) 289: true 290: end 291: end 292: end 293: # Expecting foo found bar element only if found zero, not if 294: # found one but expecting two. 295: message ||= content_mismatch if matches.empty? 296: # Test minimum/maximum occurrence. 297: min, max = equals[:minimum], equals[:maximum] 298: message = message || %(Expected #{count_description(min, max)} matching "#{selector.to_s}", found #{matches.size}.) 299: assert matches.size >= min, message if min 300: assert matches.size <= max, message if max 301: 302: # If a block is given call that block. Set @selected to allow 303: # nested assert_select, which can be nested several levels deep. 304: if block_given? && !matches.empty? 305: begin 306: in_scope, @selected = @selected, matches 307: yield matches 308: ensure 309: @selected = in_scope 310: end 311: end 312: 313: # Returns all matches elements. 314: matches 315: end
Extracts the body of an email and runs nested assertions on it.
You must enable deliveries for this assertion to work, use:
ActionMailer::Base.perform_deliveries = true
assert_select_email do assert_select "h1", "Email alert" end assert_select_email do items = assert_select "ol>li" items.each do # Work with items here... end end
# File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 564 564: def assert_select_email(&block) 565: deliveries = ActionMailer::Base.deliveries 566: assert !deliveries.empty?, "No e-mail in delivery list" 567: 568: for delivery in deliveries 569: for part in delivery.parts 570: if part["Content-Type"].to_s =~ /^text\/html\W/ 571: root = HTML::Document.new(part.body).root 572: assert_select root, ":root", &block 573: end 574: end 575: end 576: end
Extracts the content of an element, treats it as encoded HTML and runs nested assertion on it.
You typically call this method within another assertion to operate on all currently selected elements. You can also pass an element or array of elements.
The content of each element is un-encoded, and wrapped in the root element encoded. It then calls the block with all un-encoded elements.
# Selects all bold tags from within the title of an ATOM feed's entries (perhaps to nab a section name prefix) assert_select_feed :atom, 1.0 do # Select each entry item and then the title item assert_select "entry>title" do # Run assertions on the encoded title elements assert_select_encoded do assert_select "b" end end end # Selects all paragraph tags from within the description of an RSS feed assert_select_feed :rss, 2.0 do # Select description element of each feed item. assert_select "channel>item>description" do # Run assertions on the encoded elements. assert_select_encoded do assert_select "p" end end end
# File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 510 510: def assert_select_encoded(element = nil, &block) 511: case element 512: when Array 513: elements = element 514: when HTML::Node 515: elements = [element] 516: when nil 517: unless elements = @selected 518: raise ArgumentError, "First argument is optional, but must be called from a nested assert_select" 519: end 520: else 521: raise ArgumentError, "Argument is optional, and may be node or array of nodes" 522: end 523: 524: fix_content = lambda do |node| 525: # Gets around a bug in the Rails 1.1 HTML parser. 526: node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { CGI.escapeHTML($1) } 527: end 528: 529: selected = elements.map do |element| 530: text = element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join 531: root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root 532: css_select(root, "encoded:root", &block)[0] 533: end 534: 535: begin 536: old_selected, @selected = @selected, selected 537: assert_select ":root", &block 538: ensure 539: @selected = old_selected 540: end 541: end
Selects content from the RJS response.
With no arguments, asserts that one or more elements are updated or inserted by RJS statements.
Use the id argument to narrow down the assertion to only statements that update or insert an element with that identifier.
Use the first argument to narrow down assertions to only statements of that type. Possible values are :replace, :replace_html, :show, :hide, :toggle, :remove and :insert_html.
Use the argument :insert followed by an insertion position to narrow down the assertion to only statements that insert elements in that position. Possible values are :top, :bottom, :before and :after.
Using the :remove statement, you will be able to pass a block, but it will be ignored as there is no HTML passed for this statement.
Without a block, assert_select_rjs merely asserts that the response contains one or more RJS statements that replace or update content.
With a block, assert_select_rjs also selects all elements used in these statements and passes them to the block. Nested assertions are supported.
Calling assert_select_rjs with no arguments and using nested asserts asserts that the HTML content is returned by one or more RJS statements. Using assert_select directly makes the same assertion on the content, but without distinguishing whether the content is returned in an HTML or JavaScript.
# Replacing the element foo. # page.replace 'foo', ... assert_select_rjs :replace, "foo" # Replacing with the chained RJS proxy. # page[:foo].replace ... assert_select_rjs :chained_replace, 'foo' # Inserting into the element bar, top position. assert_select_rjs :insert, :top, "bar" # Remove the element bar assert_select_rjs :remove, "bar" # Changing the element foo, with an image. assert_select_rjs "foo" do assert_select "img[src=/images/logo.gif"" end # RJS inserts or updates a list with four items. assert_select_rjs do assert_select "ol>li", 4 end # The same, but shorter. assert_select "ol>li", 4
# File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 400 400: def assert_select_rjs(*args, &block) 401: rjs_type = nil 402: arg = args.shift 403: 404: # If the first argument is a symbol, it's the type of RJS statement we're looking 405: # for (update, replace, insertion, etc). Otherwise, we're looking for just about 406: # any RJS statement. 407: if arg.is_a?(Symbol) 408: rjs_type = arg 409: 410: if rjs_type == :insert 411: arg = args.shift 412: insertion = "insert_#{arg}".to_sym 413: raise ArgumentError, "Unknown RJS insertion type #{arg}" unless RJS_STATEMENTS[insertion] 414: statement = "(#{RJS_STATEMENTS[insertion]})" 415: else 416: raise ArgumentError, "Unknown RJS statement type #{rjs_type}" unless RJS_STATEMENTS[rjs_type] 417: statement = "(#{RJS_STATEMENTS[rjs_type]})" 418: end 419: arg = args.shift 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. 426: if arg.is_a?(String) 427: id = Regexp.quote(arg) 428: arg = args.shift 429: else 430: id = "[^\"]*" 431: end 432: 433: pattern = 434: case rjs_type 435: when :chained_replace, :chained_replace_html 436: Regexp.new("\\$\\(\"#{id}\"\\)#{statement}\\(#{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE) 437: when :remove, :show, :hide, :toggle 438: Regexp.new("#{statement}\\(\"#{id}\"\\)") 439: else 440: Regexp.new("#{statement}\\(\"#{id}\", #{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE) 441: end 442: 443: # Duplicate the body since the next step involves destroying it. 444: matches = nil 445: case rjs_type 446: when :remove, :show, :hide, :toggle 447: matches = @response.body.match(pattern) 448: else 449: @response.body.gsub(pattern) do |match| 450: html = unescape_rjs($2) 451: matches ||= [] 452: matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? } 453: "" 454: end 455: end 456: 457: if matches 458: assert_block("") { true } # to count the assertion 459: if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type) 460: begin 461: in_scope, @selected = @selected, matches 462: yield matches 463: ensure 464: @selected = in_scope 465: end 466: end 467: matches 468: else 469: # RJS statement not found. 470: flunk args.shift || "No RJS statement that replaces or inserts HTML content." 471: end 472: end
Select and return all matching elements.
If called with a single argument, uses that argument as a selector to match all elements of the current page. Returns an empty array if no match is found.
If called with two arguments, uses the first argument as the base element and the second argument as the selector. Attempts to match the base element and any of its children. Returns an empty array if no match is found.
The selector may be a CSS selector expression (String), an expression with substitution values (Array) or an HTML::Selector object.
# Selects all div tags divs = css_select("div") # Selects all paragraph tags and does something interesting pars = css_select("p") pars.each do |par| # Do something fun with paragraphs here... end # Selects all list items in unordered lists items = css_select("ul>li") # Selects all form tags and then all inputs inside the form forms = css_select("form") forms.each do |form| inputs = css_select(form, "input") ... end
# File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 70 70: def css_select(*args) 71: # See assert_select to understand what's going on here. 72: arg = args.shift 73: 74: if arg.is_a?(HTML::Node) 75: root = arg 76: arg = args.shift 77: elsif arg == nil 78: 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?" 79: elsif @selected 80: matches = [] 81: 82: @selected.each do |selected| 83: subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup)) 84: subset.each do |match| 85: matches << match unless matches.any? { |m| m.equal?(match) } 86: end 87: end 88: 89: return matches 90: else 91: root = response_from_page_or_rjs 92: end 93: 94: case arg 95: when String 96: selector = HTML::Selector.new(arg, args) 97: when Array 98: selector = HTML::Selector.new(*arg) 99: when HTML::Selector 100: selector = arg 101: else raise ArgumentError, "Expecting a selector as the first argument" 102: end 103: 104: selector.select(root) 105: end
assert_select and css_select call this to obtain the content in the HTML page, or from all the RJS statements, depending on the type of response.
# File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 606 606: def response_from_page_or_rjs() 607: content_type = @response.content_type 608: 609: if content_type && content_type =~ /text\/javascript/ 610: body = @response.body.dup 611: root = HTML::Node.new(nil) 612: 613: while true 614: next if body.sub!(RJS_PATTERN_EVERYTHING) do |match| 615: html = unescape_rjs($3) 616: matches = HTML::Document.new(html).root.children.select { |n| n.tag? } 617: root.children.concat matches 618: "" 619: end 620: break 621: end 622: 623: root 624: else 625: html_document.root 626: end 627: end
Unescapes a RJS string.
# File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 630 630: def unescape_rjs(rjs_string) 631: # RJS encodes double quotes and line breaks. 632: unescaped= rjs_string.gsub('\"', '"') 633: unescaped.gsub!(/\\\//, '/') 634: unescaped.gsub!('\n', "\n") 635: unescaped.gsub!('\076', '>') 636: unescaped.gsub!('\074', '<') 637: # RJS encodes non-ascii characters. 638: unescaped.gsub!(RJS_PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')} 639: unescaped 640: end