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:
Also see HTML::Selector to learn how to use selectors.
RJS_PATTERN_HTML | = | "\"((\\\\\"|[^\"])*)\"" |
RJS_ANY_ID | = | "\"([^\"])*\"" |
RJS_STATEMENTS | = | { :chained_replace => "\\$\\(#{RJS_ANY_ID}\\)\\.replace\\(#{RJS_PATTERN_HTML}\\)", :chained_replace_html => "\\$\\(#{RJS_ANY_ID}\\)\\.update\\(#{RJS_PATTERN_HTML}\\)", :replace_html => "Element\\.update\\(#{RJS_ANY_ID}, #{RJS_PATTERN_HTML}\\)", :replace => "Element\\.replace\\(#{RJS_ANY_ID}, #{RJS_PATTERN_HTML}\\)" |
RJS_INSERTIONS | = | ["top", "bottom", "before", "after"] |
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 191 191: def assert_select(*args, &block) 192: # Start with optional element followed by mandatory selector. 193: arg = args.shift 194: 195: if arg.is_a?(HTML::Node) 196: # First argument is a node (tag or text, but also HTML root), 197: # so we know what we're selecting from. 198: root = arg 199: arg = args.shift 200: elsif arg == nil 201: # This usually happens when passing a node/element that 202: # happens to be nil. 203: 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?" 204: elsif @selected 205: root = HTML::Node.new(nil) 206: root.children.concat @selected 207: else 208: # Otherwise just operate on the response document. 209: root = response_from_page_or_rjs 210: end 211: 212: # First or second argument is the selector: string and we pass 213: # all remaining arguments. Array and we pass the argument. Also 214: # accepts selector itself. 215: case arg 216: when String 217: selector = HTML::Selector.new(arg, args) 218: when Array 219: selector = HTML::Selector.new(*arg) 220: when HTML::Selector 221: selector = arg 222: else raise ArgumentError, "Expecting a selector as the first argument" 223: end 224: 225: # Next argument is used for equality tests. 226: equals = {} 227: case arg = args.shift 228: when Hash 229: equals = arg 230: when String, Regexp 231: equals[:text] = arg 232: when Integer 233: equals[:count] = arg 234: when Range 235: equals[:minimum] = arg.begin 236: equals[:maximum] = arg.end 237: when FalseClass 238: equals[:count] = 0 239: when NilClass, TrueClass 240: equals[:minimum] = 1 241: else raise ArgumentError, "I don't understand what you're trying to match" 242: end 243: 244: # By default we're looking for at least one match. 245: if equals[:count] 246: equals[:minimum] = equals[:maximum] = equals[:count] 247: else 248: equals[:minimum] = 1 unless equals[:minimum] 249: end 250: 251: # Last argument is the message we use if the assertion fails. 252: message = args.shift 253: #- message = "No match made with selector #{selector.inspect}" unless message 254: if args.shift 255: raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type" 256: end 257: 258: matches = selector.select(root) 259: # If text/html, narrow down to those elements that match it. 260: content_mismatch = nil 261: if match_with = equals[:text] 262: matches.delete_if do |match| 263: text = "" 264: text.force_encoding(match_with.encoding) if text.respond_to?(:force_encoding) 265: stack = match.children.reverse 266: while node = stack.pop 267: if node.tag? 268: stack.concat node.children.reverse 269: else 270: content = node.content 271: content.force_encoding(match_with.encoding) if content.respond_to?(:force_encoding) 272: text << content 273: end 274: end 275: text.strip! unless NO_STRIP.include?(match.name) 276: unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s) 277: content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, text) 278: true 279: end 280: end 281: elsif match_with = equals[:html] 282: matches.delete_if do |match| 283: html = match.children.map(&:to_s).join 284: html.strip! unless NO_STRIP.include?(match.name) 285: unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s) 286: content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, html) 287: true 288: end 289: end 290: end 291: # Expecting foo found bar element only if found zero, not if 292: # found one but expecting two. 293: message ||= content_mismatch if matches.empty? 294: # Test minimum/maximum occurrence. 295: min, max = equals[:minimum], equals[:maximum] 296: message = message || %(Expected #{count_description(min, max)} matching "#{selector.to_s}", found #{matches.size}.) 297: assert matches.size >= min, message if min 298: assert matches.size <= max, message if max 299: 300: # If a block is given call that block. Set @selected to allow 301: # nested assert_select, which can be nested several levels deep. 302: if block_given? && !matches.empty? 303: begin 304: in_scope, @selected = @selected, matches 305: yield matches 306: ensure 307: @selected = in_scope 308: end 309: end 310: 311: # Returns all matches elements. 312: matches 313: 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 552 552: def assert_select_email(&block) 553: deliveries = ActionMailer::Base.deliveries 554: assert !deliveries.empty?, "No e-mail in delivery list" 555: 556: for delivery in deliveries 557: for part in delivery.parts 558: if part["Content-Type"].to_s =~ /^text\/html\W/ 559: root = HTML::Document.new(part.body).root 560: assert_select root, ":root", &block 561: end 562: end 563: end 564: 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 498 498: def assert_select_encoded(element = nil, &block) 499: case element 500: when Array 501: elements = element 502: when HTML::Node 503: elements = [element] 504: when nil 505: unless elements = @selected 506: raise ArgumentError, "First argument is optional, but must be called from a nested assert_select" 507: end 508: else 509: raise ArgumentError, "Argument is optional, and may be node or array of nodes" 510: end 511: 512: fix_content = lambda do |node| 513: # Gets around a bug in the Rails 1.1 HTML parser. 514: node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { CGI.escapeHTML($1) } 515: end 516: 517: selected = elements.map do |element| 518: text = element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join 519: root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root 520: css_select(root, "encoded:root", &block)[0] 521: end 522: 523: begin 524: old_selected, @selected = @selected, selected 525: assert_select ":root", &block 526: ensure 527: @selected = old_selected 528: end 529: 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 398 398: def assert_select_rjs(*args, &block) 399: rjs_type = args.first.is_a?(Symbol) ? args.shift : nil 400: id = args.first.is_a?(String) ? args.shift : nil 401: 402: # If the first argument is a symbol, it's the type of RJS statement we're looking 403: # for (update, replace, insertion, etc). Otherwise, we're looking for just about 404: # any RJS statement. 405: if rjs_type 406: if rjs_type == :insert 407: position = args.shift 408: insertion = "insert_#{position}".to_sym 409: raise ArgumentError, "Unknown RJS insertion type #{position}" unless RJS_STATEMENTS[insertion] 410: statement = "(#{RJS_STATEMENTS[insertion]})" 411: else 412: raise ArgumentError, "Unknown RJS statement type #{rjs_type}" unless RJS_STATEMENTS[rjs_type] 413: statement = "(#{RJS_STATEMENTS[rjs_type]})" 414: end 415: else 416: statement = "#{RJS_STATEMENTS[:any]}" 417: end 418: 419: # Next argument we're looking for is the element identifier. If missing, we pick 420: # any element, otherwise we replace it in the statement. 421: pattern = Regexp.new( 422: id ? statement.gsub(RJS_ANY_ID, "\"#{id}\"") : statement 423: ) 424: 425: # Duplicate the body since the next step involves destroying it. 426: matches = nil 427: case rjs_type 428: when :remove, :show, :hide, :toggle 429: matches = @response.body.match(pattern) 430: else 431: @response.body.gsub(pattern) do |match| 432: html = unescape_rjs(match) 433: matches ||= [] 434: matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? } 435: "" 436: end 437: end 438: 439: if matches 440: assert_block("") { true } # to count the assertion 441: if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type) 442: begin 443: in_scope, @selected = @selected, matches 444: yield matches 445: ensure 446: @selected = in_scope 447: end 448: end 449: matches 450: else 451: # RJS statement not found. 452: case rjs_type 453: when :remove, :show, :hide, :toggle 454: flunk_message = "No RJS statement that #{rjs_type.to_s}s '#{id}' was rendered." 455: else 456: flunk_message = "No RJS statement that replaces or inserts HTML content." 457: end 458: flunk args.shift || flunk_message 459: end 460: 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 68 68: def css_select(*args) 69: # See assert_select to understand what's going on here. 70: arg = args.shift 71: 72: if arg.is_a?(HTML::Node) 73: root = arg 74: arg = args.shift 75: elsif arg == nil 76: 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?" 77: elsif @selected 78: matches = [] 79: 80: @selected.each do |selected| 81: subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup)) 82: subset.each do |match| 83: matches << match unless matches.any? { |m| m.equal?(match) } 84: end 85: end 86: 87: return matches 88: else 89: root = response_from_page_or_rjs 90: end 91: 92: case arg 93: when String 94: selector = HTML::Selector.new(arg, args) 95: when Array 96: selector = HTML::Selector.new(*arg) 97: when HTML::Selector 98: selector = arg 99: else raise ArgumentError, "Expecting a selector as the first argument" 100: end 101: 102: selector.select(root) 103: 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 590 590: def response_from_page_or_rjs() 591: content_type = @response.content_type 592: 593: if content_type && content_type =~ /text\/javascript/ 594: body = @response.body.dup 595: root = HTML::Node.new(nil) 596: 597: while true 598: next if body.sub!(RJS_STATEMENTS[:any]) do |match| 599: html = unescape_rjs(match) 600: matches = HTML::Document.new(html).root.children.select { |n| n.tag? } 601: root.children.concat matches 602: "" 603: end 604: break 605: end 606: 607: root 608: else 609: html_document.root 610: end 611: end
Unescapes a RJS string.
# File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 614 614: def unescape_rjs(rjs_string) 615: # RJS encodes double quotes and line breaks. 616: unescaped= rjs_string.gsub('\"', '"') 617: unescaped.gsub!(/\\\//, '/') 618: unescaped.gsub!('\n', "\n") 619: unescaped.gsub!('\076', '>') 620: unescaped.gsub!('\074', '<') 621: # RJS encodes non-ascii characters. 622: unescaped.gsub!(RJS_PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')} 623: unescaped 624: end