Upgrade to Rails 2.0.2

Upgraded to Rails 2.0.2, except that we maintain

   vendor/rails/actionpack/lib/action_controller/routing.rb

from Rail 1.2.6 (at least for now), so that Routes don't change. We still
get to enjoy Rails's many new features.

Also fixed a bug in Chunk-handling: disable WikiWord processing in tags (for real this time).
This commit is contained in:
Jacques Distler 2007-12-21 01:48:59 -06:00
parent 0f6889e09f
commit 6873fc8026
1083 changed files with 52810 additions and 41058 deletions

View file

@ -1,228 +0,0 @@
require 'rexml/document'
module ActionController #:nodoc:
module Assertions #:nodoc:
module DeprecatedAssertions #:nodoc:
def assert_success(message=nil) #:nodoc:
assert_response(:success, message)
end
deprecate :assert_success => "use assert_response(:success)"
def assert_redirect(message=nil) #:nodoc:
assert_response(:redirect, message)
end
deprecate :assert_redirect => "use assert_response(:redirect)"
def assert_rendered_file(expected=nil, message=nil) #:nodoc:
assert_template(expected, message)
end
deprecate :assert_rendered_file => :assert_template
# ensure that the session has an object with the specified name
def assert_session_has(key=nil, message=nil) #:nodoc:
msg = build_message(message, "<?> is not in the session <?>", key, @response.session)
assert_block(msg) { @response.has_session_object?(key) }
end
deprecate :assert_session_has => "use assert(@response.has_session_object?(key))"
# ensure that the session has no object with the specified name
def assert_session_has_no(key=nil, message=nil) #:nodoc:
msg = build_message(message, "<?> is in the session <?>", key, @response.session)
assert_block(msg) { !@response.has_session_object?(key) }
end
deprecate :assert_session_has_no => "use assert(!@response.has_session_object?(key))"
def assert_session_equal(expected = nil, key = nil, message = nil) #:nodoc:
msg = build_message(message, "<?> expected in session['?'] but was <?>", expected, key, @response.session[key])
assert_block(msg) { expected == @response.session[key] }
end
deprecate :assert_session_equal => "use assert_equal(expected, @response[key])"
# -- cookie assertions ---------------------------------------------------
def assert_no_cookie(key = nil, message = nil) #:nodoc:
actual = @response.cookies[key]
msg = build_message(message, "<?> not expected in cookies['?']", actual, key)
assert_block(msg) { actual.nil? or actual.empty? }
end
deprecate :assert_no_cookie => "use assert(!@response.cookies.key?(key))"
def assert_cookie_equal(expected = nil, key = nil, message = nil) #:nodoc:
actual = @response.cookies[key]
actual = actual.first if actual
msg = build_message(message, "<?> expected in cookies['?'] but was <?>", expected, key, actual)
assert_block(msg) { expected == actual }
end
deprecate :assert_cookie_equal => "use assert(@response.cookies.key?(key))"
# -- flash assertions ---------------------------------------------------
# ensure that the flash has an object with the specified name
def assert_flash_has(key=nil, message=nil) #:nodoc:
msg = build_message(message, "<?> is not in the flash <?>", key, @response.flash)
assert_block(msg) { @response.has_flash_object?(key) }
end
deprecate :assert_flash_has => "use assert(@response.has_flash_object?(key))"
# ensure that the flash has no object with the specified name
def assert_flash_has_no(key=nil, message=nil) #:nodoc:
msg = build_message(message, "<?> is in the flash <?>", key, @response.flash)
assert_block(msg) { !@response.has_flash_object?(key) }
end
deprecate :assert_flash_has_no => "use assert(!@response.has_flash_object?(key))"
# ensure the flash exists
def assert_flash_exists(message=nil) #:nodoc:
msg = build_message(message, "the flash does not exist <?>", @response.session['flash'] )
assert_block(msg) { @response.has_flash? }
end
deprecate :assert_flash_exists => "use assert(@response.has_flash?)"
# ensure the flash does not exist
def assert_flash_not_exists(message=nil) #:nodoc:
msg = build_message(message, "the flash exists <?>", @response.flash)
assert_block(msg) { !@response.has_flash? }
end
deprecate :assert_flash_not_exists => "use assert(!@response.has_flash?)"
# ensure the flash is empty but existent
def assert_flash_empty(message=nil) #:nodoc:
msg = build_message(message, "the flash is not empty <?>", @response.flash)
assert_block(msg) { !@response.has_flash_with_contents? }
end
deprecate :assert_flash_empty => "use assert(!@response.has_flash_with_contents?)"
# ensure the flash is not empty
def assert_flash_not_empty(message=nil) #:nodoc:
msg = build_message(message, "the flash is empty")
assert_block(msg) { @response.has_flash_with_contents? }
end
deprecate :assert_flash_not_empty => "use assert(@response.has_flash_with_contents?)"
def assert_flash_equal(expected = nil, key = nil, message = nil) #:nodoc:
msg = build_message(message, "<?> expected in flash['?'] but was <?>", expected, key, @response.flash[key])
assert_block(msg) { expected == @response.flash[key] }
end
deprecate :assert_flash_equal => "use assert_equal(expected, @response.flash[key])"
# ensure our redirection url is an exact match
def assert_redirect_url(url=nil, message=nil) #:nodoc:
assert_redirect(message)
msg = build_message(message, "<?> is not the redirected location <?>", url, @response.redirect_url)
assert_block(msg) { @response.redirect_url == url }
end
deprecate :assert_redirect_url => "use assert_equal(url, @response.redirect_url)"
# ensure our redirection url matches a pattern
def assert_redirect_url_match(pattern=nil, message=nil) #:nodoc:
assert_redirect(message)
msg = build_message(message, "<?> was not found in the location: <?>", pattern, @response.redirect_url)
assert_block(msg) { @response.redirect_url_match?(pattern) }
end
deprecate :assert_redirect_url_match => "use assert(@response.redirect_url_match?(pattern))"
# -- template assertions ------------------------------------------------
# ensure that a template object with the given name exists
def assert_template_has(key=nil, message=nil) #:nodoc:
msg = build_message(message, "<?> is not a template object", key )
assert_block(msg) { @response.has_template_object?(key) }
end
deprecate :assert_template_has => "use assert(@response.has_template_object?(key))"
# ensure that a template object with the given name does not exist
def assert_template_has_no(key=nil,message=nil) #:nodoc:
msg = build_message(message, "<?> is a template object <?>", key, @response.template_objects[key])
assert_block(msg) { !@response.has_template_object?(key) }
end
deprecate :assert_template_has_no => "use assert(!@response.has_template_object?(key))"
# ensures that the object assigned to the template on +key+ is equal to +expected+ object.
def assert_template_equal(expected = nil, key = nil, message = nil) #:nodoc:
msg = build_message(message, "<?> expected in assigns['?'] but was <?>", expected, key, @response.template.assigns[key.to_s])
assert_block(msg) { expected == @response.template.assigns[key.to_s] }
end
alias_method :assert_assigned_equal, :assert_template_equal
deprecate :assert_assigned_equal => "use assert_equal(expected, @response.template.assigns[key.to_s])"
deprecate :assert_template_equal => "use assert_equal(expected, @response.template.assigns[key.to_s])"
# Asserts that the template returns the +expected+ string or array based on the XPath +expression+.
# This will only work if the template rendered a valid XML document.
def assert_template_xpath_match(expression=nil, expected=nil, message=nil) #:nodoc:
xml, matches = REXML::Document.new(@response.body), []
xml.elements.each(expression) { |e| matches << e.text }
if matches.empty? then
msg = build_message(message, "<?> not found in document", expression)
flunk(msg)
return
elsif matches.length < 2 then
matches = matches.first
end
msg = build_message(message, "<?> found <?>, not <?>", expression, matches, expected)
assert_block(msg) { matches == expected }
end
deprecate :assert_template_xpath_match => "you should use assert_tag, instead"
# Assert the template object with the given name is an Active Record descendant and is valid.
def assert_valid_record(key = nil, message = nil) #:nodoc:
record = find_record_in_template(key)
msg = build_message(message, "Active Record is invalid <?>)", record.errors.full_messages)
assert_block(msg) { record.valid? }
end
deprecate :assert_valid_record => "use assert(assigns(key).valid?)"
# Assert the template object with the given name is an Active Record descendant and is invalid.
def assert_invalid_record(key = nil, message = nil) #:nodoc:
record = find_record_in_template(key)
msg = build_message(message, "Active Record is valid)")
assert_block(msg) { !record.valid? }
end
deprecate :assert_invalid_record => "use assert(!assigns(key).valid?)"
# Assert the template object with the given name is an Active Record descendant and the specified column(s) are valid.
def assert_valid_column_on_record(key = nil, columns = "", message = nil) #:nodoc:
record = find_record_in_template(key)
record.send(:validate)
cols = glue_columns(columns)
cols.delete_if { |col| !record.errors.invalid?(col) }
msg = build_message(message, "Active Record has invalid columns <?>)", cols.join(",") )
assert_block(msg) { cols.empty? }
end
deprecate :assert_valid_column_on_record => "use assert(!record.errors.invalid?(column)) instead"
# Assert the template object with the given name is an Active Record descendant and the specified column(s) are invalid.
def assert_invalid_column_on_record(key = nil, columns = "", message = nil) #:nodoc:
record = find_record_in_template(key)
record.send(:validate)
cols = glue_columns(columns)
cols.delete_if { |col| record.errors.invalid?(col) }
msg = build_message(message, "Active Record has valid columns <?>)", cols.join(",") )
assert_block(msg) { cols.empty? }
end
deprecate :assert_invalid_column_on_record => "use assert(record.errors.invalid?(column)) instead"
private
def glue_columns(columns)
cols = []
cols << columns if columns.class == String
cols += columns if columns.class == Array
cols
end
def find_record_in_template(key = nil)
assert_not_nil assigns(key)
record = @response.template_objects[key]
assert_not_nil(record)
assert_kind_of ActiveRecord::Base, record
return record
end
end
end
end

