Module: Test::Unit::Assertions

Defined in:
lib/action_controller/assertions.rb,
lib/action_controller/deprecated_assertions.rb

Overview

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:

  • assigns: Instance variables assigned in the action that’s available for the view.

  • session: Objects being saved in the session.

  • flash: The flash objects being currently in the session.

  • cookies: Cookies being sent to the user on this request.

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 won’t work, but assigns 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, but again, assigns 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 follow triggering another action call which can then be asserted against.

Manipulating the request collections

The collections described above link to the response, so you can test if what the actions were expected to do happen. But some times you also want to manipulate these collections in the request coming in. 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")

Testing named routes

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')

Instance Method Summary collapse

Instance Method Details

:nodoc:



45
46
47
48
49
50
# File 'lib/action_controller/deprecated_assertions.rb', line 45

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

#assert_dom_equal(expected, actual, message = "") ⇒ Object

test 2 html strings to be equivalent, i.e. identical up to reordering of attributes



268
269
270
271
272
273
274
275
# File 'lib/action_controller/assertions.rb', line 268

def assert_dom_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

#assert_dom_not_equal(expected, actual, message = "") ⇒ Object

negated form of assert_dom_equivalent



278
279
280
281
282
283
284
285
# File 'lib/action_controller/assertions.rb', line 278

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

#assert_flash_empty(message = nil) ⇒ Object

ensure the flash is empty but existent



79
80
81
82
# File 'lib/action_controller/deprecated_assertions.rb', line 79

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

#assert_flash_equal(expected = nil, key = nil, message = nil) ⇒ Object

:nodoc:



90
91
92
93
# File 'lib/action_controller/deprecated_assertions.rb', line 90

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

#assert_flash_exists(message = nil) ⇒ Object

ensure the flash exists



67
68
69
70
# File 'lib/action_controller/deprecated_assertions.rb', line 67

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

#assert_flash_has(key = nil, message = nil) ⇒ Object

ensure that the flash has an object with the specified name



55
56
57
58
# File 'lib/action_controller/deprecated_assertions.rb', line 55

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

#assert_flash_has_no(key = nil, message = nil) ⇒ Object

ensure that the flash has no object with the specified name



61
62
63
64
# File 'lib/action_controller/deprecated_assertions.rb', line 61

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

#assert_flash_not_empty(message = nil) ⇒ Object

ensure the flash is not empty



85
86
87
88
# File 'lib/action_controller/deprecated_assertions.rb', line 85

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

#assert_flash_not_exists(message = nil) ⇒ Object

ensure the flash does not exist



73
74
75
76
# File 'lib/action_controller/deprecated_assertions.rb', line 73

def assert_flash_not_exists(message=nil) #:nodoc:
  msg = build_message(message, "the flash exists <?>", @response.flash)
  assert_block(msg) { !@response.has_flash? }
end

#assert_generates(expected_path, options, defaults = {}, extras = {}, message = nil) ⇒ Object

Asserts that the provided options can be used to generate the provided path.



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/action_controller/assertions.rb', line 144

def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)
  clean_backtrace do 
    expected_path = "/#{expected_path}" unless expected_path[0] == ?/
    # Load routes.rb if it hasn't been loaded.
    ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty? 

    generated_path, extra_keys = ActionController::Routing::Routes.generate(options, extras)
    found_extras = options.reject {|k, v| ! extra_keys.include? k}

    msg = build_message(message, "found extras <?>, not <?>", found_extras, extras)
    assert_block(msg) { found_extras == extras }

    msg = build_message(message, "The generated path <?> did not match <?>", generated_path, 
        expected_path)
    assert_block(msg) { expected_path == generated_path }
  end
end

#assert_invalid_column_on_record(key = nil, columns = "", message = nil) ⇒ Object

Assert the template object with the given name is an Active Record descendant and the specified column(s) are invalid.



175
176
177
178
179
180
181
182
183
# File 'lib/action_controller/deprecated_assertions.rb', line 175

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

#assert_invalid_record(key = nil, message = nil) ⇒ Object

Assert the template object with the given name is an Active Record descendant and is invalid.



157
158
159
160
161
# File 'lib/action_controller/deprecated_assertions.rb', line 157

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

– cookie assertions —————————————————



39
40
41
42
43
# File 'lib/action_controller/deprecated_assertions.rb', line 39

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

#assert_no_tag(opts) ⇒ Object

Identical to #assert_tag, but asserts that a matching tag does not exist. (See #assert_tag for a full discussion of the syntax.)



260
261
262
263
264
265
# File 'lib/action_controller/assertions.rb', line 260

def assert_no_tag(opts)
  clean_backtrace do
    tag = find_tag(opts)
    assert !tag, "expected no tag, but found tag matching #{opts.inspect} in:\n#{@response.body.inspect}"
  end
end

#assert_recognizes(expected_options, path, extras = {}, message = nil) ⇒ Object

Asserts that the routing of the given path is handled correctly and that the parsed options match.



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/action_controller/assertions.rb', line 122

