Adds the assert_select method for use in Rails functional test cases.

Use assert_select 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 for learning how to use selectors.

Methods
Constants
RJS_STATEMENTS = { :replace => /Element\.replace/, :replace_html => /Element\.update/, :chained_replace => /\.replace/, :chained_replace_html => /\.update/, }
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})/
Public Instance methods
assert_select(selector, equality?, message?)
assert_select(element, selector, equality?, message?)

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.

For example:

  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.

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 vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 179
179:       def assert_select(*args, &block)
180:         # Start with optional element followed by mandatory selector.
181:         arg = args.shift
182: 
183:         if arg.is_a?(HTML::Node)
184:           # First argument is a node (tag or text, but also HTML root),
185:           # so we know what we're selecting from.
186:           root = arg
187:           arg = args.shift
188:         elsif arg == nil
189:           # This usually happens when passing a node/element that
190:           # happens to be nil.
191:           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?"
192:         elsif @selected
193:           root = HTML::Node.new(nil)
194:           root.children.concat @selected
195:         else
196:           # Otherwise just operate on the response document.
197:           root = response_from_page_or_rjs
198:         end
199: 
200:         # First or second argument is the selector: string and we pass
201:         # all remaining arguments. Array and we pass the argument. Also
202:         # accepts selector itself.
203:         case arg
204:           when String
205:             selector = HTML::Selector.new(arg, args)
206:           when Array
207:             selector = HTML::Selector.new(*arg)
208:           when HTML::Selector
209:             selector = arg
210:           else raise ArgumentError, "Expecting a selector as the first argument"
211:         end
212: 
213:         # Next argument is used for equality tests.
214:         equals = {}
215:         case arg = args.shift
216:           when Hash
217:             equals = arg
218:           when String, Regexp
219:             equals[:text] = arg
220:           when Integer
221:             equals[:count] = arg
222:           when Range
223:             equals[:minimum] = arg.begin
224:             equals[:maximum] = arg.end
225:           when FalseClass
226:             equals[:count] = 0
227:           when NilClass, TrueClass
228:             equals[:minimum] = 1
229:           else raise ArgumentError, "I don't understand what you're trying to match"
230:         end
231: 
232:         # By default we're looking for at least one match.
233:         if equals[:count]
234:           equals[:minimum] = equals[:maximum] = equals[:count]
235:         else
236:           equals[:minimum] = 1 unless equals[:minimum]
237:         end
238: 
239:         # Last argument is the message we use if the assertion fails.
240:         message = args.shift
241:         #- message = "No match made with selector #{selector.inspect}" unless message
242:         if args.shift
243:           raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type"
244:         end
245: 
246:         matches = selector.select(root)
247:         # If text/html, narrow down to those elements that match it.
248:         content_mismatch = nil
249:         if match_with = equals[:text]
250:           matches.delete_if do |match|
251:             text = ""
252:             stack = match.children.reverse
253:             while node = stack.pop
254:               if node.tag?
255:                 stack.concat node.children.reverse
256:               else
257:                 text << node.content
258:               end
259:             end
260:             text.strip! unless NO_STRIP.include?(match.name)
261:             unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s)
262:               content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, text)
263:               true
264:             end
265:           end
266:         elsif match_with = equals[:html]
267:           matches.delete_if do |match|
268:             html = match.children.map(&:to_s).join
269:             html.strip! unless NO_STRIP.include?(match.name)
270:             unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s)
271:               content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, html)
272:               true
273:             end
274:           end
275:         end
276:         # Expecting foo found bar element only if found zero, not if
277:         # found one but expecting two.
278:         message ||= content_mismatch if matches.empty?
279:         # Test minimum/maximum occurrence.
280:         if equals[:minimum]
281:           assert matches.size >= equals[:minimum], message ||
282:              "Expected at least #{equals[:minimum]} elements, found #{matches.size}."
283:         end
284:         if equals[:maximum]
285:           assert matches.size <= equals[:maximum], message ||
286:             "Expected at most #{equals[:maximum]} elements, found #{matches.size}."
287:         end
288: 
289:         # If a block is given call that block. Set @selected to allow
290:         # nested assert_select, which can be nested several levels deep.
291:         if block_given? && !matches.empty?
292:           begin
293:             in_scope, @selected = @selected, matches
294:             yield matches
295:           ensure
296:             @selected = in_scope
297:           end
298:         end
299: 
300:         # Returns all matches elements.
301:         matches
302:       end
assert_select_email { }

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

Example

assert_select_email do

  assert_select "h1", "Email alert"

end

     # File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 501
501:       def assert_select_email(&block)
502:         deliveries = ActionMailer::Base.deliveries
503:         assert !deliveries.empty?, "No e-mail in delivery list"
504: 
505:         for delivery in deliveries
506:           for part in delivery.parts
507:             if part["Content-Type"].to_s =~ /^text\/html\W/
508:               root = HTML::Document.new(part.body).root
509:               assert_select root, ":root", &block
510:             end
511:           end
512:         end
513:       end
assert_select_encoded(element?) { |elements| ... }

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.

Example

  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 455