View file

@ -2,24 +2,38 @@ module ActionController
module Assertions
module DomAssertions
# Test two HTML strings for equivalency (e.g., identical up to reordering of attributes)
def assert_dom_equal(expected, actual, message="")
#
# ==== Examples
#
# # assert that the referenced method generates the appropriate HTML string
# assert_dom_equal '<a href="http://www.example.com">Apples</a>', link_to("Apples", "http://www.example.com")
#
def assert_dom_equal(expected, actual, message = "")
clean_backtrace do
expected_dom = HTML::Document.new(expected).root
actual_dom = HTML::Document.new(actual).root
actual_dom = HTML::Document.new(actual).root
full_message = build_message(message, "<?> expected to be == to\n<?>.", expected_dom.to_s, actual_dom.to_s)
assert_block(full_message) { expected_dom == actual_dom }
end
end
# The negated form of +assert_dom_equivalent+.
def assert_dom_not_equal(expected, actual, message="")
#
# ==== Examples
#
# # assert that the referenced method does not generate the specified HTML string
# assert_dom_not_equal '<a href="http://www.example.com">Apples</a>', link_to("Oranges", "http://www.example.com")
#
def assert_dom_not_equal(expected, actual, message = "")
clean_backtrace do
expected_dom = HTML::Document.new(expected).root
actual_dom = HTML::Document.new(actual).root
full_message = build_message(message, "<?> expected to be != to\n<?>.", expected_dom.to_s, actual_dom.to_s)
assert_block(full_message) { expected_dom != actual_dom }
end
end
end
end
end
end

