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.

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/
RJS_INSERTIONS = [:top, :bottom, :before, :after]
RJS_PATTERN_HTML = /"((\\"|[^"])*)"/
RJS_PATTERN_EVERYTHING = Regexp.new("#{RJS_STATEMENTS[:any]}\\(\"([^\"]*)\", #{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE)

Public Instance methods

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:

  • nil/true — Assertion is true if at least one element is selected.
  • String — Assertion is true if the text value of all selected elements equals to the string.
  • Regexp — Assertion is true if the text value of all selected elements matches the regular expression.
  • false — Assertion is true if no element is selected.
  • 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.

To perform more than one equality tests, use a hash the following keys:

  • :text — Assertion is true if the text value of each selected elements equals to the value (String or Regexp).
  • :count — Assertion is true if the number of matched elements is equal to the value.
  • :minimum — Assertion is true if the number of matched elements is at least that value.
  • :maximum — Assertion is true if the number of matched elements is at most that 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

[Source]

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

Example

assert_select_email do

  assert_select "h1", "Email alert"

end

[Source]

     # File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 495
495:       def assert_select_email(&block)
496:         deliveries = ActionMailer::Base.deliveries
497:         assert !deliveries.empty?, "No e-mail in delivery list"
498: 
499:         for delivery in deliveries
500:           for part in delivery.parts
501:             if part["Content-Type"].to_s =~ /^text\/html\W/
502:               root = HTML::Document.new(part.body).root
503:               assert_select root, ":root", &block
504:             end
505:           end
506:         end
507:       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.

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

[Source]

     # File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 449
449:       def assert_select_encoded(element = nil, &block)
450:         case element
451:           when Array
452:             elements = element
453:           when HTML::Node
454:             elements = [element]
455:           when nil
456:             unless elements = @selected
457:               raise ArgumentError, "First argument is optional, but must be called from a nested assert_select"
458:             end
459:           else
460:             raise ArgumentError, "Argument is optional, and may be node or array of nodes"
461:         end
462: 
463:         fix_content = lambda do |node|
464:           # Gets around a bug in the Rails 1.1 HTML parser.
465:           node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { CGI.escapeHTML($1) }
466:         end
467: 
468:         selected = elements.map do |element|
469:           text = element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join
470:           root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root
471:           css_select(root, "encoded:root", &block)[0]
472:         end
473: 
474:         begin
475:           old_selected, @selected = @selected, selected
476:           assert_select ":root", &block
477:         ensure
478:           @selected = old_selected
479:         end
480:       end

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

  # Updating the element foo.
  assert_select_rjs :update, "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

[Source]

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

For example:

  forms = css_select("form")
  forms.each do |form|
    inputs = css_select(form, "input")
    ...
  end

[Source]

    # File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 54
54:       def css_select(*args)
55:         # See assert_select to understand what's going on here.
56:         arg = args.shift
57: 
58:         if arg.is_a?(HTML::Node)
59:           root = arg
60:           arg = args.shift
61:         elsif arg == nil
62:           raise ArgumentError, "First arugment is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
63:         elsif @selected
64:           matches = []
65:           @selected.each do |selected|
66:             subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup))
67:             subset.each do |match|
68:               matches << match unless matches.any? { |m| m.equal?(match) }
69:             end
70:           end
71: 
72:           return matches
73:         else
74:           root = response_from_page_or_rjs
75:         end
76: 
77:         case arg
78:           when String
79:             selector = HTML::Selector.new(arg, args)
80:           when Array
81:             selector = HTML::Selector.new(*arg)
82:           when HTML::Selector 
83:             selector = arg
84:           else raise ArgumentError, "Expecting a selector as the first argument"
85:         end
86: 
87:         selector.select(root)  
88:       end

Protected Instance methods

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.

[Source]

     # File vendor/rails/actionpack/lib/action_controller/assertions/selector_assertions.rb, line 530
530:         def response_from_page_or_rjs()
531:           content_type = @response.headers["Content-Type"]
532:           if content_type && content_type =~ /text\/javascript/
533:             body = @response.body.dup
534:             root = HTML::Node.new(nil)
535:             while true
536:               next if body.sub!(RJS_PATTERN_EVERYTHING) do |match|
537:                 # RJS encodes double quotes and line breaks.
538:                 html = $3
539:                 html.gsub!(/\\"/, "\"")
540:                 html.gsub!(/\\n/, "\n")
541:                 matches = HTML::Document.new(html).root.children.select { |n| n.tag? }
542:                 root.children.concat matches
543:                 ""
544:               end
545:               break
546:             end
547:             root
548:           else
549:             html_document.root
550:           end
551:         end

[Validate]