Class Index [+]

Quicksearch

ActionDispatch::Assertions::SelectorAssertions

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.

Constants

RJS_PATTERN_HTML
RJS_ANY_ID
RJS_STATEMENTS
RJS_INSERTIONS
RJS_PATTERN_UNICODE_ESCAPED_CHAR

Public Instance Methods

assert_select(selector, equality?, message?) assert_select(element, selector, equality?, message?) click to toggle source

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 lib/action_dispatch/testing/assertions/selector.rb, line 195
195:       def assert_select(*args, &block)
196:         # Start with optional element followed by mandatory selector.
197:         arg = args.shift
198: 
199:         if arg.is_a?(HTML::Node)
200:           # First argument is a node (tag or text, but also HTML root),
201:           # so we know what we're selecting from.
202:           root = arg
203:           arg = args.shift
204:         elsif arg == nil
205:           # This usually happens when passing a node/element that
206:           # happens to be nil.
207:           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?"
208:         elsif @selected
209:           root = HTML::Node.new(nil)
210:           root.children.concat @selected
211:         else
212:           # Otherwise just operate on the response document.
213:           root = response_from_page_or_rjs
214:         end
215: 
216:         # First or second argument is the selector: string and we pass
217:         # all remaining arguments. Array and we pass the argument. Also
218:         # accepts selector itself.
219:         case arg
220:           when String
221:             selector = HTML::Selector.new(arg, args)
222:           when Array
223:             selector = HTML::Selector.new(*arg)
224:           when HTML::Selector
225:             selector = arg
226:           else raise ArgumentError, "Expecting a selector as the first argument"
227:         end
228: 
229:         # Next argument is used for equality tests.
230:         equals = {}
231:         case arg = args.shift
232:           when Hash
233:             equals = arg
234:           when String, Regexp
235:             equals[:text] = arg
236:           when Integer
237:             equals[:count] = arg
238:           when Range
239:             equals[:minimum] = arg.begin
240:             equals[:maximum] = arg.end
241:           when FalseClass
242:             equals[:count] = 0
243:           when NilClass, TrueClass
244:             equals[:minimum] = 1
245:           else raise ArgumentError, "I don't understand what you're trying to match"
246:         end
247: 
248:         # By default we're looking for at least one match.
249:         if equals[:count]
250:           equals[:minimum] = equals[:maximum] = equals[:count]
251:         else
252:           equals[:minimum] = 1 unless equals[:minimum]
253:         end
254: 
255:         # Last argument is the message we use if the assertion fails.
256:         message = args.shift
257:         #- message = "No match made with selector #{selector.inspect}" unless message
258:         if args.shift
259:           raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type"
260:         end
261: 
262:         matches = selector.select(root)
263:         # If text/html, narrow down to those elements that match it.
264:         content_mismatch = nil
265:         if match_with = equals[:text]
266:           matches.delete_if do |match|
267:             text = ""
268:             stack = match.children.reverse
269:             while node = stack.pop
270:               if node.tag?
271:                 stack.concat node.children.reverse
272:               else
273:                 content = node.content
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, count = equals[:minimum], equals[:maximum], equals[:count]
298:         message = message || %(Expected #{count_description(min, max, count)} matching "#{selector.to_s}", found #{matches.size}.)
299:         if count
300:           assert matches.size == count, message
301:         else
302:           assert matches.size >= min, message if min
303:           assert matches.size <= max, message if max
304:         end
305: 
306:         # If a block is given call that block. Set @selected to allow
307:         # nested assert_select, which can be nested several levels deep.
308:         if block_given? && !matches.empty?
309:           begin
310:             in_scope, @selected = @selected, matches
311:             yield matches
312:           ensure
313:             @selected = in_scope
314:           end
315:         end
316: 
317:         # Returns all matches elements.
318:         matches
319:       end
assert_select_email { } click to toggle source

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 lib/action_dispatch/testing/assertions/selector.rb, line 567
567:       def assert_select_email(&block)
568:         deliveries = ActionMailer::Base.deliveries
569:         assert !deliveries.empty?, "No e-mail in delivery list"
570: 
571:         for delivery in deliveries
572:           for part in delivery.parts
573:             if part["Content-Type"].to_s =~ /^text\/html\W/
574:               root = HTML::Document.new(part.body).root
575:               assert_select root, ":root", &block
576:             end
577:           end
578:         end
579:       end
} click to toggle source

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 lib/action_dispatch/testing/assertions/selector.rb, line 513
513:       def assert_select_encoded(element = nil, &block)
514:         case element
515:           when Array
516:             elements = element
517:           when HTML::Node
518:             elements = [element]
519:           when nil
520:             unless elements = @selected
521:               raise ArgumentError, "First argument is optional, but must be called from a nested assert_select"
522:             end
523:           else
524:             raise ArgumentError, "Argument is optional, and may be node or array of nodes"
525:         end
526: 
527:         fix_content = lambda do |node|
528:           # Gets around a bug in the Rails 1.1 HTML parser.
529:           node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/) { Rack::Utils.escapeHTML($1) }
530:         end
531: 
532:         selected = elements.map do |element|
533:           text = element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join
534:           root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root
535:           css_select(root, "encoded:root", &block)[0]
536:         end
537: 
538:         begin
539:           old_selected, @selected = @selected, selected
540:           assert_select ":root", &block
541:         ensure
542:           @selected = old_selected
543:         end
544:       end
} click to toggle source

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, :show, :hide, :toggle, :remove</tta>, <tt>:insert_html and :redirect.

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.

