Module | Test::Unit::Assertions |
In: |
vendor/rails/actionpack/lib/action_controller/assertions.rb
vendor/rails/actionpack/lib/action_controller/deprecated_assertions.rb |
In addition to these specific assertions, you also have easy access to various collections that the regular test/unit assertions can be used against. These collections are:
These collections can be used just like any other hash:
assert_not_nil assigns(:person) # makes sure that a @person instance variable was set assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave" assert flash.empty? # makes sure that there's nothing in the flash
For historic reasons, the assigns hash uses string-based keys. So assigns[:person] won‘t work, but assigns["person"] will. To appease our yearning for symbols, though, an alternative accessor has been deviced using a method call instead of index referencing. So assigns(:person) will work just like assigns["person"], but again, assigns[:person] will not work.
On top of the collections, you have the complete url that a given action redirected to available in redirect_to_url.
For redirects within the same controller, you can even call follow_redirect and the redirect will be followed, triggering another action call which can then be asserted against.
The collections described above link to the response, so you can test if what the actions were expected to do happened. But sometimes you also want to manipulate these collections in the incoming request. This is really only relevant for sessions and cookies, though. For sessions, you just do:
@request.session[:key] = "value"
For cookies, you need to manually create the cookie, like this:
@request.cookies["key"] = CGI::Cookie.new("key", "value")
If you‘re using named routes, they can be easily tested using the original named routes methods straight in the test case. Example:
assert_redirected_to page_url(:title => 'foo')
assert_template_equal | -> | assert_assigned_equal |
test 2 html strings to be equivalent, i.e. identical up to reordering of attributes
# File vendor/rails/actionpack/lib/action_controller/assertions.rb, line 286 286: def assert_dom_equal(expected, actual, message="") 287: clean_backtrace do 288: expected_dom = HTML::Document.new(expected).root 289: actual_dom = HTML::Document.new(actual).root 290: full_message = build_message(message, "<?> expected to be == to\n<?>.", expected_dom.to_s, actual_dom.to_s) 291: assert_block(full_message) { expected_dom == actual_dom } 292: end 293: end
negated form of assert_dom_equivalent
# File vendor/rails/actionpack/lib/action_controller/assertions.rb, line 296 296: def assert_dom_not_equal(expected, actual, message="") 297: clean_backtrace do 298: expected_dom = HTML::Document.new(expected).root 299: actual_dom = HTML::Document.new(actual).root 300: full_message = build_message(message, "<?> expected to be != to\n<?>.", expected_dom.to_s, actual_dom.to_s) 301: assert_block(full_message) { expected_dom != actual_dom } 302: end 303: end
Asserts that the provided options can be used to generate the provided path.
# File vendor/rails/actionpack/lib/action_controller/assertions.rb, line 145 145: def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil) 146: clean_backtrace do 147: expected_path = "/#{expected_path}" unless expected_path[0] == ?/ 148: # Load routes.rb if it hasn't been loaded. 149: ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty? 150: 151: generated_path, extra_keys = ActionController::Routing::Routes.generate(options, extras) 152: found_extras = options.reject {|k, v| ! extra_keys.include? k} 153: 154: msg = build_message(message, "found extras <?>, not <?>", found_extras, extras) 155: assert_block(msg) { found_extras == extras } 156: 157: msg = build_message(message, "The generated path <?> did not match <?>", generated_path, 158: expected_path) 159: assert_block(msg) { expected_path == generated_path } 160: end 161: end
Identical to assert_tag, but asserts that a matching tag does not exist. (See assert_tag for a full discussion of the syntax.)
# File vendor/rails/actionpack/lib/action_controller/assertions.rb, line 277 277: def assert_no_tag(*opts) 278: clean_backtrace do 279: opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first 280: tag = find_tag(opts) 281: assert !tag, "expected no tag, but found tag matching #{opts.inspect} in:\n#{@response.body.inspect}" 282: end 283: end
Asserts that the routing of the given path was handled correctly and that the parsed options match.
# File vendor/rails/actionpack/lib/action_controller/assertions.rb, line 123 123: def assert_recognizes(expected_options, path, extras={}, message=nil) 124: clean_backtrace do 125: path = "/#{path}" unless path[0..0] == '/' 126: # Load routes.rb if it hasn't been loaded. 127: ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty? 128: 129: # Assume given controller 130: request = ActionController::TestRequest.new({}, {}, nil) 131: request.path = path 132: ActionController::Routing::Routes.recognize!(request) 133: 134: expected_options = expected_options.clone 135: extras.each_key { |key| expected_options.delete key } unless extras.nil? 136: 137: expected_options.stringify_keys! 138: msg = build_message(message, "The recognized options <?> did not match <?>", 139: request.path_parameters, expected_options) 140: assert_block(msg) { request.path_parameters == expected_options } 141: end 142: 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.
# File vendor/rails/actionpack/lib/action_controller/assertions.rb, line 73 73: def assert_redirected_to(options = {}, message=nil) 74: clean_backtrace do 75: assert_response(:redirect, message) 76: 77: if options.is_a?(String) 78: msg = build_message(message, "expected a redirect to <?>, found one to <?>", options, @response.redirect_url) 79: url_regexp = %r{^(\w+://.*?(/|$|\?))(.*)$} 80: eurl, epath, url, path = [options, @response.redirect_url].collect do |url| 81: u, p = (url_regexp =~ url) ? [$1, $3] : [nil, url] 82: [u, (p[0..0] == '/') ? p : '/' + p] 83: end.flatten 84: 85: assert_equal(eurl, url, msg) if eurl && url 86: assert_equal(epath, path, msg) if epath && path 87: else 88: @response_diff = options.diff(@response.redirected_to) if options.is_a?(Hash) && @response.redirected_to.is_a?(Hash) 89: msg = build_message(message, "response is not a redirection to all of the options supplied (redirection is <?>)#{', difference: <?>' if @response_diff}", 90: @response.redirected_to || @response.redirect_url, @response_diff) 91: 92: assert_block(msg) do 93: if options.is_a?(Symbol) 94: @response.redirected_to == options 95: else 96: options.keys.all? do |k| 97: if k == :controller then options[k] == ActionController::Routing.controller_relative_to(@response.redirected_to[k], @controller.class.controller_path) 98: else options[k] == (@response.redirected_to[k].respond_to?(:to_param) ? @response.redirected_to[k].to_param : @response.redirected_to[k] unless @response.redirected_to[k].nil?) 99: end 100: end 101: end 102: end 103: end 104: end 105: end
Asserts that the response is one of the following types:
You can also pass an explicit status code number as the type, like assert_response(501)
# File vendor/rails/actionpack/lib/action_controller/assertions.rb, line 58 58: def assert_response(type, message = nil) 59: clean_backtrace do 60: if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?") 61: assert_block("") { true } # to count the assertion 62: elsif type.is_a?(Fixnum) && @response.response_code == type 63: assert_block("") { true } # to count the assertion 64: else 65: assert_block(build_message(message, "Expected response to be a <?>, but was <?>", type, @response.response_code)) { false } 66: end 67: end 68: 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
# File vendor/rails/actionpack/lib/action_controller/assertions.rb, line 165 165: def assert_routing(path, options, defaults={}, extras={}, message=nil) 166: assert_recognizes(options, path, extras, message) 167: 168: controller, default_controller = options[:controller], defaults[:controller] 169: if controller && controller.include?(?/) && default_controller && default_controller.include?(?/) 170: options[:controller] = "/#{controller}" 171: end 172: 173: assert_generates(path, options, defaults, extras, message) 174: end
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 be a hash of any of the following keys (all are optional):
given value. This will not match HTML tags in the body of a tag--only text.
Conditions are matched using the following algorithm:
Usage:
# assert that there is a "span" tag assert_tag :tag => "span" # 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_tag :span # 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_tag :tag => "span", :parent => { :tag => "div" } # 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_tag :tag => "span", :child => { :tag => "em" } # 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 # 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 # and an "li" parent (with "class" = "enum"), and containing a # "span" descendant that contains text matching /hello world/ assert_tag :tag => "div", :ancestor => { :tag => "ul" }, :parent => { :tag => "li", :attributes => { :class => "enum" } }, :descendant => { :tag => "span", :child => /hello world/ }
<strong>Please note</strong: 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). You must explicitly close all of your tags to use these assertions.
# File vendor/rails/actionpack/lib/action_controller/assertions.rb, line 267 267: def assert_tag(*opts) 268: clean_backtrace do 269: opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first 270: tag = find_tag(opts) 271: assert tag, "expected tag, but no tag found matching #{opts.inspect} in:\n#{@response.body.inspect}" 272: end 273: end
Asserts that the request was rendered with the appropriate template file.
# File vendor/rails/actionpack/lib/action_controller/assertions.rb, line 108 108: def assert_template(expected = nil, message=nil) 109: clean_backtrace do 110: rendered = expected ? @response.rendered_file(!expected.include?('/')) : @response.rendered_file 111: msg = build_message(message, "expecting <?> but rendering with <?>", expected, rendered) 112: assert_block(msg) do 113: if expected.nil? 114: !@response.rendered_with_file? 115: else 116: expected == rendered 117: end 118: end 119: end 120: end
ensures that the passed record is valid by active record standards. returns the error messages if not
# File vendor/rails/actionpack/lib/action_controller/assertions.rb, line 306 306: def assert_valid(record) 307: clean_backtrace do 308: assert record.valid?, record.errors.full_messages.join("\n") 309: end 310: end
# File vendor/rails/actionpack/lib/action_controller/assertions.rb, line 312 312: def clean_backtrace(&block) 313: yield 314: rescue AssertionFailedError => e 315: path = File.expand_path(__FILE__) 316: raise AssertionFailedError, e.message, e.backtrace.reject { |line| File.expand_path(line) =~ /#{path}/ } 317: end