View file

@ -2,6 +2,13 @@ module ActionController
module Assertions
module ModelAssertions
# Ensures that the passed record is valid by ActiveRecord standards and returns any error messages if it is not.
#
# ==== Examples
#
# # assert that a newly created record is valid
# model = Model.new
# assert_valid(model)
#
def assert_valid(record)
clean_backtrace do
assert record.valid?, record.errors.full_messages.join("\n")
@ -9,4 +16,4 @@ module ActionController
end
end
end
end
end

View file

@ -1,19 +1,29 @@
require 'rexml/document'
require File.dirname(__FILE__) + "/../vendor/html-scanner/html/document"
require 'html/document'
module ActionController
module Assertions
# A small suite of assertions that test responses from Rails applications.
module ResponseAssertions
# Asserts that the response is one of the following types:
#
# * <tt>:success</tt>: Status code was 200
# * <tt>:redirect</tt>: Status code was in the 300-399 range
# * <tt>:missing</tt>: Status code was 404
# * <tt>:error</tt>: Status code was in the 500-599 range
# * <tt>:success</tt> - Status code was 200
# * <tt>:redirect</tt> - Status code was in the 300-399 range
# * <tt>:missing</tt> - Status code was 404
# * <tt>:error</tt> - Status code was in the 500-599 range
#
# You can also pass an explicit status number like assert_response(501)
# or its symbolic equivalent assert_response(:not_implemented).
# See ActionController::StatusCodes for a full list.
#
# ==== Examples
#
# # assert that the response was a redirection
# assert_response :redirect
#
# # assert that the response code was status code 401 (unauthorized)
# assert_response 401
#
def assert_response(type, message = nil)
clean_backtrace do
if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?")
@ -28,9 +38,18 @@ module ActionController
end
end
# Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial,
# such that assert_redirected_to(:controller => "weblog") will also match the redirection of
# redirect_to(:controller => "weblog", :action => "show") and so on.
# Assert that the redirection options passed in match those of the redirect called in the latest action.
# This match can be partial, such that assert_redirected_to(:controller => "weblog") will also
# match the redirection of redirect_to(:controller => "weblog", :action => "show") and so on.
#
# ==== Examples
#
# # assert that the redirection was to the "index" action on the WeblogController
# assert_redirected_to :controller => "weblog", :action => "index"
#
# # assert that the redirection was to the named route login_url
# assert_redirected_to login_url
#
def assert_redirected_to(options = {}, message=nil)
clean_backtrace do
assert_response(:redirect, message)
@ -79,10 +98,8 @@ module ActionController
url[key] = value
end
@response_diff = url[:expected].diff(url[:actual]) if url[:actual]
msg = build_message(message, "response is not a redirection to all of the options supplied (redirection is <?>), difference: <?>",
url[:actual], @response_diff)
@response_diff = url[:actual].diff(url[:expected]) if url[:actual]
msg = build_message(message, "expected a redirect to <?>, found one to <?>, a difference of <?> ", url[:expected], url[:actual], @response_diff)
assert_block(msg) do
url[:expected].keys.all? do |k|
@ -106,6 +123,12 @@ module ActionController
end
# Asserts that the request was rendered with the appropriate template file.
#
# ==== Examples
#
# # assert that the "new" view template was rendered
# assert_template "new"
#
def assert_template(expected = nil, message=nil)
clean_backtrace do
rendered = expected ? @response.rendered_file(!expected.include?('/')) : @response.rendered_file