def assert_recognizes(expected_options, path, extras={}, message=nil)
  clean_backtrace do 
    path = "/#{path}" unless path[0..0] == '/'
    # Load routes.rb if it hasn't been loaded.
    ActionController::Routing::Routes.reload if ActionController::Routing::Routes.empty? 

    # Assume given controller
    request = ActionController::TestRequest.new({}, {}, nil)
    request.path = path
    ActionController::Routing::Routes.recognize!(request)

    expected_options = expected_options.clone
    extras.each_key { |key| expected_options.delete key } unless extras.nil?

    expected_options.stringify_keys!
    msg = build_message(message, "The recognized options <?> did not match <?>", 
        request.path_parameters, expected_options)
    assert_block(msg) { request.path_parameters == expected_options }
  end
end

#assert_redirect(message = nil) ⇒ Object

:nodoc:



12
13
14
# File 'lib/action_controller/deprecated_assertions.rb', line 12

def assert_redirect(message=nil) #:nodoc:
  assert_response(:redirect, message)
end

#assert_redirect_url(url = nil, message = nil) ⇒ Object

ensure our redirection url is an exact match



97
98
99
100
101
# File 'lib/action_controller/deprecated_assertions.rb', line 97

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

#assert_redirect_url_match(pattern = nil, message = nil) ⇒ Object

ensure our redirection url matches a pattern



104
105
106
107
108
# File 'lib/action_controller/deprecated_assertions.rb', line 104

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

#assert_redirected_to(options = {}, message = nil) ⇒ Object

Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such at assert_redirected_to(:controller => “weblog”) will also match the redirection of redirect_to(:controller => “weblog”, :action => “show”) and so on.



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/action_controller/assertions.rb', line 73

def assert_redirected_to(options = {}, message=nil)
  clean_backtrace do
    assert_response(:redirect, message)

    if options.is_a?(String)
      msg = build_message(message, "expected a redirect to <?>, found one to <?>", options, @response.redirect_url)
      url_regexp = %r{^(\w+://.*?(/|$|\?))(.*)$}
      eurl, epath, url, path = [options, @response.redirect_url].collect do |url|
        u, p = (url_regexp =~ url) ? [$1, $3] : [nil, url]
        [u, (p[0..0] == '/') ? p : '/' + p]
      end.flatten

      assert_equal(eurl, url, msg) if eurl && url
      assert_equal(epath, path, msg) if epath && path 
    else
      msg = build_message(message, "response is not a redirection to all of the options supplied (redirection is <?>)",
                          @response.redirected_to || @response.redirect_url)

      assert_block(msg) do
        if options.is_a?(Symbol)
          @response.redirected_to == options
        else
          options.keys.all? do |k|
            if k == :controller then options[k] == ActionController::Routing.controller_relative_to(@response.redirected_to[k], @controller.class.controller_path)
            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?)
            end
          end
        end
      end
    end
  end
end

#assert_rendered_file(expected = nil, message = nil) ⇒ Object

:nodoc:



16
17
18
# File 'lib/action_controller/deprecated_assertions.rb', line 16

def assert_rendered_file(expected=nil, message=nil) #:nodoc:
  assert_template(expected, message)
end

#assert_response(type, message = nil) ⇒ Object

Asserts that the response is one of the following types:

  • :success: Status code was 200

  • :redirect: Status code was in the 300-399 range

  • :missing: Status code was 404

  • :error: Status code was in the 500-599 range

You can also pass an explicit status code number as the type, like assert_response(501)



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/action_controller/assertions.rb', line 58

def assert_response(type, message = nil)
  clean_backtrace do
    if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?")
      assert_block("") { true } # to count the assertion
    elsif type.is_a?(Fixnum) && @response.response_code == type
      assert_block("") { true } # to count the assertion
    else
      assert_block(build_message(message, "Expected response to be a <?>, but was <?>", type, @response.response_code)) { false }
    end               
  end
end

#assert_routing(path, options, defaults = {}, extras = {}, message = nil) ⇒ Object

asserts that path and options match both ways, in other words, the URL generated from options is same as path, and also that the options recognized from path are same as options



164
165
166
167
168
169
170
171
172
173
# File 'lib/action_controller/assertions.rb', line 164

def assert_routing(path, options, defaults={}, extras={}, message=nil)
  assert_recognizes(options, path, extras, message)
  
  controller, default_controller = options[:controller], defaults[:controller] 
  if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
    options[:controller] = "/#{controller}"
  end
   
  assert_generates(path, options, defaults, extras, message)
end

#assert_session_equal(expected = nil, key = nil, message = nil) ⇒ Object

:nodoc:



32
33
34
35
# File 'lib/action_controller/deprecated_assertions.rb', line 32

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

#assert_session_has(key = nil, message = nil) ⇒ Object

ensure that the session has an object with the specified name



21
22
23
24
# File 'lib/action_controller/deprecated_assertions.rb', line 21

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

#assert_session_has_no(key = nil, message = nil) ⇒ Object

ensure that the session has no object with the specified name



27
28
29
30
# File 'lib/action_controller/deprecated_assertions.rb', line 27

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

#assert_success(message = nil) ⇒ Object

:nodoc:



8
9
10
# File 'lib/action_controller/deprecated_assertions.rb', line 8

def assert_success(message=nil) #:nodoc:
  assert_response(:success, message)
end

#assert_tag(opts) ⇒ Object

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):

  • :tag: the node type must match the corresponding value

  • :attributes: a hash. The node’s attributes must match the corresponding values in the hash.

  • :parent: a hash. The node’s parent must match the corresponding hash.

  • :child: a hash. At least one of the node’s immediate children must meet the criteria described by the hash.

  • :ancestor: a hash. At least one of the node’s ancestors must meet the criteria described by the hash.

  • :descendant: a hash. At least one of the node’s descendants must meet the criteria described by the hash.

  • :sibling: a hash. At least one of the node’s siblings must meet the criteria described by the hash.

  • :after: a hash. The node must be after any sibling meeting the criteria described by the hash, and at least one sibling must match.

  • :before: a hash. The node must be before any sibling meeting the criteria described by the hash, and at least one sibling must match.

  • :children: a hash, for counting children of a node. Accepts the keys:

    • :count: either a number or a range which must equal (or include) the number of children that match.

    • :less_than: the number of matching children must be less than this number.

    • :greater_than: the number of matching children must be greater than this number.

    • :only: another hash consisting of the keys to use to match on the children, and only matching children will be counted.

  • :content: 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.
    

