PageRenderTime 42ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/test/test_helper.rb

https://github.com/newrooky/lftwb
Ruby | 156 lines | 99 code | 19 blank | 38 comment | 10 complexity | 7aa1fb506db27bf4b0b1d95661922c1e MD5 | raw file
Possible License(s): MIT
  1. $:.reject! { |e| e.include? 'TextMate' }
  2. ENV["RAILS_ENV"] = "test"
  3. require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
  4. require 'test_help'
  5. require 'redgreen' unless ENV['TM_MODE']
  6. require 'ostruct'
  7. require 'mocha'
  8. require 'factory_girl'
  9. require File.expand_path(File.dirname(__FILE__) + '/factories')
  10. # for testing uploaded files
  11. # place any "already uploaded" files in a subdirectory within /test/ instead of overwriting production files.
  12. FileColumn::ClassMethods::DEFAULT_OPTIONS[:root_path] = File.join(RAILS_ROOT, 'test', "public", 'system')
  13. class Test::Unit::TestCase
  14. # Transactional fixtures accelerate your tests by wrapping each test method
  15. # in a transaction that's rolled back on completion. This ensures that the
  16. # test database remains unchanged so your fixtures don't have to be reloaded
  17. # between every test method. Fewer database queries means faster tests.
  18. #
  19. # Read Mike Clark's excellent walkthrough at
  20. # http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
  21. #
  22. # Every Active Record database supports transactions except MyISAM tables
  23. # in MySQL. Turn off transactional fixtures in this case; however, if you
  24. # don't care one way or the other, switching from MyISAM to InnoDB tables
  25. # is recommended.
  26. self.use_transactional_fixtures = true
  27. # Instantiated fixtures are slow, but give you @david where otherwise you
  28. # would need people(:david). If you don't want to migrate your existing
  29. # test cases which use the @david style and don't mind the speed hit (each
  30. # instantiated fixtures translates to a database query per test method),
  31. # then set this back to true.
  32. self.use_instantiated_fixtures = false
  33. fixtures :all
  34. # Add more helper methods to be used by all tests here...
  35. @@association_test_exclusions = %w{LocalizationTest RequestLoggingTest UserPhotosTest
  36. UserPhotoshootPhotosTest PurchasedPhotosTest UserPhotoRatingsTest
  37. PhotoRatingsTest UserCommentsTest PhotoCommentsTest UserPurchasedPhotosTest
  38. ProUsersControllerTest PhotoSizeTest PhotoStoriesTest
  39. GuestTest EmailTest SystemMailerTest}
  40. def _test_associations
  41. if ['SpiderTest', 'Controller', 'ActiveSupport', 'ActionMailer'].any?{|x| self.class.to_s.include?(x)} ||
  42. @@association_test_exclusions.include?(self.class.to_s)
  43. return true
  44. end
  45. check_associations(self.class.to_s.gsub('Test', '').constantize)
  46. end
  47. def check_associations(m, ignore = [])
  48. @m = m.new
  49. ig = [ignore].flatten
  50. m.reflect_on_all_associations.each do |assoc|
  51. next if ig.any?{|i| i == assoc.name}
  52. assert_nothing_raised("*************\n#{assoc.name} caused an error\n*************") do
  53. @m.send(assoc.name, true)
  54. end
  55. end
  56. true
  57. end
  58. #
  59. #
  60. # def test_roles
  61. # return unless self.class.to_s.ends_with? 'ControllerTest'
  62. # _test_actions self.class.to_s.gsub('ControllerTest', '') do |action|
  63. # puts "No test for controller: #{self.class.to_s.gsub('ControllerTest', '')}, action: #{action}"
  64. # case action
  65. # when ''
  66. # else
  67. # # _test_action 'get', action, {}, 1, 200, false
  68. # # _test_action 'get', action, {}, 3, 200, true
  69. # end
  70. # end
  71. # assert false
  72. # end
  73. def _test_action( method, action, options, user = nil, response = 200, includes_401 = false, debug = false)
  74. # puts "#{method}, #{action}, #{options.inspect}, #{user}"
  75. h = {}
  76. h = {:user=>users(user)} if user.is_a?(Symbol)
  77. h = {:user=>user} if user.is_a?(Numeric)
  78. send(method, action.to_sym, options, h)
  79. puts @response.body if debug
  80. assert_response response
  81. assert @response.body.include?('It looks like you don\'t have permission to view this page.') if includes_401
  82. assert !@response.body.include?('It looks like you don\'t have permission to view this page.') unless includes_401
  83. recycle
  84. end
  85. def _test_actions(controller, options={})
  86. return unless block_given?
  87. exclude = Set.new((options[:except] || []).to_a | ['set_vars', 'wsdl', 'rescue_action', 'render_500', 'render_404', 'filter_parameters',
  88. 'rescue_action_in_public', 'local_request?', 'allow_to', 'set_timezone', 'set_locale', 'uuid', 'tz', 'locale_from_header',
  89. 'route_name', 'resource_source=', 'find_singleton=', 'name_prefix', 'respond_to_without_url_helper?', 'resource_name=',
  90. 'resource_service_class', 'method_missing_with_url_helper', 'resources_name', 'name_prefix=', 'singleton',
  91. 'resource_url_helper_method?', 'enclosing_loaders', 'respond_to_with_url_helper?', 'singleton=', 'resource_class=', 'resource_class',
  92. 'route_name=', 'enclosing_loaders=', 'resource_service_class=', 'resource_name', 'resources_name=', 'find_singleton','resource_source',
  93. 'tzz', 'pretty_print', 'pretty_print_inspect', 'pretty_print_cycle', 'pretty_inspect', 'pretty_print_instance_variables', 'simple_price',
  94. 'is_lightbox_search?', 'current_user', 'set_cookie_domain'])
  95. exclude = exclude.map( &:to_s)
  96. controller_class = eval(Inflector.classify("#{controller}_controller"))
  97. controller_class.send(:action_methods).each do |method|
  98. next if exclude.include? method
  99. yield method
  100. end
  101. end
  102. def assert_models_equal(expected_models, actual_models, message = nil)
  103. to_test_param = lambda { |r| "<#{r.class}:#{r.to_param}>" }
  104. full_message = build_message(message, "<?> expected but was\n<?>.\n",
  105. expected_models.collect(&to_test_param), actual_models.collect(&to_test_param))
  106. assert_block(full_message) { expected_models == actual_models }
  107. end
  108. def ensure_flash(val)
  109. assert_contains flash.values, val, ", Flash: #{flash.inspect}"
  110. end
  111. def ensure_home_page
  112. # make sure there is a default 'home' page in the system
  113. @site = Site.first
  114. @user = Factory(:user)
  115. @content_page = @site.pages.create(:url_key => 'home', :title => 'the home page',
  116. :body_raw => 'the page body', :creator => @user)
  117. end
  118. # Teardown and setup - for quick recycling of env. within a single test
  119. def recycle; teardown; setup; end
  120. NOT_LOGGED_IN_MSG = /You must be logged in to access this feature/i
  121. PERMISSION_DENIED_MSG = /You don't have permission to do that/i
  122. end
  123. # turn off solr for tests
  124. class ActsAsSolr::Post
  125. def self.execute(request)
  126. true
  127. end
  128. end
  129. include AuthenticatedTestHelper
  130. # Add more helper methods to be used by all tests here...
  131. def login_using_basic_auth
  132. @request.env['HTTP_AUTHENTICATION'] = ActionController::HttpAuthentication::Basic.encode_credntials("", "")
  133. end