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:
- assert_select_encoded - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions.
- assert_select_email - Assertions on the HTML body of an e-mail.
Also see HTML::Selector to learn how to use selectors.
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 selects from the response HTML unless assert_select is called from within an assert_select block.
When called with a block assert_select passes an array of selected elements to the block. Calling assert_select from the block, with no element specified, runs the assertion on the complete set of elements selected by the enclosing assertion. Alternatively the array may be iterated through so that assert_select can be called separately for each element.
Example
If the response contains two ordered lists, each with four list elements then:
assert_select "ol" do |elements| elements.each do |element| assert_select element, "li", 4 end end
will pass, as will:
assert_select "ol" do assert_select "li", 8 end
The selector may be a CSS selector expression (String), an expression with substitution values, or an HTML::Selector object.
Equality Tests
The equality test may be one of the following:
- true - Assertion is true if at least one element selected.
- false - Assertion is true if no element selected.
- String/Regexp - Assertion is true if the text value of at least one element matches the string or regular expression.
- Integer - Assertion is true if exactly that number of elements are selected.
- Range - Assertion is true if the number of selected elements fit the range.
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:
- :text - Narrow the selection to elements that have this text value (string or regexp).
- :html - Narrow the selection to elements that have this HTML content (string or regexp).
- :count - Assertion is true if the number of selected elements is equal to this value.
- :minimum - Assertion is true if the number of selected elements is at least this value.
- :maximum - Assertion is true if the number of selected elements is at most this value.
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.
Examples
# 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 actionpack/lib/action_dispatch/testing/assertions/selector.rb, line 188 188: def assert_select(*args, &block) 189: # Start with optional element followed by mandatory selector. 190: arg = args.shift 191: @selected ||= nil 192: 193: if arg.is_a?(HTML::Node) 194: # First argument is a node (tag or text, but also HTML root), 195: # so we know what we're selecting from. 196: root = arg 197: arg = args.shift 198: elsif arg == nil 199: # This usually happens when passing a node/element that 200: # happens to be nil. 201: 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?" 202: elsif @selected 203: root = HTML::Node.new(nil) 204: root.children.concat @selected 205: else 206: # Otherwise just operate on the response document. 207: root = response_from_page 208: end 209: 210: # First or second argument is the selector: string and we pass 211: # all remaining arguments. Array and we pass the argument. Also 212: # accepts selector itself. 213: case arg 214: when String 215: selector = HTML::Selector.new(arg, args) 216: when Array 217: selector = HTML::Selector.new(*arg) 218: when HTML::Selector 219: selector = arg 220: else raise ArgumentError, "Expecting a selector as the first argument" 221: end 222: 223: # Next argument is used for equality tests. 224: equals = {} 225: case arg = args.shift 226: when Hash 227: equals = arg 228: when String, Regexp 229: equals[:text] = arg 230: when Integer 231: equals[:count] = arg 232: when Range 233: equals[:minimum] = arg.begin 234: equals[:maximum] = arg.end 235: when FalseClass 236: equals[:count] = 0 237: when NilClass, TrueClass 238: equals[:minimum] = 1 239: else raise ArgumentError, "I don't understand what you're trying to match" 240: end 241: 242: # By default we're looking for at least one match. 243: if equals[:count] 244: equals[:minimum] = equals[:maximum] = equals[:count] 245: else 246: equals[:minimum] = 1 unless equals[:minimum] 247: end 248: 249: # Last argument is the message we use if the assertion fails. 250: message = args.shift 251: #- message = "No match made with selector #{selector.inspect}" unless message 252: if args.shift 253: raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type" 254: end 255: 256: matches = selector.select(root) 257: # If text/html, narrow down to those elements that match it. 258: content_mismatch = nil 259: if match_with = equals[:text] 260: matches.delete_if do |match| 261: text = "" 262: stack = match.children.reverse 263: while node = stack.pop 264: if node.tag? 265: stack.concat node.children.reverse 266: else 267: content = node.content 268: text << content 269: end 270: end 271: text.strip! unless NO_STRIP.include?(match.name) 272: text.sub!(/\A\n/, '') if match.name == "textarea" 273: unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s) 274: content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, text) 275: true 276: end 277: end 278: elsif match_with = equals[:html] 279: matches.delete_if do |match| 280: html = match.children.map(&:to_s).join 281: html.strip! unless NO_STRIP.include?(match.name) 282: unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s) 283: content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, html) 284: true 285: end 286: end 287: end 288: # Expecting foo found bar element only if found zero, not if 289: # found one but expecting two. 290: message ||= content_mismatch if matches.empty? 291: # Test minimum/maximum occurrence. 292: min, max, count = equals[:minimum], equals[:maximum], equals[:count] 293: message = message || %(Expected #{count_description(min, max, count)} matching "#{selector.to_s}", found #{matches.size}.) 294: if count 295: assert matches.size == count, message 296: else 297: assert matches.size >= min, message if min 298: assert matches.size <= max, message if max 299: end 300: 301: # If a block is given call that block. Set @selected to allow 302: # nested assert_select, which can be nested several levels deep. 303: if block_given? && !matches.empty? 304: begin 305: in_scope, @selected = @selected, matches 306: yield matches 307: ensure 308: @selected = in_scope 309: end 310: end 311: 312: # Returns all matches elements. 313: matches 314: 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
Examples
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 actionpack/lib/action_dispatch/testing/assertions/selector.rb, line 414 414: def assert_select_email(&block) 415: deliveries = ActionMailer::Base.deliveries 416: assert !deliveries.empty?, "No e-mail in delivery list" 417: 418: for delivery in deliveries 419: for part in (delivery.parts.empty? ? [delivery] : delivery.parts) 420: if part["Content-Type"].to_s =~ /^text\/html\W/ 421: root = HTML::Document.new(part.body.to_s).root 422: assert_select root, ":root", &block 423: end 424: end 425: end 426: 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.
Examples
# 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 actionpack/lib/action_dispatch/testing/assertions/selector.rb, line 363 363: def assert_select_encoded(element = nil, &block) 364: case element 365: when Array 366: elements = element 367: when HTML::Node 368: elements = [element] 369: when nil 370: unless elements = @selected 371: raise ArgumentError, "First argument is optional, but must be called from a nested assert_select" 372: end 373: else 374: raise ArgumentError, "Argument is optional, and may be node or array of nodes" 375: end 376: 377: fix_content = lambda do |node| 378: # Gets around a bug in the Rails 1.1 HTML parser. 379: node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { Rack::Utils.escapeHTML($1) } 380: end 381: 382: selected = elements.map do |_element| 383: text = _element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join 384: root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root 385: css_select(root, "encoded:root", &block)[0] 386: end 387: 388: begin 389: old_selected, @selected = @selected, selected 390: assert_select ":root", &block 391: ensure 392: @selected = old_selected 393: end 394: 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.
Examples
# 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 actionpack/lib/action_dispatch/testing/assertions/selector.rb, line 62 62: def css_select(*args) 63: # See assert_select to understand what's going on here. 64: arg = args.shift 65: 66: if arg.is_a?(HTML::Node) 67: root = arg 68: arg = args.shift 69: elsif arg == nil 70: 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?" 71: elsif defined?(@selected) && @selected 72: matches = [] 73: 74: @selected.each do |selected| 75: subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup)) 76: subset.each do |match| 77: matches << match unless matches.any? { |m| m.equal?(match) } 78: end 79: end 80: 81: return matches 82: else 83: root = response_from_page 84: end 85: 86: case arg 87: when String 88: selector = HTML::Selector.new(arg, args) 89: when Array 90: selector = HTML::Selector.new(*arg) 91: when HTML::Selector 92: selector = arg 93: else raise ArgumentError, "Expecting a selector as the first argument" 94: end 95: 96: selector.select(root) 97: end
assert_select and css_select call this to obtain the content in the HTML page.