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: stack = match.children.reverse 267: while node = stack.pop 268: if node.tag? 269: stack.concat node.children.reverse 270: else 271: text << node.content 272: end 273: end 274: text.strip! unless NO_STRIP.include?(match.name) 275: unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s) 276: content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, text) 277: true 278: end 279: end 280: elsif match_with = equals[:html] 281: matches.delete_if do |match| 282: html = match.children.map(&:to_s).join 283: html.strip! unless NO_STRIP.include?(match.name) 284: unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s) 285: content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, html) 286: true 287: end 288: end 289: end 290: # Expecting foo found bar element only if found zero, not if 291: # found one but expecting two. 292: message ||= content_mismatch if matches.empty? 293: # Test minimum/maximum occurrence. 294: min, max = equals[:minimum], equals[:maximum] 295: message = message || %(Expected #{count_description(min, max)} matching "#{selector.to_s}", found #{matches.size}.) 296: assert matches.size >= min, message if min 297: assert matches.size <= max, message if max 298: 299: # If a block is given call that block. Set @selected to allow 300: # nested assert_select, which can be nested several levels deep. 301: if block_given? && !matches.empty? 302: begin 303: in_scope, @selected = @selected, matches 304: yield matches 305: ensure 306: @selected = in_scope 307: end 308: end 309: 310: # Returns all matches elements. 311: matches 312: 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 561 561: def assert_select_email(&block) 562: deliveries = ActionMailer::Base.deliveries 563: assert !deliveries.empty?, "No e-mail in delivery list" 564: 565: for delivery in deliveries 566: for part in delivery.parts 567: if part["Content-Type"].to_s =~ /^text\/html\W/ 568: root = HTML::Document.new(part.body).root 569: assert_select root, ":root", &block 570: end 571: end 572: end 573: 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 507 507: def assert_select_encoded(element = nil, &block) 508: case element 509: when Array 510: elements = element 511: when HTML::Node 512: elements = [element] 513: when nil 514: unless elements = @selected 515: raise ArgumentError, "First argument is optional, but must be called from a nested assert_select" 516: end 517: else 518: raise ArgumentError, "Argument is optional, and may be node or array of nodes" 519: end 520: 521: fix_content = lambda do |node| 522: # Gets around a bug in the Rails 1.1 HTML parser. 523: node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { CGI.escapeHTML($1) } 524: end 525: 526: selected = elements.map do |element| 527: text = element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join 528: root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root 529: css_select(root, "encoded:root", &block)[0] 530: end 531: 532: begin 533: old_selected, @selected = @selected, selected 534: assert_select ":root", &block 535: ensure 536: @selected = old_selected 537: end 538: 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 397 397: def assert_select_rjs(*args, &block) 398: rjs_type = nil 399: arg = args.shift 400: 401: # If the first argument is a symbol, it's the type of RJS statement we're looking 402: # for (update, replace, insertion, etc). Otherwise, we're looking for just about 403: # any RJS statement. 404: if arg.is_a?(Symbol) 405: rjs_type = arg 406: 407: if rjs_type == :insert 408: arg = args.shift 409: insertion = "insert_#{arg}".to_sym 410: raise ArgumentError, "Unknown RJS insertion type #{arg}" unless RJS_STATEMENTS[insertion] 411: statement = "(#{RJS_STATEMENTS[insertion]})" 412: else 413: raise ArgumentError, "Unknown RJS statement type #{rjs_type}" unless RJS_STATEMENTS[rjs_type] 414: statement = "(#{RJS_STATEMENTS[rjs_type]})" 415: end 416: arg = args.shift 417: else 418: statement = "#{RJS_STATEMENTS[:any]}" 419: end 420: 421: # Next argument we're looking for is the element identifier. If missing, we pick 422: # any element. 423: if arg.is_a?(String) 424: id = Regexp.quote(arg) 425: arg = args.shift 426: else 427: id = "[^\"]*" 428: end 429: 430: pattern = 431: case rjs_type 432: when :chained_replace, :chained_replace_html 433: Regexp.new("\\$\\(\"#{id}\"\\)#{statement}\\(#{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE) 434: when :remove, :show, :hide, :toggle 435: Regexp.new("#{statement}\\(\"#{id}\"\\)") 436: else 437: Regexp.new("#{statement}\\(\"#{id}\", #{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE) 438: end 439: 440: # Duplicate the body since the next step involves destroying it. 441: matches = nil 442: case rjs_type 443: when :remove, :show, :hide, :toggle 444: matches = @response.body.match(pattern) 445: else 446: @response.body.gsub(pattern) do |match| 447: html = unescape_rjs($2) 448: matches ||= [] 449: matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? } 450: "" 451: end 452: end 453: 454: if matches 455: assert_block("") { true } # to count the assertion 456: if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type) 457: begin 458: in_scope, @selected = @selected, matches 459: yield matches 460: ensure 461: @selected = in_scope 462: end 463: end 464: matches 465: else 466: # RJS statement not found. 467: flunk args.shift || "No RJS statement that replaces or inserts HTML content." 468: end 469: 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 603 603: def response_from_page_or_rjs() 604: content_type = @response.content_type 605: 606: if content_type && content_type =~ /text\/javascript/ 607: body = @response.body.dup 608: root = HTML::Node.new(nil) 609: 610: while true 611: next if body.sub!(RJS_PATTERN_EVERYTHING) do |match| 612: html = unescape_rjs($3) 613: matches = HTML::Document.new(html).root.children.select { |n| n.tag? } 614: root.children.concat matches 615: "" 616: end 617: break 618: end 619: 620: root 621: else 622: html_document.root 623: end 624: end
Unescapes a RJS string.
# File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 627 627: def unescape_rjs(rjs_string) 628: # RJS encodes double quotes and line breaks. 629: unescaped= rjs_string.gsub('\"', '"') 630: unescaped.gsub!(/\\\//, '/') 631: unescaped.gsub!('\n', "\n") 632: unescaped.gsub!('\076', '>') 633: unescaped.gsub!('\074', '<') 634: # RJS encodes non-ascii characters. 635: unescaped.gsub!(RJS_PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')} 636: unescaped 637: end