PageRenderTime 74ms CodeModel.GetById 18ms RepoModel.GetById 2ms app.codeStats 0ms

/test/test_helper.rb

https://github.com/grantneufeld/wayground-old
Ruby | 182 lines | 103 code | 11 blank | 68 comment | 10 complexity | bc8cc16d0b0e9a901b58ea16b104233f MD5 | raw file
  1. ENV["RAILS_ENV"] = "test"
  2. require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
  3. require 'test_help'
  4. class Test::Unit::TestCase
  5. # Transactional fixtures accelerate your tests by wrapping each test method
  6. # in a transaction that's rolled back on completion. This ensures that the
  7. # test database remains unchanged so your fixtures don't have to be reloaded
  8. # between every test method. Fewer database queries means faster tests.
  9. #
  10. # Read Mike Clark's excellent walkthrough at
  11. # http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
  12. #
  13. # Every Active Record database supports transactions except MyISAM tables
  14. # in MySQL. Turn off transactional fixtures in this case; however, if you
  15. # don't care one way or the other, switching from MyISAM to InnoDB tables
  16. # is recommended.
  17. #
  18. # The only drawback to using transactional fixtures is when you actually
  19. # need to test transactions. Since your test is bracketed by a transaction,
  20. # any transactions started in your code will be automatically rolled back.
  21. self.use_transactional_fixtures = true
  22. # Instantiated fixtures are slow, but give you @david where otherwise you
  23. # would need people(:david). If you don't want to migrate your existing
  24. # test cases which use the @david style and don't mind the speed hit (each
  25. # instantiated fixtures translates to a database query per test method),
  26. # then set this back to true.
  27. self.use_instantiated_fixtures = false
  28. # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
  29. #
  30. # Note: You'll currently still have to declare fixtures explicitly in integration tests
  31. # -- they do not yet inherit this setting
  32. #fixtures :all
  33. # Add more helper methods to be used by all tests here...
  34. # http://blog.caboo.se/articles/2006/11/04/automatically-test-your-associations
  35. # This is a basic “sanity check” for model associations.
  36. # In each unit test, add this (substituting the class for “<class>”):
  37. # def test_associations
  38. # assert check_associations(<class>)
  39. # end
  40. def check_associations(m = nil, ignore = [])
  41. m ||= self.class.to_s.sub(/Test$/, '').constantize
  42. @m = m.new
  43. ig = [ignore].flatten
  44. m.reflect_on_all_associations.each do |assoc|
  45. next if ig.any?{|i| i == assoc.name}
  46. assert_nothing_raised("#{assoc.name} caused an error") do
  47. @m.send(assoc.name, true)
  48. end
  49. end
  50. true
  51. end
  52. # Test that the routes for a resource defined in routes.rb are working as expected.
  53. # E.g., in routes.rb:
  54. # map.resources :things
  55. # controller='things'
  56. # Some routes may be overridden elsewhere in routes.rb. E.g.:
  57. # map.myspecial '/special', :controller=>'things', :action=>'new'
  58. # map.resources :things
  59. # skip=['new']
  60. # If using nested resources, set the nesting array (use singular strings).
  61. # map.resources :nests do |nest|
  62. # nest.resources :things
  63. # end
  64. # nesting=['nest']
  65. # You can add actions in addition to the standard REST actions:
  66. # map.resources :things, :collection=>{:otheraction=>:get}
  67. # Test for routes generated by map.resource (singular).
  68. def assert_routing_for_resource(controller, skip=[], nesting=[], collection={}, member={}, resource=nil)
  69. routes = [
  70. ["new",'/new',{},:get], ["create",'',{},:post],
  71. ["show",'',{},:get], ["edit",'/edit',{},:get],
  72. ["update",'',{},:put], ["destroy",'',{},:delete]
  73. ]
  74. collection.each_pair do |k,v|
  75. routes << [k.to_s, "/#{k}", {}, v]
  76. end
  77. member.each_pair do |k,v|
  78. routes << [k.to_s, "/1/#{k}", {:id=>'1'}, v]
  79. end
  80. check_resource_routing(controller, routes, skip, nesting, resource)
  81. end
  82. # Test for routes generated by map.resources (plural).
  83. def assert_routing_for_resources(controller, skip=[], nesting=[], collection={}, member={}, resource=nil)
  84. routes = [
  85. ["index",'',{},:get], ["new",'/new',{},:get], ["create",'',{},:post],
  86. ["show",'/1',{:id=>'1'},:get], ["edit",'/1/edit',{:id=>'1'},:get],
  87. ["update",'/1',{:id=>'1'},:put], ["destroy",'/1',{:id=>'1'},:delete]
  88. ]
  89. collection.each_pair do |k,v|
  90. routes << [k.to_s, "/#{k}", {}, v]
  91. end
  92. member.each_pair do |k,v|
  93. routes << [k.to_s, "/1/#{k}", {:id=>'1'}, v]
  94. end
  95. check_resource_routing(controller, routes, skip, nesting, resource)
  96. end
  97. # Check that the expected paths will be generated by a resource, and that
  98. # the expected params will be generated by paths defined by a resource.
  99. # routes is array of [action, url string after controller, extra params].
  100. def check_resource_routing(controller, routes, skip=[], nesting=[], resource=nil)
  101. resource ||= controller
  102. # set a prefix for nested resources
  103. prefix = nesting.join('s/1/')
  104. unless prefix.blank?
  105. prefix += "s/1/"
  106. end
  107. # Add params for nested resources.
  108. # For each 'nest', include a ":nest_id=>'1'" param.
  109. params = {}
  110. nesting.each do |param|
  111. params["#{param}_id".to_sym] = '1'
  112. end
  113. # Test each of the standard resource routes.
  114. routes.each do |pair|
  115. unless skip.include? pair[0]
  116. assert_generates("/#{prefix}#{resource}#{pair[1]}",
  117. {:controller=>controller,
  118. :action=>pair[0]}.merge(pair[2]).merge(params), {}, {},
  119. "Failed generation of resource route for action #{pair[0]} /#{prefix}#{resource}#{pair[1]}")
  120. assert_recognizes(
  121. {:controller=>controller,
  122. :action=>pair[0]}.merge(pair[2]).merge(params),
  123. {:path=>"/#{prefix}#{resource}#{pair[1]}", :method=>pair[3]},
  124. {}, "Failed to recognize resource route for path #{pair[3]}:/#{prefix}#{resource}#{pair[1]}")
  125. end
  126. end
  127. end
  128. # Check that ar has the expected validation errors and that the error list shows up in the view.
  129. def assert_validation_errors_on(ar, fields)
  130. validation_error_check_discrepancies(ar, fields)
  131. # check that the page content has the validation errors box,
  132. # and the expected number of error items in it
  133. assert_select 'div#errorExplanation' do
  134. assert_select 'li', :count=>ar.errors.length
  135. end
  136. end
  137. # Validate ar and verify that the expected fields have errors.
  138. def assert_validation_fails_for(ar, fields)
  139. assert !(ar.valid?), "passed validation when errors expected for fields #{fields.join(', ')}"
  140. validation_error_check_discrepancies(ar, fields)
  141. end
  142. # Checks for expected fields missing from the validation errors,
  143. # and unexpected fields present in the validation errors.
  144. # ar is an ActiveRecord object that has been validated and should have validation errors.
  145. # fields is an array of field (attribute) name strings that are expected to be invalid.
  146. def validation_error_check_discrepancies(ar, fields)
  147. msgs = []
  148. # get the list of fields that have errors (err_fields)
  149. err_fields = []
  150. ar.errors.each {|k,v| err_fields << k}
  151. # identify fields missing from the record’s errors
  152. missing_errors = []
  153. fields.each do |field_name|
  154. missing_errors << field_name unless err_fields.include?(field_name) #if ar.errors[field_name].blank?
  155. end
  156. if missing_errors.length > 0
  157. msgs << "missing validation error for fields #{missing_errors.join(', ')}"
  158. end
  159. # identify unexpected fields in the record’s errors
  160. unexpected_errors = []
  161. err_fields.each do |field_name|
  162. unexpected_errors << field_name unless fields.include?(field_name)
  163. end
  164. if unexpected_errors.length > 0
  165. msgs << "unexpected errors for fields #{unexpected_errors.join(', ')}"
  166. end
  167. if msgs.length > 0
  168. assert false, msgs.join(".\r")
  169. end
  170. end
  171. end