View file

@ -1,25 +1,41 @@
module ActionController
module Assertions
# Suite of assertions to test routes generated by Rails and the handling of requests made to them.
module RoutingAssertions
# Asserts that the routing of the given path was handled correctly and that the parsed options match.
# Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash)
# match +path+. Basically, it asserts that Rails recognizes the route given by +expected_options+.
#
# assert_recognizes({:controller => 'items', :action => 'index'}, 'items') # check the default action
# assert_recognizes({:controller => 'items', :action => 'list'}, 'items/list') # check a specific action
# assert_recognizes({:controller => 'items', :action => 'list', :id => '1'}, 'items/list/1') # check an action with a parameter
#
# Pass a hash in the second argument to specify the request method. This is useful for routes
# Pass a hash in the second argument (+path+) to specify the request method. This is useful for routes
# requiring a specific HTTP method. The hash should contain a :path with the incoming request path
# and a :method containing the required HTTP verb.
#
# # assert that POSTing to /items will call the create action on ItemsController
# assert_recognizes({:controller => 'items', :action => 'create'}, {:path => 'items', :method => :post})
#
# You can also pass in "extras" with a hash containing URL parameters that would normally be in the query string. This can be used
# You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
# to assert that values in the query string string will end up in the params hash correctly. To test query strings you must use the
# extras argument, appending the query string on the path directly will not work. For example:
#
# # assert that a path of '/items/list/1?view=print' returns the correct options
# assert_recognizes({:controller => 'items', :action => 'list', :id => '1', :view => 'print'}, 'items/list/1', { :view => "print" })
#
# The +message+ parameter allows you to pass in an error message that is displayed upon failure.
#
# ==== Examples
# # Check the default route (i.e., the index action)
# assert_recognizes({:controller => 'items', :action => 'index'}, 'items')
#
# # Test a specific action
# assert_recognizes({:controller => 'items', :action => 'list'}, 'items/list')
#
# # Test an action with a parameter
# assert_recognizes({:controller => 'items', :action => 'destroy', :id => '1'}, 'items/destroy/1')
#
# # Test a custom route
# assert_recognizes({:controller => 'items', :action => 'show', :id => '1'}, 'view/item1')
#
# # Check a Simply RESTful generated route
# assert_recognizes(list_items_url, 'items/list')
def assert_recognizes(expected_options, path, extras={}, message=nil)
if path.is_a? Hash
request_method = path[:method]
@ -43,12 +59,24 @@ module ActionController
end
end
# Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes.
# For example:
# Asserts that the provided options can be used to generate the provided path. This is the inverse of #assert_recognizes.
# The +extras+ parameter is used to tell the request the names and values of additional request parameters that would be in
# a query string. The +message+ parameter allows you to specify a custom error message for assertion failures.
#
# The +defaults+ parameter is unused.
#
# ==== Examples
# # Asserts that the default action is generated for a route with no action
# assert_generates("/items", :controller => "items", :action => "index")
#
# # Tests that the list action is properly routed
# assert_generates("/items/list", :controller => "items", :action => "list")
#
# # Tests the generation of a route with a parameter
# assert_generates("/items/list/1", { :controller => "items", :action => "list", :id => "1" })
#
# # Asserts that the generated route gives us our custom route
# assert_generates "changesets/12", { :controller => 'scm', :action => 'show_diff', :revision => "12" }
def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)
clean_backtrace do
expected_path = "/#{expected_path}" unless expected_path[0] == ?/
@ -67,9 +95,25 @@ module ActionController
end
end
# Asserts that path and options match both ways; in other words, the URL generated from
# options is the same as path, and also that the options recognized from path are the same as options. This
# essentially combines assert_recognizes and assert_generates into one step.
# Asserts that path and options match both ways; in other words, it verifies that <tt>path</tt> generates
# <tt>options</tt> and then that <tt>options</tt> generates <tt>path</tt>. This essentially combines #assert_recognizes
# and #assert_generates into one step.
#
# The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The
# +message+ parameter allows you to specify a custom error message to display upon failure.
#
# ==== Examples
# # Assert a basic route: a controller with the default action (index)
# assert_routing('/home', :controller => 'home', :action => 'index')
#
# # Test a route generated with a specific controller, action, and parameter (id)
# assert_routing('/entries/show/23', :controller => 'entries', :action => 'show', id => 23)
#
# # Assert a basic route (controller + default action), with an error message if it fails
# assert_routing('/store', { :controller => 'store', :action => 'index' }, {}, {}, 'Route for store index not generated properly')
#
# # Tests a route, providing a defaults hash
# assert_routing 'controller/action/9', {:id => "9", :item => "square"}, {:controller => "controller", :action => "action"}, {}, {:item => "square"}
def assert_routing(path, options, defaults={}, extras={}, message=nil)
assert_recognizes(options, path, extras, message)