Use the argument :redirect followed by a path to check that an statement which redirects to the specified path is generated.

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.

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"

  # 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

  # Checking for a redirect.
  assert_select_rjs :redirect, root_path
     # File lib/action_dispatch/testing/assertions/selector.rb, line 412
412:       def assert_select_rjs(*args, &block)
413:         rjs_type = args.first.is_a?(Symbol) ? args.shift : nil
414:         id       = args.first.is_a?(String) ? args.shift : nil
415: 
416:         # If the first argument is a symbol, it's the type of RJS statement we're looking
417:         # for (update, replace, insertion, etc). Otherwise, we're looking for just about
418:         # any RJS statement.
419:         if rjs_type
420:           if rjs_type == :insert
421:             position  = args.shift
422:             id = args.shift
423:             insertion = "insert_#{position}".to_sym
424:             raise ArgumentError, "Unknown RJS insertion type #{position}" unless RJS_STATEMENTS[insertion]
425:             statement = "(#{RJS_STATEMENTS[insertion]})"
426:           else
427:             raise ArgumentError, "Unknown RJS statement type #{rjs_type}" unless RJS_STATEMENTS[rjs_type]
428:             statement = "(#{RJS_STATEMENTS[rjs_type]})"
429:           end
430:         else
431:           statement = "#{RJS_STATEMENTS[:any]}"
432:         end
433: 
434:         # Next argument we're looking for is the element identifier. If missing, we pick
435:         # any element, otherwise we replace it in the statement.
436:         pattern = Regexp.new(
437:           id ? statement.gsub(RJS_ANY_ID, "\"#{id}\"") : statement
438:         )
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(match)
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:           case rjs_type
468:             when :remove, :show, :hide, :toggle
469:               flunk_message = "No RJS statement that #{rjs_type.to_s}s '#{id}' was rendered."
470:             else
471:               flunk_message = "No RJS statement that replaces or inserts HTML content."
472:           end
473:           flunk args.shift || flunk_message
474:         end
475:       end
css_select(selector) => array css_select(element, selector) => array click to toggle source

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

Protected Instance Methods

response_from_page_or_rjs() click to toggle source

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 lib/action_dispatch/testing/assertions/selector.rb, line 604
604:         def response_from_page_or_rjs()
605:           content_type = @response.content_type
606: 
607:           if content_type && Mime::JS =~ content_type
608:             body = @response.body.dup
609:             root = HTML::Node.new(nil)
610: 
611:             while true
612:               next if body.sub!(RJS_STATEMENTS[:any]) do |match|
613:                 html = unescape_rjs(match)
614:                 matches = HTML::Document.new(html).root.children.select { |n| n.tag? }
615:                 root.children.concat matches
616:                 ""
617:               end
618:               break
619:             end
620: 
621:             root
622:           else
623:             html_document.root
624:           end
625:         end
unescape_rjs(rjs_string) click to toggle source

Unescapes a RJS string.

     # File lib/action_dispatch/testing/assertions/selector.rb, line 628
628:         def unescape_rjs(rjs_string)
629:           # RJS encodes double quotes and line breaks.
630:           unescaped= rjs_string.gsub('\"', '"')
631:           unescaped.gsub!(/\\\//, '/')
632:           unescaped.gsub!('\n', "\n")
633:           unescaped.gsub!('\076', '>')
634:           unescaped.gsub!('\074', '<')
635:           # RJS encodes non-ascii characters.
636:           unescaped.gsub!(RJS_PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')}
637:           unescaped
638:         end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.