455:       def assert_select_encoded(element = nil, &block)
456:         case element
457:           when Array
458:             elements = element
459:           when HTML::Node
460:             elements = [element]
461:           when nil
462:             unless elements = @selected
463:               raise ArgumentError, "First argument is optional, but must be called from a nested assert_select"
464:             end
465:           else
466:             raise ArgumentError, "Argument is optional, and may be node or array of nodes"
467:         end
468: 
469:         fix_content = lambda do |node|
470:           # Gets around a bug in the Rails 1.1 HTML parser.
471:           node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { CGI.escapeHTML($1) }
472:         end
473: 
474:         selected = elements.map do |element|
475:           text = element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join
476:           root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root
477:           css_select(root, "encoded:root", &block)[0]
478:         end
479: 
480:         begin
481:           old_selected, @selected = @selected, selected
482:           assert_select ":root", &block
483:         ensure
484:           @selected = old_selected
485:         end
486:       end
assert_select_rjs(id?) { |elements| ... }
assert_select_rjs(statement, id?) { |elements| ... }
assert_select_rjs(:insert, position, id?) { |elements| ... }

Selects content from the RJS response.

Narrowing down

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+ 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 blocks

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.

Examples

  # 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"

  # 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 367
367:       def assert_select_rjs(*args, &block)
368:         rjs_type = nil
369:         arg      = args.shift
370: 
371:         # If the first argument is a symbol, it's the type of RJS statement we're looking
372:         # for (update, replace, insertion, etc). Otherwise, we're looking for just about
373:         # any RJS statement.
374:         if arg.is_a?(Symbol)
375:           rjs_type = arg
376:           if rjs_type == :insert
377:             arg = args.shift
378:             insertion = "insert_#{arg}".to_sym
379:             raise ArgumentError, "Unknown RJS insertion type #{arg}" unless RJS_STATEMENTS[insertion]
380:             statement = "(#{RJS_STATEMENTS[insertion]})"
381:           else
382:             raise ArgumentError, "Unknown RJS statement type #{rjs_type}" unless RJS_STATEMENTS[rjs_type]
383:             statement = "(#{RJS_STATEMENTS[rjs_type]})"
384:           end
385:           arg = args.shift
386:         else
387:           statement = "#{RJS_STATEMENTS[:any]}"
388:         end
389: 
390:         # Next argument we're looking for is the element identifier. If missing, we pick
391:         # any element.
392:         if arg.is_a?(String)
393:           id = Regexp.quote(arg)
394:           arg = args.shift
395:         else
396:           id = "[^\"]*"
397:         end
398: 
399:         pattern =
400:           case rjs_type
401:             when :chained_replace, :chained_replace_html
402:               Regexp.new("\\$\\(\"#{id}\"\\)#{statement}\\(#{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE)
403:             else
404:               Regexp.new("#{statement}\\(\"#{id}\", #{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE)
405:           end
406: 
407:         # Duplicate the body since the next step involves destroying it.
408:         matches = nil
409:         @response.body.gsub(pattern) do |match|
410:           html = unescape_rjs($2)
411:           matches ||= []
412:           matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? }
413:           ""
414:         end
415:         if matches
416:           if block_given?
417:             begin
418:               in_scope, @selected = @selected, matches
419:               yield matches
420:             ensure
421:               @selected = in_scope
422:             end
423:           end
424:           matches
425:         else
426:           # RJS statement not found.
427:           flunk args.shift || "No RJS statement that replaces or inserts HTML content."
428:         end
429:       end
css_select(selector) => array
css_select(element, selector) => array

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.

For example:

  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 58
58:       def css_select(*args)
59:         # See assert_select to understand what's going on here.
60:         arg = args.shift
61: 
62:         if arg.is_a?(HTML::Node)
63:           root = arg
64:           arg = args.shift
65:         elsif arg == nil
66:           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?"
67:         elsif @selected
68:           matches = []
69:           @selected.each do |selected|
70:             subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup))
71:             subset.each do |match|
72:               matches << match unless matches.any? { |m| m.equal?(match) }
73:             end
74:           end
75: 
76:           return matches
77:         else
78:           root = response_from_page_or_rjs
79:         end
80: 
81:         case arg
82:           when String
83:             selector = HTML::Selector.new(arg, args)
84:           when Array
85:             selector = HTML::Selector.new(*arg)
86:           when HTML::Selector
87:             selector = arg
88:           else raise ArgumentError, "Expecting a selector as the first argument"
89:         end
90: 
91:         selector.select(root)
92:       end
Protected Instance methods
response_from_page_or_rjs()

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 539
539:         def response_from_page_or_rjs()
540:           content_type = @response.headers["Content-Type"]
541:           if content_type && content_type =~ /text\/javascript/
542:             body = @response.body.dup
543:             root = HTML::Node.new(nil)
544:             while true
545:               next if body.sub!(RJS_PATTERN_EVERYTHING) do |match|
546:                 html = unescape_rjs($3)
547:                 matches = HTML::Document.new(html).root.children.select { |n| n.tag? }
548:                 root.children.concat matches
549:                 ""
550:               end
551:               break
552:             end
553:             root
554:           else
555:             html_document.root
556:           end
557:         end
unescape_rjs(rjs_string)

Unescapes a RJS string.

     # File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 560
560:         def unescape_rjs(rjs_string)
561:           # RJS encodes double quotes and line breaks.
562:           unescaped= rjs_string.gsub('\"', '"')
563:           unescaped.gsub!('\n', "\n")
564:           # RJS encodes non-ascii characters.
565:           unescaped.gsub!(RJS_PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')}
566:           unescaped
567:         end