Conditions are matched using the following algorithm:

  • if the condition is a string, it must be a substring of the value.

  • if the condition is a regexp, it must match the value.

  • if the condition is a number, the value must match number.to_s.

  • if the condition is true, the value must not be nil.

  • if the condition is false or nil, the value must be nil.

Usage:

# assert that there is a "span" tag
assert_tag :tag => "span"

# 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/ }


251
252
253
254
255
256
# File 'lib/action_controller/assertions.rb', line 251

def assert_tag(opts)
  clean_backtrace do
    tag = find_tag(opts)
    assert tag, "expected tag, but no tag found matching #{opts.inspect} in:\n#{@response.body.inspect}"
  end
end

#assert_template(expected = nil, message = nil) ⇒ Object

Asserts that the request was rendered with the appropriate template file.



107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/action_controller/assertions.rb', line 107

def assert_template(expected = nil, message=nil)
  clean_backtrace do
    rendered = expected ? @response.rendered_file(!expected.include?('/')) : @response.rendered_file
    msg = build_message(message, "expecting <?> but rendering with <?>", expected, rendered)
    assert_block(msg) do
      if expected.nil?
        !@response.rendered_with_file?
      else
        expected == rendered
      end
    end               
  end
end

#assert_template_equal(expected = nil, key = nil, message = nil) ⇒ Object Also known as: assert_assigned_equal

ensures that the object assigned to the template on key is equal to expected object.



126
127
128
129
# File 'lib/action_controller/deprecated_assertions.rb', line 126

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

#assert_template_has(key = nil, message = nil) ⇒ Object

ensure that a template object with the given name exists



114
115
116
117
# File 'lib/action_controller/deprecated_assertions.rb', line 114

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

#assert_template_has_no(key = nil, message = nil) ⇒ Object

ensure that a template object with the given name does not exist



120
121
122
123
# File 'lib/action_controller/deprecated_assertions.rb', line 120

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

#assert_template_xpath_match(expression = nil, expected = nil, message = nil) ⇒ Object

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.



134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/action_controller/deprecated_assertions.rb', line 134

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

#assert_valid(record) ⇒ Object

ensures that the passed record is valid by active record standards. returns the error messages if not



288
289
290
291
292
# File 'lib/action_controller/assertions.rb', line 288

def assert_valid(record)                                   
  clean_backtrace do
    assert record.valid?, record.errors.full_messages        
  end
end

#assert_valid_column_on_record(key = nil, columns = "", message = nil) ⇒ Object

Assert the template object with the given name is an Active Record descendant and the specified column(s) are valid.



164
165
166
167
168
169
170
171
172
# File 'lib/action_controller/deprecated_assertions.rb', line 164

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

#assert_valid_record(key = nil, message = nil) ⇒ Object

Assert the template object with the given name is an Active Record descendant and is valid.



150
151
152
153
154
# File 'lib/action_controller/deprecated_assertions.rb', line 150

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

#clean_backtrace(&block) ⇒ Object



294
295
296
297
298
299
300
301
# File 'lib/action_controller/assertions.rb', line 294

def clean_backtrace(&block)
  begin
    yield
  rescue AssertionFailedError => e         
    path = File.expand_path(__FILE__)
    raise AssertionFailedError, e.message, e.backtrace.reject { |line| File.expand_path(line) =~ /#{path}/ }
  end           
end