View file

@ -4,7 +4,7 @@
#++
require 'rexml/document'
require File.dirname(__FILE__) + "/../vendor/html-scanner/html/document"
require 'html/document'
module ActionController
module Assertions
@ -13,15 +13,13 @@ module ActionController
end
# 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
# 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_rjs -- Assertions on HTML content of RJS update and
# insertion operations.
@ -29,7 +27,7 @@ module ActionController
# for example for dealing with feed item descriptions.
# * #assert_select_email -- Assertions on the HTML body of an e-mail.
#
# Also see HTML::Selector for learning how to use selectors.
# Also see HTML::Selector to learn how to use selectors.
module SelectorAssertions
# :call-seq:
# css_select(selector) => array
@ -49,12 +47,26 @@ module ActionController
# The selector may be a CSS selector expression (+String+), an expression
# with substitution values (+Array+) or an HTML::Selector object.
#
# For example:
# ==== 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
#
def css_select(*args)
# See assert_select to understand what's going on here.
arg = args.shift
@ -66,6 +78,7 @@ module ActionController
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?"
elsif @selected
matches = []
@selected.each do |selected|
subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup))
subset.each do |match|
@ -105,12 +118,13 @@ module ActionController
# response HTML. Calling #assert_select inside an #assert_select block will
# run the assertion for each element selected by the enclosing assertion.
#
# For example:
# ==== 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"
@ -148,7 +162,7 @@ module ActionController
# 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
# ==== Examples
#
# # At least one form element
# assert_select "form"
@ -196,7 +210,7 @@ module ActionController
# Otherwise just operate on the response document.
root = response_from_page_or_rjs
end
# First or second argument is the selector: string and we pass
# all remaining arguments. Array and we pass the argument. Also
# accepts selector itself.
@ -209,7 +223,7 @@ module ActionController
selector = arg
else raise ArgumentError, "Expecting a selector as the first argument"
end
# Next argument is used for equality tests.
equals = {}
case arg = args.shift
@ -277,14 +291,10 @@ module ActionController
# found one but expecting two.
message ||= content_mismatch if matches.empty?
# Test minimum/maximum occurrence.
if equals[:minimum]
assert matches.size >= equals[:minimum], message ||
"Expected at least #{equals[:minimum]} elements, found #{matches.size}."
end
if equals[:maximum]
assert matches.size <= equals[:maximum], message ||
"Expected at most #{equals[:maximum]} elements, found #{matches.size}."
end
min, max = equals[:minimum], equals[:maximum]
message = message || %(Expected #{count_description(min, max)} matching "#{selector.to_s}", found #{matches.size}.)
assert matches.size >= min, message if min
assert matches.size <= max, message if max
# If a block is given call that block. Set @selected to allow
# nested assert_select, which can be nested several levels deep.
@ -300,7 +310,19 @@ module ActionController
# Returns all matches elements.
matches
end
def count_description(min, max) #:nodoc:
pluralize = lambda {|word, quantity| word << (quantity == 1 ? '' : 's')}
if min && max && (max != min)
"between #{min} and #{max} elements"
elsif min && !(min == 1 && max == 1)
"at least #{min} #{pluralize['element', min]}"
elsif max
"at most #{max} #{pluralize['element', max]}"
end
end
# :call-seq:
# assert_select_rjs(id?) { |elements| ... }
# assert_select_rjs(statement, id?) { |elements| ... }
@ -317,12 +339,17 @@ module ActionController
# 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+.
# of that type. Possible values are <tt>:replace</tt>, <tt>:replace_html</tt>,
# <tt>:show</tt>, <tt>:hide</tt>, <tt>:toggle</tt>, <tt>:remove</tt> and
# <tt>:insert_html</tt>.
#
# Use the argument +:insert+ followed by an insertion position to narrow
# Use the argument <tt>:insert</tt> 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+.
# position. Possible values are <tt>:top</tt>, <tt>:bottom</tt>, <tt>:before</tt>
# and <tt>:after</tt>.
#
# Using the <tt>:remove</tt> 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
#
@ -339,7 +366,7 @@ module ActionController
# but without distinguishing whether the content is returned in an HTML
# or JavaScript.
#
# === Examples
# ==== Examples
#
# # Replacing the element foo.
# # page.replace 'foo', ...
@ -352,6 +379,9 @@ module ActionController
# # 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""
@ -373,6 +403,7 @@ module ActionController
# any RJS statement.
if arg.is_a?(Symbol)
rjs_type = arg
if rjs_type == :insert
arg = args.shift
insertion = "insert_#{arg}".to_sym
@ -400,20 +431,29 @@ module ActionController
case rjs_type
when :chained_replace, :chained_replace_html
Regexp.new("\\$\\(\"#{id}\"\\)#{statement}\\(#{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE)
when :remove, :show, :hide, :toggle
Regexp.new("#{statement}\\(\"#{id}\"\\)")
else
Regexp.new("#{statement}\\(\"#{id}\", #{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE)
end
# Duplicate the body since the next step involves destroying it.
matches = nil
@response.body.gsub(pattern) do |match|
html = unescape_rjs($2)
matches ||= []
matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? }
""
case rjs_type
when :remove, :show, :hide, :toggle
matches = @response.body.match(pattern)
else
@response.body.gsub(pattern) do |match|
html = unescape_rjs($2)
matches ||= []
matches.concat HTML::Document.new(html).root.children.select { |n| n.tag? }
""
end
end
if matches
if block_given?
assert_block("") { true } # to count the assertion
if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type)
begin
in_scope, @selected = @selected, matches
yield matches
@ -441,8 +481,20 @@ module ActionController
# 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
# ==== 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
@ -493,11 +545,19 @@ module ActionController
# You must enable deliveries for this assertion to work, use:
# ActionMailer::Base.perform_deliveries = true
#
# === Example
# ==== 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
#
# assert_select_email do
# assert_select "h1", "Email alert"
# end
def assert_select_email(&block)
deliveries = ActionMailer::Base.deliveries
assert !deliveries.empty?, "No e-mail in delivery list"
@ -519,6 +579,10 @@ module ActionController
:replace_html => /Element\.update/,
:chained_replace => /\.replace/,
:chained_replace_html => /\.update/,
:remove => /Element\.remove/,
:show => /Element\.show/,
:hide => /Element\.hide/,
:toggle => /Element\.toggle/
}
RJS_INSERTIONS = [:top, :bottom, :before, :after]
RJS_INSERTIONS.each do |insertion|
@ -537,10 +601,12 @@ module ActionController
# #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.
def response_from_page_or_rjs()
content_type = @response.headers["Content-Type"]
content_type = @response.content_type
if content_type && content_type =~ /text\/javascript/
body = @response.body.dup
root = HTML::Node.new(nil)
while true
next if body.sub!(RJS_PATTERN_EVERYTHING) do |match|
html = unescape_rjs($3)
@ -550,6 +616,7 @@ module ActionController
end
break
end
root
else
html_document.root
@ -560,6 +627,7 @@ module ActionController
def unescape_rjs(rjs_string)
# RJS encodes double quotes and line breaks.
unescaped= rjs_string.gsub('\"', '"')
unescaped.gsub!(/\\\//, '/')
unescaped.gsub!('\n', "\n")
unescaped.gsub!('\076', '>')
unescaped.gsub!('\074', '<')
@ -567,7 +635,6 @@ module ActionController
unescaped.gsub!(RJS_PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')}
unescaped
end
end
end
end

View file

@ -1,8 +1,9 @@
require 'rexml/document'
require File.dirname(__FILE__) + "/../vendor/html-scanner/html/document"
require 'html/document'
module ActionController
module Assertions
# Pair of assertions to testing elements in the HTML output of the response.
module TagAssertions
# Asserts that there is a tag/node/element in the body of the response
# that meets all of the given conditions. The +conditions+ parameter must
@ -37,8 +38,8 @@ module ActionController
# to match on the children, and only matching children will be
# counted.
# * <tt>:content</tt>: the textual content of the node must match the
# given value. This will not match HTML tags in the body of a
# tag--only text.
# given value. This will not match HTML tags in the body of a
# tag--only text.
#
# Conditions are matched using the following algorithm:
#
@ -48,39 +49,39 @@ module ActionController
# * if the condition is +true+, the value must not be +nil+.
# * if the condition is +false+ or +nil+, the value must be +nil+.
#
# Usage:
# === Examples
#
# # assert that there is a "span" tag
# # Assert that there is a "span" tag
# assert_tag :tag => "span"
#
# # assert that there is a "span" tag with id="x"
# # Assert that there is a "span" tag with id="x"
# assert_tag :tag => "span", :attributes => { :id => "x" }
#
# # assert that there is a "span" tag using the short-hand
# # Assert that there is a "span" tag using the short-hand
# assert_tag :span
#
# # assert that there is a "span" tag with id="x" using the short-hand
# # Assert that there is a "span" tag with id="x" using the short-hand
# assert_tag :span, :attributes => { :id => "x" }
#
# # assert that there is a "span" inside of a "div"
# # Assert that there is a "span" inside of a "div"
# assert_tag :tag => "span", :parent => { :tag => "div" }
#
# # assert that there is a "span" somewhere inside a table
# # Assert that there is a "span" somewhere inside a table
# assert_tag :tag => "span", :ancestor => { :tag => "table" }
#
# # assert that there is a "span" with at least one "em" child
# # Assert that there is a "span" with at least one "em" child
# assert_tag :tag => "span", :child => { :tag => "em" }
#
# # assert that there is a "span" containing a (possibly nested)
# # Assert that there is a "span" containing a (possibly nested)
# # "strong" tag.
# assert_tag :tag => "span", :descendant => { :tag => "strong" }
#
# # assert that there is a "span" containing between 2 and 4 "em" tags
# # Assert that there is a "span" containing between 2 and 4 "em" tags
# # as immediate children
# assert_tag :tag => "span",
# :children => { :count => 2..4, :only => { :tag => "em" } }
#
# # get funky: assert that there is a "div", with an "ul" ancestor
# # Get funky: assert that there is a "div", with an "ul" ancestor
# # and an "li" parent (with "class" = "enum"), and containing a
# # "span" descendant that contains text matching /hello world/
# assert_tag :tag => "div",
@ -90,7 +91,7 @@ module ActionController
# :descendant => { :tag => "span",
# :child => /hello world/ }
#
# <strong>Please note</strong: #assert_tag and #assert_no_tag only work
# <b>Please note</b>: #assert_tag and #assert_no_tag only work
# with well-formed XHTML. They recognize a few tags as implicitly self-closing
# (like br and hr and such) but will not work correctly with tags
# that allow optional closing tags (p, li, td). <em>You must explicitly
@ -105,6 +106,18 @@ module ActionController
# Identical to #assert_tag, but asserts that a matching tag does _not_
# exist. (See #assert_tag for a full discussion of the syntax.)
#
# === Examples
# # Assert that there is not a "div" containing a "p"
# assert_no_tag :tag => "div", :descendant => { :tag => "p" }
#
# # Assert that an unordered list is empty
# assert_no_tag :tag => "ul", :descendant => { :tag => "li" }
#
# # Assert that there is not a "p" tag with between 1 to 3 "img" tags
# # as immediate children
# assert_no_tag :tag => "p",
# :children => { :count => 1..3, :only => { :tag => "img" } }
def assert_no_tag(*opts)
clean_backtrace do
opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first