diff options
298 files changed, 1294 insertions, 1580 deletions
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 220cee3da1..3afdbea42a 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -22,16 +22,16 @@ module ActionMailer #:nodoc: # # Examples: # - # class Notifier < ActionMailer::Base - # default :from => 'no-reply@example.com', + # class Notifier < ActionMailer::Base + # default :from => 'no-reply@example.com', # :return_path => 'system@example.com' # - # def welcome(recipient) - # @account = recipient - # mail(:to => recipient.email_address_with_name, - # :bcc => ["bcc@example.com", "Order Watcher <watcher@example.com>"]) - # end - # end + # def welcome(recipient) + # @account = recipient + # mail(:to => recipient.email_address_with_name, + # :bcc => ["bcc@example.com", "Order Watcher <watcher@example.com>"]) + # end + # end # # Within the mailer method, you have access to the following methods: # @@ -366,7 +366,7 @@ module ActionMailer #:nodoc: end # Register an Inteceptor which will be called before mail is sent. - # Either a class or a string can be passed in as the Observer. If a string is passed in + # Either a class or a string can be passed in as the Interceptor. If a string is passed in # it will be <tt>constantize</tt>d. def register_interceptor(interceptor) delivery_interceptor = (interceptor.is_a?(String) ? interceptor.constantize : interceptor) diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 48b3e5bfff..479e8246c5 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,3 +1,24 @@ +*Rails 3.2.0 (unreleased)* + +* Refactor ActionController::TestCase cookies [Andrew White] + + Assigning cookies for test cases should now use cookies[], e.g: + + cookies[:email] = 'user@example.com' + get :index + assert_equal 'user@example.com', cookies[:email] + + To clear the cookies, use clear, e.g: + + cookies.clear + get :index + assert_nil cookies[:email] + + We now no longer write out HTTP_COOKIE and the cookie jar is + persistent between requests so if you need to manipulate the environment + for your test you need to do it before the cookie jar is created. + + *Rails 3.1.0 (unreleased)* * Added 'ActionView::Helpers::FormHelper.fields_for_with_index', similar to fields_for but allows to have access to the current iteration index [Jorge Bejar] diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec index d7c8aeadd3..37a3d960f1 100644 --- a/actionpack/actionpack.gemspec +++ b/actionpack/actionpack.gemspec @@ -24,7 +24,7 @@ Gem::Specification.new do |s| s.add_dependency('rack', '~> 1.3.0') s.add_dependency('rack-test', '~> 0.6.0') s.add_dependency('rack-mount', '~> 0.8.1') - s.add_dependency('sprockets', '~> 2.0.0.beta.8') + s.add_dependency('sprockets', '~> 2.0.0.beta.10') s.add_dependency('tzinfo', '~> 0.3.27') s.add_dependency('erubis', '~> 2.7.0') end diff --git a/actionpack/lib/action_controller/metal/instrumentation.rb b/actionpack/lib/action_controller/metal/instrumentation.rb index 16cbbce2fb..85d0f5f699 100644 --- a/actionpack/lib/action_controller/metal/instrumentation.rb +++ b/actionpack/lib/action_controller/metal/instrumentation.rb @@ -19,7 +19,7 @@ module ActionController :controller => self.class.name, :action => self.action_name, :params => request.filtered_parameters, - :format => request.format.ref, + :format => request.format.try(:ref), :method => request.method, :path => (request.fullpath rescue "unknown") } diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 2ca9bae073..d14bb666cc 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -175,10 +175,6 @@ module ActionController end def recycle! - write_cookies! - @env.delete('HTTP_COOKIE') if @cookies.blank? - @env.delete('action_dispatch.cookies') - @cookies = nil @formats = nil @env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ } @env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ } @@ -186,6 +182,14 @@ module ActionController @method = @request_method = nil @fullpath = @ip = @remote_ip = nil @env['action_dispatch.request.query_parameters'] = {} + @set_cookies ||= {} + @set_cookies.update(Hash[cookie_jar.instance_variable_get("@set_cookies").map{ |k,o| [k,o[:value]] }]) + deleted_cookies = cookie_jar.instance_variable_get("@delete_cookies") + @set_cookies.reject!{ |k,v| deleted_cookies.include?(k) } + cookie_jar.update(rack_cookies) + cookie_jar.update(cookies) + cookie_jar.update(@set_cookies) + cookie_jar.recycle! end end @@ -301,18 +305,17 @@ module ActionController # 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. # - # == Manipulating the request collections + # == Manipulating session and cookie variables # - # 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: + # Sometimes you need to set up the session and cookie variables for a test. + # To do this just assign a value to the session or cookie collection: # - # @request.session[:key] = "value" - # @request.cookies[:key] = "value" + # session[:key] = "value" + # cookies[:key] = "value" # - # To clear the cookies for a test just clear the request's cookies hash: + # To clear the cookies for a test just clear the cookie collection: # - # @request.cookies.clear + # cookies.clear # # == \Testing named routes # @@ -395,7 +398,26 @@ module ActionController end alias xhr :xml_http_request + def paramify_values(hash_or_array_or_value) + case hash_or_array_or_value + when Hash + hash_or_array_or_value.each do |key, value| + hash_or_array_or_value[key] = paramify_values(value) + end + when Array + hash_or_array_or_value.map {|i| paramify_values(i)} + when Rack::Test::UploadedFile + hash_or_array_or_value + else + hash_or_array_or_value.to_param + end + end + def process(action, parameters = nil, session = nil, flash = nil, http_method = 'GET') + # Ensure that numbers and symbols passed as params are converted to + # proper params, as is the case when engaging rack. + paramify_values(parameters) + # Sanity check for required instance variables so we can give an # understandable error message. %w(@routes @controller @request @response).each do |iv_name| @@ -431,7 +453,6 @@ module ActionController @controller.process_with_new_base_test(@request, @response) @assigns = @controller.respond_to?(:view_assigns) ? @controller.view_assigns : {} @request.session.delete('flash') if @request.session['flash'].blank? - @request.cookies.merge!(@response.cookies) @response end diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index 47c4bad489..8cee9ecdc4 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -1,4 +1,5 @@ -require "active_support/core_ext/object/blank" +require 'active_support/core_ext/object/blank' +require 'active_support/core_ext/hash/keys' module ActionDispatch class Request @@ -129,7 +130,7 @@ module ActionDispatch end def update(other_hash) - @cookies.update other_hash + @cookies.update other_hash.stringify_keys self end @@ -185,6 +186,11 @@ module ActionDispatch value end + # Removes all cookies on the client machine by calling <tt>delete</tt> for each cookie + def clear(options = {}) + @cookies.each_key{ |k| delete(k, options) } + end + # Returns a jar that'll automatically set the assigned cookies to have an expiration date 20 years from now. Example: # # cookies.permanent[:prefers_open_id] = true @@ -222,6 +228,11 @@ module ActionDispatch @delete_cookies.each { |k, v| ::Rack::Utils.delete_cookie_header!(headers, k, v) } end + def recycle! #:nodoc: + @set_cookies.clear + @delete_cookies.clear + end + private def write_cookie?(cookie) diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 3999bd0a5e..ec76d1da1e 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -1423,7 +1423,9 @@ module ActionDispatch end def action_path(name, path = nil) #:nodoc: - path || @scope[:path_names][name.to_sym] || name.to_s + # Ruby 1.8 can't transform empty strings to symbols + name = name.to_sym if name.is_a?(String) && !name.empty? + path || @scope[:path_names][name] || name.to_s end def prefix_name_for_action(as, action) #:nodoc: diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb index 606b01893e..a2d639cd56 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/response.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb @@ -60,11 +60,11 @@ module ActionDispatch assert_response(:redirect, message) return true if options == @response.location - redirected_to_after_normalisation = normalize_argument_to_redirection(@response.location) - options_after_normalisation = normalize_argument_to_redirection(options) + redirected_to_after_normalization = normalize_argument_to_redirection(@response.location) + options_after_normalization = normalize_argument_to_redirection(options) - if redirected_to_after_normalisation != options_after_normalisation - flunk "Expected response to be a redirect to <#{options_after_normalisation}> but was a redirect to <#{redirected_to_after_normalisation}>" + if redirected_to_after_normalization != options_after_normalization + flunk "Expected response to be a redirect to <#{options_after_normalization}> but was a redirect to <#{redirected_to_after_normalization}>" end end diff --git a/actionpack/lib/action_dispatch/testing/test_process.rb b/actionpack/lib/action_dispatch/testing/test_process.rb index 397bda41d5..367c295cf5 100644 --- a/actionpack/lib/action_dispatch/testing/test_process.rb +++ b/actionpack/lib/action_dispatch/testing/test_process.rb @@ -1,3 +1,4 @@ +require 'action_dispatch/middleware/cookies' require 'action_dispatch/middleware/flash' require 'active_support/core_ext/hash/indifferent_access' @@ -22,7 +23,7 @@ module ActionDispatch end def cookies - @request.cookies.merge(@response.cookies).with_indifferent_access + @request.cookie_jar end def redirect_to_url diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb index 822adb6a47..7280e9a93b 100644 --- a/actionpack/lib/action_dispatch/testing/test_request.rb +++ b/actionpack/lib/action_dispatch/testing/test_request.rb @@ -1,4 +1,5 @@ require 'active_support/core_ext/object/blank' +require 'active_support/core_ext/hash/indifferent_access' require 'active_support/core_ext/hash/reverse_merge' require 'rack/utils' @@ -14,18 +15,11 @@ module ActionDispatch env = Rails.application.env_config.merge(env) if defined?(Rails.application) super(DEFAULT_ENV.merge(env)) - @cookies = nil self.host = 'test.host' self.remote_addr = '0.0.0.0' self.user_agent = 'Rails Testing' end - def env - write_cookies! - delete_nil_values! - super - end - def request_method=(method) @env['REQUEST_METHOD'] = method.to_s.upcase end @@ -71,23 +65,10 @@ module ActionDispatch @env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_type| mime_type.to_s }.join(",") end + alias :rack_cookies :cookies + def cookies - @cookies ||= super + @cookies ||= {}.with_indifferent_access end - - private - def write_cookies! - unless @cookies.blank? - @env['HTTP_COOKIE'] = @cookies.map { |name, value| escape_cookie(name, value) }.join('; ') - end - end - - def escape_cookie(name, value) - "#{Rack::Utils.escape(name)}=#{Rack::Utils.escape(value)}" - end - - def delete_nil_values! - @env.delete_if { |k, v| v.nil? } - end end end diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb index a67b61c1ef..78eddb7530 100644 --- a/actionpack/lib/action_view.rb +++ b/actionpack/lib/action_view.rb @@ -71,11 +71,6 @@ module ActionView autoload :TemplateError autoload :WrongEncodingError end - - autoload_at "action_view/template" do - autoload :TemplateHandler - autoload :TemplateHandlers - end end ENCODING_FLAG = '#.*coding[:=]\s*(\S+)[ \t]*' diff --git a/actionpack/lib/action_view/helpers/asset_paths.rb b/actionpack/lib/action_view/helpers/asset_paths.rb index 1bc5c9e003..9a99c3cf52 100644 --- a/actionpack/lib/action_view/helpers/asset_paths.rb +++ b/actionpack/lib/action_view/helpers/asset_paths.rb @@ -44,7 +44,12 @@ module ActionView raise NotImplementedError end + def rewrite_relative_url_root(source, relative_url_root) + relative_url_root && !source.starts_with?("#{relative_url_root}/") ? "#{relative_url_root}#{source}" : source + end + def rewrite_host_and_protocol(source, has_request) + source = rewrite_relative_url_root(source, controller.config.relative_url_root) if has_request host = compute_asset_host(source) if has_request && host && !is_uri?(host) host = "#{controller.request.protocol}#{host}" @@ -75,4 +80,4 @@ module ActionView end end -end
\ No newline at end of file +end diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb index cd0f8c8878..2d49823412 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb @@ -85,17 +85,8 @@ module ActionView end end end - - def rewrite_relative_url_root(source, relative_url_root) - relative_url_root && !source.starts_with?("#{relative_url_root}/") ? "#{relative_url_root}#{source}" : source - end - - def rewrite_host_and_protocol(source, has_request) - source = rewrite_relative_url_root(source, controller.config.relative_url_root) if has_request - super(source, has_request) - end end end end -end
\ No newline at end of file +end diff --git a/actionpack/lib/action_view/helpers/controller_helper.rb b/actionpack/lib/action_view/helpers/controller_helper.rb index e22331cb3c..db59bca159 100644 --- a/actionpack/lib/action_view/helpers/controller_helper.rb +++ b/actionpack/lib/action_view/helpers/controller_helper.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/module/attr_internal' + module ActionView module Helpers # This module keeps all methods and behavior in ActionView diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb index b99d24d281..10797c010f 100644 --- a/actionpack/lib/action_view/template.rb +++ b/actionpack/lib/action_view/template.rb @@ -91,7 +91,6 @@ module ActionView eager_autoload do autoload :Error - autoload :Handler autoload :Handlers autoload :Text end diff --git a/actionpack/lib/sprockets/helpers/rails_helper.rb b/actionpack/lib/sprockets/helpers/rails_helper.rb index a99dcad81d..dcf4b9279e 100644 --- a/actionpack/lib/sprockets/helpers/rails_helper.rb +++ b/actionpack/lib/sprockets/helpers/rails_helper.rb @@ -15,42 +15,48 @@ module Sprockets end end - def javascript_include_tag(source, options = {}) + def javascript_include_tag(*sources) + options = sources.extract_options! debug = options.key?(:debug) ? options.delete(:debug) : debug_assets? body = options.key?(:body) ? options.delete(:body) : false - if debug && asset = asset_paths.asset_for(source, 'js') - asset.to_a.map { |dep| - javascript_include_tag(dep, :debug => false, :body => true) - }.join("\n").html_safe - else - options = { - 'type' => "text/javascript", - 'src' => asset_path(source, 'js', body) - }.merge(options.stringify_keys) - - content_tag 'script', "", options - end + sources.collect do |source| + if debug && asset = asset_paths.asset_for(source, 'js') + asset.to_a.map { |dep| + javascript_include_tag(dep, :debug => false, :body => true) + }.join("\n").html_safe + else + tag_options = { + 'type' => "text/javascript", + 'src' => asset_path(source, 'js', body) + }.merge(options.stringify_keys) + + content_tag 'script', "", tag_options + end + end.join("\n").html_safe end - def stylesheet_link_tag(source, options = {}) + def stylesheet_link_tag(*sources) + options = sources.extract_options! debug = options.key?(:debug) ? options.delete(:debug) : debug_assets? body = options.key?(:body) ? options.delete(:body) : false - if debug && asset = asset_paths.asset_for(source, 'css') - asset.to_a.map { |dep| - stylesheet_link_tag(dep, :debug => false, :body => true) - }.join("\n").html_safe - else - options = { - 'rel' => "stylesheet", - 'type' => "text/css", - 'media' => "screen", - 'href' => asset_path(source, 'css', body) - }.merge(options.stringify_keys) - - tag 'link', options - end + sources.collect do |source| + if debug && asset = asset_paths.asset_for(source, 'css') + asset.to_a.map { |dep| + stylesheet_link_tag(dep, :debug => false, :body => true) + }.join("\n").html_safe + else + tag_options = { + 'rel' => "stylesheet", + 'type' => "text/css", + 'media' => "screen", + 'href' => asset_path(source, 'css', body) + }.merge(options.stringify_keys) + + tag 'link', tag_options + end + end.join("\n").html_safe end private diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index 01dc2f2091..23709e44e2 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -492,6 +492,8 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest end routes.draw do + match '', :to => 'application_integration_test/test#index', :as => :empty_string + match 'foo', :to => 'application_integration_test/test#index', :as => :foo match 'bar', :to => 'application_integration_test/test#index', :as => :bar end @@ -501,11 +503,15 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest end test "includes route helpers" do + assert_equal '/', empty_string_path assert_equal '/foo', foo_path assert_equal '/bar', bar_path end test "route helpers after controller access" do + get '/' + assert_equal '/', empty_string_path + get '/foo' assert_equal '/foo', foo_path diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index 4a5e597500..26270571cf 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -498,6 +498,12 @@ class RespondToControllerTest < ActionController::TestCase assert_equal '<html><div id="iphone">Hello iPhone future from iPhone!</div></html>', @response.body assert_equal "text/html", @response.content_type end + + def test_invalid_format + get :using_defaults, :format => "invalidformat" + assert_equal " ", @response.body + assert_equal "text/html", @response.content_type + end end class RespondWithController < ActionController::Base diff --git a/actionpack/test/controller/new_base/base_test.rb b/actionpack/test/controller/new_base/base_test.rb index 8fa5d20372..ed244513a5 100644 --- a/actionpack/test/controller/new_base/base_test.rb +++ b/actionpack/test/controller/new_base/base_test.rb @@ -40,7 +40,7 @@ module Dispatching class ContainedEmptyController < ActionController::Base ; end class ContainedSubEmptyController < ContainedEmptyController ; end class ContainedNonDefaultPathController < ActionController::Base - def self.controller_path; "i_am_extremly_not_default"; end + def self.controller_path; "i_am_extremely_not_default"; end end end @@ -89,7 +89,7 @@ module Dispatching end test "namespaced non-default controller path" do - assert_equal 'i_am_extremly_not_default', Submodule::ContainedNonDefaultPathController.controller_path + assert_equal 'i_am_extremely_not_default', Submodule::ContainedNonDefaultPathController.controller_path assert_equal Submodule::ContainedNonDefaultPathController.controller_path, Submodule::ContainedNonDefaultPathController.new.controller_path end diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb index 5896222a0a..f48b73b63a 100644 --- a/actionpack/test/controller/test_test.rb +++ b/actionpack/test/controller/test_test.rb @@ -493,6 +493,16 @@ XML ) end + def test_params_passing_with_fixnums + get :test_params, :page => {:name => "Page name", :month => 4, :year => 2004, :day => 6} + parsed_params = eval(@response.body) + assert_equal( + {'controller' => 'test_test/test', 'action' => 'test_params', + 'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}}, + parsed_params + ) + end + def test_params_passing_with_frozen_values assert_nothing_raised do get :test_params, :frozen => 'icy'.freeze, :frozens => ['icy'.freeze].freeze @@ -583,13 +593,13 @@ XML end def test_should_have_knowledge_of_client_side_cookie_state_even_if_they_are_not_set - @request.cookies['foo'] = 'bar' + cookies['foo'] = 'bar' get :no_op assert_equal 'bar', cookies['foo'] end def test_should_detect_if_cookie_is_deleted - @request.cookies['foo'] = 'bar' + cookies['foo'] = 'bar' get :delete_cookie assert_nil cookies['foo'] end diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb index e42c39f527..8e5fd97cc6 100644 --- a/actionpack/test/dispatch/cookies_test.rb +++ b/actionpack/test/dispatch/cookies_test.rb @@ -417,7 +417,7 @@ class CookiesTest < ActionController::TestCase assert_cookie_header "user_name=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" end - + def test_cookies_hash_is_indifferent_access get :symbol_key assert_equal "david", cookies[:user_name] @@ -430,54 +430,95 @@ class CookiesTest < ActionController::TestCase def test_setting_request_cookies_is_indifferent_access - @request.cookies.clear - @request.cookies[:user_name] = "andrew" + cookies.clear + cookies[:user_name] = "andrew" get :string_key_mock - assert_equal "david", cookies[:user_name] + assert_equal "david", cookies['user_name'] - @request.cookies.clear - @request.cookies['user_name'] = "andrew" + cookies.clear + cookies['user_name'] = "andrew" get :symbol_key_mock - assert_equal "david", cookies['user_name'] + assert_equal "david", cookies[:user_name] end def test_cookies_retained_across_requests get :symbol_key - assert_equal "user_name=david; path=/", @response.headers["Set-Cookie"] + assert_cookie_header "user_name=david; path=/" assert_equal "david", cookies[:user_name] get :noop assert_nil @response.headers["Set-Cookie"] - assert_equal "user_name=david", @request.env['HTTP_COOKIE'] assert_equal "david", cookies[:user_name] get :noop assert_nil @response.headers["Set-Cookie"] - assert_equal "user_name=david", @request.env['HTTP_COOKIE'] assert_equal "david", cookies[:user_name] end def test_cookies_can_be_cleared get :symbol_key - assert_equal "user_name=david; path=/", @response.headers["Set-Cookie"] assert_equal "david", cookies[:user_name] - @request.cookies.clear + cookies.clear get :noop - assert_nil @response.headers["Set-Cookie"] - assert_nil @request.env['HTTP_COOKIE'] assert_nil cookies[:user_name] get :symbol_key - assert_equal "user_name=david; path=/", @response.headers["Set-Cookie"] assert_equal "david", cookies[:user_name] end - def test_cookies_are_escaped - @request.cookies[:user_ids] = '1;2' + def test_can_set_http_cookie_header + @request.env['HTTP_COOKIE'] = 'user_name=david' + get :noop + assert_equal 'david', cookies['user_name'] + assert_equal 'david', cookies[:user_name] + + get :noop + assert_equal 'david', cookies['user_name'] + assert_equal 'david', cookies[:user_name] + + @request.env['HTTP_COOKIE'] = 'user_name=andrew' + get :noop + assert_equal 'andrew', cookies['user_name'] + assert_equal 'andrew', cookies[:user_name] + end + + def test_can_set_request_cookies + @request.cookies['user_name'] = 'david' + get :noop + assert_equal 'david', cookies['user_name'] + assert_equal 'david', cookies[:user_name] + + get :noop + assert_equal 'david', cookies['user_name'] + assert_equal 'david', cookies[:user_name] + + @request.cookies[:user_name] = 'andrew' + get :noop + assert_equal 'andrew', cookies['user_name'] + assert_equal 'andrew', cookies[:user_name] + end + + def test_cookies_precedence_over_http_cookie + @request.env['HTTP_COOKIE'] = 'user_name=andrew' + get :authenticate + assert_equal 'david', cookies['user_name'] + assert_equal 'david', cookies[:user_name] + + get :noop + assert_equal 'david', cookies['user_name'] + assert_equal 'david', cookies[:user_name] + end + + def test_cookies_precedence_over_request_cookies + @request.cookies['user_name'] = 'andrew' + get :authenticate + assert_equal 'david', cookies['user_name'] + assert_equal 'david', cookies[:user_name] + get :noop - assert_equal "user_ids=1%3B2", @request.env['HTTP_COOKIE'] - assert_equal "1;2", cookies[:user_ids] + assert_equal 'david', cookies['user_name'] + assert_equal 'david', cookies[:user_name] end private diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb index 81a8c24525..aa115608ef 100644 --- a/actionpack/test/dispatch/test_request_test.rb +++ b/actionpack/test/dispatch/test_request_test.rb @@ -34,12 +34,24 @@ class TestRequestTest < ActiveSupport::TestCase assert_equal({}, req.cookies) assert_equal nil, req.env["HTTP_COOKIE"] - req.cookies["user_name"] = "david" - assert_equal({"user_name" => "david"}, req.cookies) - assert_equal "user_name=david", req.env["HTTP_COOKIE"] + req.cookie_jar["user_name"] = "david" + assert_cookies({"user_name" => "david"}, req.cookie_jar) - req.cookies["login"] = "XJ-122" - assert_equal({"user_name" => "david", "login" => "XJ-122"}, req.cookies) - assert_equal %w(login=XJ-122 user_name=david), req.env["HTTP_COOKIE"].split(/; /).sort + req.cookie_jar["login"] = "XJ-122" + assert_cookies({"user_name" => "david", "login" => "XJ-122"}, req.cookie_jar) + + req.cookie_jar.delete(:login) + assert_cookies({"user_name" => "david"}, req.cookie_jar) + + req.cookie_jar.clear + assert_cookies({}, req.cookie_jar) + + req.cookie_jar.update(:user_name => "david") + assert_cookies({"user_name" => "david"}, req.cookie_jar) end + + private + def assert_cookies(expected, cookie_jar) + assert_equal(expected, cookie_jar.instance_variable_get("@cookies")) + end end diff --git a/actionpack/test/fixtures/sprockets/app/javascripts/extra.js b/actionpack/test/fixtures/sprockets/app/javascripts/extra.js new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/actionpack/test/fixtures/sprockets/app/javascripts/extra.js diff --git a/actionpack/test/fixtures/sprockets/app/stylesheets/extra.css b/actionpack/test/fixtures/sprockets/app/stylesheets/extra.css new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/actionpack/test/fixtures/sprockets/app/stylesheets/extra.css diff --git a/actionpack/test/template/sprockets_helper_test.rb b/actionpack/test/template/sprockets_helper_test.rb index b26315083c..b1317d0a35 100644 --- a/actionpack/test/template/sprockets_helper_test.rb +++ b/actionpack/test/template/sprockets_helper_test.rb @@ -57,6 +57,12 @@ class SprocketsHelperTest < ActionView::TestCase asset_path("http://www.example.com/video/play.mp4") end + test "asset path with relative url root" do + @controller.config.relative_url_root = "/collaboration/hieraki" + assert_equal "/collaboration/hieraki/images/logo.gif", + asset_path("/images/logo.gif") + end + test "javascript path" do assert_equal "/assets/application-d41d8cd98f00b204e9800998ecf8427e.js", asset_path(:application, "js") @@ -88,6 +94,9 @@ class SprocketsHelperTest < ActionView::TestCase assert_equal "<script src=\"/assets/xmlhr-d41d8cd98f00b204e9800998ecf8427e.js?body=1\" type=\"text/javascript\"></script>\n<script src=\"/assets/application-d41d8cd98f00b204e9800998ecf8427e.js?body=1\" type=\"text/javascript\"></script>", javascript_include_tag(:application, :debug => true) + + assert_equal "<script src=\"/assets/xmlhr-d41d8cd98f00b204e9800998ecf8427e.js\" type=\"text/javascript\"></script>\n<script src=\"/assets/extra-d41d8cd98f00b204e9800998ecf8427e.js\" type=\"text/javascript\"></script>", + javascript_include_tag("xmlhr", "extra") end test "stylesheet path" do @@ -121,5 +130,8 @@ class SprocketsHelperTest < ActionView::TestCase assert_equal "<link href=\"/assets/style-d41d8cd98f00b204e9800998ecf8427e.css?body=1\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\" />\n<link href=\"/assets/application-68b329da9893e34099c7d8ad5cb9c940.css?body=1\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\" />", stylesheet_link_tag(:application, :debug => true) + + assert_equal "<link href=\"/assets/style-d41d8cd98f00b204e9800998ecf8427e.css\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\" />\n<link href=\"/assets/extra-d41d8cd98f00b204e9800998ecf8427e.css\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\" />", + stylesheet_link_tag("style", "extra") end end diff --git a/activemodel/CHANGELOG b/activemodel/CHANGELOG index be4de2e53c..b1ad315c46 100644 --- a/activemodel/CHANGELOG +++ b/activemodel/CHANGELOG @@ -1,3 +1,5 @@ +* Provide mass_assignment_sanitizer as an easy API to replace the sanitizer behavior. Also support both :logger (default) and :strict sanitizer behavior [Bogdan Gusiev] + *Rails 3.1.0 (unreleased)* * attr_accessible and friends now accepts :as as option to specify a role [Josh Kalderimis] diff --git a/activemodel/lib/active_model/mass_assignment_security.rb b/activemodel/lib/active_model/mass_assignment_security.rb index 483b577681..a7b4706906 100644 --- a/activemodel/lib/active_model/mass_assignment_security.rb +++ b/activemodel/lib/active_model/mass_assignment_security.rb @@ -1,5 +1,7 @@ -require 'active_support/core_ext/class/attribute.rb' +require 'active_support/core_ext/class/attribute' +require 'active_support/core_ext/string/inflections' require 'active_model/mass_assignment_security/permission_set' +require 'active_model/mass_assignment_security/sanitizer' module ActiveModel # = Active Model Mass-Assignment Security @@ -10,6 +12,9 @@ module ActiveModel class_attribute :_accessible_attributes class_attribute :_protected_attributes class_attribute :_active_authorizer + + class_attribute :_mass_assignment_sanitizer + self.mass_assignment_sanitizer = :logger end # Mass assignment security provides an interface for protecting attributes @@ -41,6 +46,16 @@ module ActiveModel # # end # + # = Configuration options + # + # * <tt>mass_assignment_sanitizer</tt> - Defines sanitize method. Possible values are: + # * <tt>:logger</tt> (default) - writes filtered attributes to logger + # * <tt>:strict</tt> - raise <tt>ActiveModel::MassAssignmentSecurity::Error</tt> on any protected attribute update + # + # You can specify your own sanitizer object eg. MySanitizer.new. + # See <tt>ActiveModel::MassAssignmentSecurity::LoggerSanitizer</tt> for example implementation. + # + # module ClassMethods # Attributes named in this macro are protected from mass-assignment # whenever attributes are sanitized before assignment. A role for the @@ -154,7 +169,7 @@ module ActiveModel options = args.extract_options! role = options[:as] || :default - self._accessible_attributes = accessible_attributes_configs.dup + self._accessible_attributes = accessible_attributes_configs.dup self._accessible_attributes[role] = self.accessible_attributes(role) + args self._active_authorizer = self._accessible_attributes @@ -177,21 +192,25 @@ module ActiveModel [] end + def mass_assignment_sanitizer=(value) + self._mass_assignment_sanitizer = if value.is_a?(Symbol) + const_get(:"#{value.to_s.camelize}Sanitizer").new(self) + else + value + end + end + private def protected_attributes_configs self._protected_attributes ||= begin - default_black_list = BlackList.new(attributes_protected_by_default).tap do |w| - w.logger = self.logger if self.respond_to?(:logger) - end - Hash.new(default_black_list) + Hash.new { |h,k| h[k] = BlackList.new(attributes_protected_by_default) } end end def accessible_attributes_configs self._accessible_attributes ||= begin - default_white_list = WhiteList.new.tap { |w| w.logger = self.logger if self.respond_to?(:logger) } - Hash.new(default_white_list) + Hash.new { |h,k| h[k] = WhiteList.new } end end end @@ -199,7 +218,7 @@ module ActiveModel protected def sanitize_for_mass_assignment(attributes, role = :default) - mass_assignment_authorizer(role).sanitize(attributes) + _mass_assignment_sanitizer.sanitize(attributes, mass_assignment_authorizer(role)) end def mass_assignment_authorizer(role = :default) diff --git a/activemodel/lib/active_model/mass_assignment_security/permission_set.rb b/activemodel/lib/active_model/mass_assignment_security/permission_set.rb index 9fcb94d48a..a1fcdf1a38 100644 --- a/activemodel/lib/active_model/mass_assignment_security/permission_set.rb +++ b/activemodel/lib/active_model/mass_assignment_security/permission_set.rb @@ -1,10 +1,8 @@ require 'set' -require 'active_model/mass_assignment_security/sanitizer' module ActiveModel module MassAssignmentSecurity class PermissionSet < Set - attr_accessor :logger def +(values) super(values.map(&:to_s)) @@ -14,6 +12,10 @@ module ActiveModel super(remove_multiparameter_id(key)) end + def deny?(key) + raise NotImplementedError, "#deny?(key) suppose to be overwritten" + end + protected def remove_multiparameter_id(key) @@ -22,7 +24,6 @@ module ActiveModel end class WhiteList < PermissionSet - include Sanitizer def deny?(key) !include?(key) @@ -30,7 +31,6 @@ module ActiveModel end class BlackList < PermissionSet - include Sanitizer def deny?(key) include?(key) diff --git a/activemodel/lib/active_model/mass_assignment_security/sanitizer.rb b/activemodel/lib/active_model/mass_assignment_security/sanitizer.rb index 150beb1ff2..ee43a6694f 100644 --- a/activemodel/lib/active_model/mass_assignment_security/sanitizer.rb +++ b/activemodel/lib/active_model/mass_assignment_security/sanitizer.rb @@ -1,9 +1,14 @@ +require 'active_support/core_ext/module/delegation' + module ActiveModel module MassAssignmentSecurity - module Sanitizer + class Sanitizer + def initialize(target=nil) + end + # Returns all attributes not denied by the authorizer. - def sanitize(attributes) - sanitized_attributes = attributes.reject { |key, value| deny?(key) } + def sanitize(attributes, authorizer) + sanitized_attributes = attributes.reject { |key, value| authorizer.deny?(key) } debug_protected_attribute_removal(attributes, sanitized_attributes) sanitized_attributes end @@ -12,12 +17,38 @@ module ActiveModel def debug_protected_attribute_removal(attributes, sanitized_attributes) removed_keys = attributes.keys - sanitized_attributes.keys - warn!(removed_keys) if removed_keys.any? + process_removed_attributes(removed_keys) if removed_keys.any? + end + + def process_removed_attributes(attrs) + raise NotImplementedError, "#process_removed_attributes(attrs) suppose to be overwritten" + end + end + + class LoggerSanitizer < Sanitizer + delegate :logger, :to => :@target + + def initialize(target) + @target = target + super end - def warn!(attrs) - self.logger.debug "WARNING: Can't mass-assign protected attributes: #{attrs.join(', ')}" if self.logger + def logger? + @target.respond_to?(:logger) && @target.logger end + + def process_removed_attributes(attrs) + logger.debug "WARNING: Can't mass-assign protected attributes: #{attrs.join(', ')}" if logger? + end + end + + class StrictSanitizer < Sanitizer + def process_removed_attributes(attrs) + raise ActiveModel::MassAssignmentSecurity::Error, "Can't mass-assign protected attributes: #{attrs.join(', ')}" + end + end + + class Error < StandardError end end end diff --git a/activemodel/lib/active_model/validations/exclusion.rb b/activemodel/lib/active_model/validations/exclusion.rb index ab4de3c459..d3b8d31502 100644 --- a/activemodel/lib/active_model/validations/exclusion.rb +++ b/activemodel/lib/active_model/validations/exclusion.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/range.rb' +require 'active_support/core_ext/range' module ActiveModel diff --git a/activemodel/lib/active_model/validations/inclusion.rb b/activemodel/lib/active_model/validations/inclusion.rb index bfb65d2f3f..9a9270d615 100644 --- a/activemodel/lib/active_model/validations/inclusion.rb +++ b/activemodel/lib/active_model/validations/inclusion.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/range.rb' +require 'active_support/core_ext/range' module ActiveModel diff --git a/activemodel/test/cases/mass_assignment_security/black_list_test.rb b/activemodel/test/cases/mass_assignment_security/black_list_test.rb index ed168bc016..0ec7f8719c 100644 --- a/activemodel/test/cases/mass_assignment_security/black_list_test.rb +++ b/activemodel/test/cases/mass_assignment_security/black_list_test.rb @@ -16,13 +16,5 @@ class BlackListTest < ActiveModel::TestCase assert_equal false, @black_list.deny?('first_name') end - test "sanitize attributes" do - original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied', 'admin(1)' => 'denied' } - attributes = @black_list.sanitize(original_attributes) - - assert attributes.key?('first_name'), "Allowed key shouldn't be rejected" - assert !attributes.key?('admin'), "Denied key should be rejected" - assert !attributes.key?('admin(1)'), "Multi-parameter key should be detected" - end end diff --git a/activemodel/test/cases/mass_assignment_security/sanitizer_test.rb b/activemodel/test/cases/mass_assignment_security/sanitizer_test.rb index 9a73a5ad91..62a6ec9c9b 100644 --- a/activemodel/test/cases/mass_assignment_security/sanitizer_test.rb +++ b/activemodel/test/cases/mass_assignment_security/sanitizer_test.rb @@ -3,36 +3,41 @@ require 'logger' require 'active_support/core_ext/object/inclusion' class SanitizerTest < ActiveModel::TestCase + attr_accessor :logger - class SanitizingAuthorizer - include ActiveModel::MassAssignmentSecurity::Sanitizer - - attr_accessor :logger - + class Authorizer < ActiveModel::MassAssignmentSecurity::PermissionSet def deny?(key) key.in?(['admin']) end - end def setup - @sanitizer = SanitizingAuthorizer.new + @logger_sanitizer = ActiveModel::MassAssignmentSecurity::LoggerSanitizer.new(self) + @strict_sanitizer = ActiveModel::MassAssignmentSecurity::StrictSanitizer.new(self) + @authorizer = Authorizer.new end test "sanitize attributes" do original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied' } - attributes = @sanitizer.sanitize(original_attributes) + attributes = @logger_sanitizer.sanitize(original_attributes, @authorizer) assert attributes.key?('first_name'), "Allowed key shouldn't be rejected" assert !attributes.key?('admin'), "Denied key should be rejected" end - test "debug mass assignment removal" do + test "debug mass assignment removal with LoggerSanitizer" do original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied' } log = StringIO.new - @sanitizer.logger = Logger.new(log) - @sanitizer.sanitize(original_attributes) + self.logger = Logger.new(log) + @logger_sanitizer.sanitize(original_attributes, @authorizer) assert_match(/admin/, log.string, "Should log removed attributes: #{log.string}") end + test "debug mass assignment removal with StrictSanitizer" do + original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied' } + assert_raise ActiveModel::MassAssignmentSecurity::Error do + @strict_sanitizer.sanitize(original_attributes, @authorizer) + end + end + end diff --git a/activemodel/test/cases/mass_assignment_security/white_list_test.rb b/activemodel/test/cases/mass_assignment_security/white_list_test.rb index aa3596ad2a..737b55492a 100644 --- a/activemodel/test/cases/mass_assignment_security/white_list_test.rb +++ b/activemodel/test/cases/mass_assignment_security/white_list_test.rb @@ -16,13 +16,4 @@ class WhiteListTest < ActiveModel::TestCase assert_equal true, @white_list.deny?('admin') end - test "sanitize attributes" do - original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied', 'admin(1)' => 'denied' } - attributes = @white_list.sanitize(original_attributes) - - assert attributes.key?('first_name'), "Allowed key shouldn't be rejected" - assert !attributes.key?('admin'), "Denied key should be rejected" - assert !attributes.key?('admin(1)'), "Multi-parameter key should be detected" - end - end diff --git a/activemodel/test/cases/mass_assignment_security_test.rb b/activemodel/test/cases/mass_assignment_security_test.rb index 43a12eed61..a778240827 100644 --- a/activemodel/test/cases/mass_assignment_security_test.rb +++ b/activemodel/test/cases/mass_assignment_security_test.rb @@ -1,6 +1,15 @@ require "cases/helper" require 'models/mass_assignment_specific' + +class CustomSanitizer < ActiveModel::MassAssignmentSecurity::Sanitizer + + def process_removed_attributes(attrs) + raise StandardError + end + +end + class MassAssignmentSecurityTest < ActiveModel::TestCase def test_attribute_protection @@ -76,4 +85,15 @@ class MassAssignmentSecurityTest < ActiveModel::TestCase assert_equal sanitized, { } end + def test_custom_sanitizer + user = User.new + User.mass_assignment_sanitizer = CustomSanitizer.new + assert_raise StandardError do + user.sanitize_for_mass_assignment("admin" => true) + end + ensure + User.mass_assignment_sanitizer = nil + + end + end diff --git a/activerecord/RUNNING_UNIT_TESTS b/activerecord/RUNNING_UNIT_TESTS index 812ac6440d..16444249cc 100644 --- a/activerecord/RUNNING_UNIT_TESTS +++ b/activerecord/RUNNING_UNIT_TESTS @@ -1,37 +1,26 @@ -== Creating the test database +== Configure databases -The default names for the test databases are "activerecord_unittest" and -"activerecord_unittest2". If you want to use another database name, then be sure -to update the connection adapter setups you want to test within -test/connections/<your database>/connection.rb. -When you have the database online, you can import the fixture tables with -the test/schema/*.sql files. +Copy test/config.example.yml to test/config.yml and edit as needed. Or just run the tests for +the first time, which will do the copy automatically and use the default (sqlite3). -Make sure that you create database objects with the same user that you specified in -connection.rb otherwise (on Postgres, at least) tests for default values will fail. +You can build postgres and mysql databases using the build_postgresql and build_mysql rake tasks. -== Running with Rake +== Running the tests -The easiest way to run the unit tests is through Rake. The default task runs -the entire test suite for all the adapters. You can also run the suite on just -one adapter by using the tasks test_mysql, test_sqlite3, test_postgresql or any -of the other test_ tasks. For more information, checkout the full array of rake -tasks with "rake -T" +You can run a particular test file from the command line, e.g. -Rake can be found at http://rake.rubyforge.org + $ ruby test/cases/base_test.rb -== Running by hand +To run a specific test: -Unit tests are located in test/cases directory. If you only want to run a single test suite, -you can do so with: + $ ruby test/cases/base_test.rb -n test_something_works - rake test_mysql TEST=test/cases/base_test.rb +You can run with a database other than the default you set in test/config.yml, using the ARCONN +environment variable: -That'll run the base suite using the MySQL-Ruby adapter. Some tests rely on the schema -being initialized - you can initialize the schema with: + $ ARCONN=postgresql ruby test/cases/base_test.rb - rake test_mysql TEST=test/cases/aaa_create_tables_test.rb - rake mysql:build_databases +You can run all the tests for a given database via rake: To setup the testing environment for PostgreSQL use this command: diff --git a/activerecord/Rakefile b/activerecord/Rakefile index 346c7e8142..d5863ab14d 100755 --- a/activerecord/Rakefile +++ b/activerecord/Rakefile @@ -43,26 +43,24 @@ end %w( mysql mysql2 postgresql sqlite3 sqlite3_mem firebird db2 oracle sybase openbase frontbase jdbcmysql jdbcpostgresql jdbcsqlite3 jdbcderby jdbch2 jdbchsqldb ).each do |adapter| Rake::TestTask.new("test_#{adapter}") { |t| - connection_path = "test/connections/#{adapter =~ /jdbc/ ? 'jdbc' : 'native'}_#{adapter}" adapter_short = adapter == 'db2' ? adapter : adapter[/^[a-z0-9]+/] - t.libs << "test" << connection_path t.test_files = (Dir.glob( "test/cases/**/*_test.rb" ).reject { |x| x =~ /\/adapters\// } + Dir.glob("test/cases/adapters/#{adapter_short}/**/*_test.rb")).sort t.verbose = true t.warning = true + t.ruby_opts = ["-r#{File.expand_path('../', __FILE__)}/test/connections/#{adapter}"] } task "isolated_test_#{adapter}" do - connection_path = "test/connections/#{adapter =~ /jdbc/ ? 'jdbc' : 'native'}_#{adapter}" adapter_short = adapter == 'db2' ? adapter : adapter[/^[a-z0-9]+/] - puts [adapter, adapter_short, connection_path].inspect + puts [adapter, adapter_short].inspect ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) (Dir["test/cases/**/*_test.rb"].reject { |x| x =~ /\/adapters\// } + Dir["test/cases/adapters/#{adapter_short}/**/*_test.rb"]).all? do |file| - sh(ruby, "-Ilib:test:#{connection_path}", file) + sh(ruby, "-Itest", "-r#{File.expand_path('../', __FILE__)}/test/connections/#{adapter}", file) end or raise "Failures" end diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 5538c837b3..2cbfa42718 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -76,12 +76,6 @@ module ActiveRecord end end - class HasAndBelongsToManyAssociationWithPrimaryKeyError < ActiveRecordError #:nodoc: - def initialize(reflection) - super("Primary key is not allowed in a has_and_belongs_to_many join table (#{reflection.options[:join_table]}).") - end - end - class HasAndBelongsToManyAssociationForeignKeyNeeded < ActiveRecordError #:nodoc: def initialize(reflection) super("Cannot create self referential has_and_belongs_to_many association on '#{reflection.class_name rescue nil}##{reflection.name rescue nil}'. :association_foreign_key cannot be the same as the :foreign_key.") @@ -866,7 +860,7 @@ module ActiveRecord # the inverse of each other and the inverse of the +dungeon+ association on +EvilWizard+ # is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default, # Active Record doesn't know anything about these inverse relationships and so no object - # loading optimisation is possible. For example: + # loading optimization is possible. For example: # # d = Dungeon.first # t = d.traps.first diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb index 94847bc2ae..9e6d9e73c5 100644 --- a/activerecord/lib/active_record/associations/association_scope.rb +++ b/activerecord/lib/active_record/associations/association_scope.rb @@ -60,7 +60,7 @@ module ActiveRecord scope = scope.joins(join( join_table, - table[reflection.active_record_primary_key]. + table[reflection.association_primary_key]. eq(join_table[reflection.association_foreign_key]) )) diff --git a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb index 4b48757da7..d7632b2ea9 100644 --- a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb +++ b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb @@ -39,10 +39,6 @@ module ActiveRecord::Associations::Builder model.send(:undecorated_table_name, model.to_s), model.send(:undecorated_table_name, reflection.class_name) ) - - if model.connection.supports_primary_key? && (model.connection.primary_key(reflection.options[:join_table]) rescue false) - raise ActiveRecord::HasAndBelongsToManyAssociationWithPrimaryKeyError.new(reflection) - end end # Generates a join table name from two provided table names. diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 8a028c8996..7e1a41e84d 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -104,26 +104,11 @@ module ActiveRecord end def create(attributes = {}, options = {}, &block) - unless owner.persisted? - raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved" - end - - if attributes.is_a?(Array) - attributes.collect { |attr| create(attr, options, &block) } - else - transaction do - add_to_target(build_record(attributes, options)) do |record| - yield(record) if block_given? - insert_record(record) - end - end - end + create_record(attributes, options, &block) end - def create!(attrs = {}, options = {}, &block) - record = create(attrs, options, &block) - Array.wrap(record).each(&:save!) - record + def create!(attributes = {}, options = {}, &block) + create_record(attributes, options, true, &block) end # Add +records+ to this association. Returns +self+ so method calls may be chained. @@ -402,9 +387,13 @@ module ActiveRecord return memory if persisted.empty? persisted.map! do |record| - mem_record = memory.delete(record) + # Unfortunately we cannot simply do memory.delete(record) since on 1.8 this returns + # record rather than memory.at(memory.index(record)). The behaviour is fixed in 1.9. + mem_index = memory.index(record) + + if mem_index + mem_record = memory.delete_at(mem_index) - if mem_record (record.attribute_names - mem_record.changes.keys).each do |name| mem_record[name] = record[name] end @@ -418,8 +407,25 @@ module ActiveRecord persisted + memory end + def create_record(attributes, options, raise = false, &block) + unless owner.persisted? + raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved" + end + + if attributes.is_a?(Array) + attributes.collect { |attr| create_record(attr, options, raise, &block) } + else + transaction do + add_to_target(build_record(attributes, options)) do |record| + yield(record) if block_given? + insert_record(record, true, raise) + end + end + end + end + # Do the relevant stuff to insert the given record into the association collection. - def insert_record(record, validate = true) + def insert_record(record, validate = true, raise = false) raise NotImplementedError end @@ -430,7 +436,6 @@ module ActiveRecord def build_record(attributes, options) record = reflection.build_association(attributes, options) record.assign_attributes(create_scope.except(*record.changed), :without_protection => true) - record.assign_attributes(attributes, options) record end diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb index adfc71d435..81b4a26b04 100644 --- a/activerecord/lib/active_record/associations/collection_proxy.rb +++ b/activerecord/lib/active_record/associations/collection_proxy.rb @@ -56,6 +56,8 @@ module ActiveRecord Array.wrap(association.options[:extend]).each { |ext| proxy_extend(ext) } end + alias_method :new, :build + def respond_to?(*args) super || (load_target && target.respond_to?(*args)) || @@ -115,14 +117,6 @@ module ActiveRecord @association.reload self end - - def new(*args, &block) - if @association.is_a?(HasManyThroughAssociation) - @association.build(*args, &block) - else - method_missing(:new, *args, &block) - end - end end end end diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb index 217213808b..f7ce70db1a 100644 --- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb +++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb @@ -9,8 +9,14 @@ module ActiveRecord super end - def insert_record(record, validate = true) - return if record.new_record? && !record.save(:validate => validate) + def insert_record(record, validate = true, raise = false) + if record.new_record? + if raise + record.save!(:validate => validate) + else + return unless record.save(:validate => validate) + end + end if options[:insert_sql] owner.connection.insert(interpolate(options[:insert_sql], record)) diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index 7172e89a05..50ee60284c 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -7,9 +7,14 @@ module ActiveRecord # is provided by its child HasManyThroughAssociation. class HasManyAssociation < CollectionAssociation #:nodoc: - def insert_record(record, validate = true) + def insert_record(record, validate = true, raise = false) set_owner_attributes(record) - record.save(:validate => validate) + + if raise + record.save!(:validate => validate) + else + record.save(:validate => validate) + end end private diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index 7708228d23..2e818dca5d 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -6,8 +6,6 @@ module ActiveRecord class HasManyThroughAssociation < HasManyAssociation #:nodoc: include ThroughAssociation - alias_method :new, :build - # Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been # loaded and calling collection.size if it has. If it's more likely than not that the collection does # have a size larger than zero, and you need to fetch that collection afterwards, it'll take one fewer @@ -33,9 +31,16 @@ module ActiveRecord super end - def insert_record(record, validate = true) + def insert_record(record, validate = true, raise = false) ensure_not_nested - return if record.new_record? && !record.save(:validate => validate) + + if record.new_record? + if raise + record.save!(:validate => validate) + else + return unless record.save(:validate => validate) + end + end through_record(record).save! update_counter(1) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index f74810720d..08cc282d09 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1308,7 +1308,6 @@ MSG rescue NameError => e # We don't want to swallow NoMethodError < NameError errors raise e unless e.instance_of?(NameError) - rescue ArgumentError end end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb index a754f46af0..74c07c624d 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -161,7 +161,7 @@ module ActiveRecord yield td if block_given? if options[:force] && table_exists?(table_name) - drop_table(table_name, options) + drop_table(table_name) end create_sql = "CREATE#{' TEMPORARY' if options[:temporary]} TABLE " @@ -253,7 +253,7 @@ module ActiveRecord end # Drops a table from the database. - def drop_table(table_name, options = {}) + def drop_table(table_name) execute "DROP TABLE #{quote_table_name(table_name)}" end diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb index 6e2c3f4527..24d8c8cad2 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb @@ -427,10 +427,6 @@ module ActiveRecord tables(nil, schema).include? table end - def drop_table(table_name, options = {}) - super(table_name, options) - end - # Returns an array of indexes for the given table. def indexes(table_name, name = nil) indexes = [] diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index ee83f8120d..8d7dd8bacf 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -568,10 +568,6 @@ module ActiveRecord tables(nil, schema).include? table end - def drop_table(table_name, options = {}) - super(table_name, options) - end - # Returns an array of indexes for the given table. def indexes(table_name, name = nil)#:nodoc: indexes = [] diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 8b48c055ac..3e390ba994 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -805,8 +805,8 @@ module ActiveRecord end if pk && sequence - quoted_sequence = quote_column_name(sequence) - + quoted_sequence = quote_table_name(sequence) + select_value <<-end_sql, 'Reset sequence' SELECT setval('#{quoted_sequence}', (SELECT COALESCE(MAX(#{quote_column_name pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false) end_sql @@ -818,18 +818,25 @@ module ActiveRecord # First try looking for a sequence with a dependency on the # given table's primary key. result = exec_query(<<-end_sql, 'SCHEMA').rows.first - SELECT attr.attname, seq.relname + SELECT attr.attname, ns.nspname, seq.relname FROM pg_class seq INNER JOIN pg_depend dep ON seq.oid = dep.objid INNER JOIN pg_attribute attr ON attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1] + INNER JOIN pg_namespace ns ON seq.relnamespace = ns.oid WHERE seq.relkind = 'S' AND cons.contype = 'p' AND dep.refobjid = '#{quote_table_name(table)}'::regclass end_sql # [primary_key, sequence] - [result.first, result.last] + if result.second == 'public' then + sequence = result.last + else + sequence = result.second+'.'+result.last + end + + [result.first, sequence] rescue nil end diff --git a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb index 3c6f52e0fa..724b2e6d9c 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb @@ -102,6 +102,10 @@ module ActiveRecord # Clears the prepared statements cache. def clear_cache! + @statements.values.map { |hash| hash[:stmt] }.each { |stmt| + stmt.close unless stmt.closed? + } + @statements.clear end diff --git a/activerecord/lib/active_record/migration/command_recorder.rb b/activerecord/lib/active_record/migration/command_recorder.rb index cf4a97d054..f01e94169f 100644 --- a/activerecord/lib/active_record/migration/command_recorder.rb +++ b/activerecord/lib/active_record/migration/command_recorder.rb @@ -79,8 +79,10 @@ module ActiveRecord end def invert_add_index(args) - table, columns, _ = *args - [:remove_index, [table, {:column => columns}]] + table, columns, options = *args + index_name = options.try(:[], :name) + options_hash = index_name ? {:name => index_name} : {:column => columns} + [:remove_index, [table, options_hash]] end def invert_remove_timestamps(args) diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb index 588f52be44..14db7a6cd6 100644 --- a/activerecord/lib/active_record/named_scope.rb +++ b/activerecord/lib/active_record/named_scope.rb @@ -17,7 +17,7 @@ module ActiveRecord # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects # # fruits = Fruit.scoped - # fruits = fruits.where(:colour => 'red') if options[:red_only] + # fruits = fruits.where(:color => 'red') if options[:red_only] # fruits = fruits.limit(10) if limited? # # Anonymous \scopes tend to be useful when procedurally generating complex diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index d88e2693b6..317af8a15d 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -6,13 +6,13 @@ module ActiveRecord JoinOperation = Struct.new(:relation, :join_class, :on) ASSOCIATION_METHODS = [:includes, :eager_load, :preload] MULTI_VALUE_METHODS = [:select, :group, :order, :joins, :where, :having, :bind] - SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :create_with, :from, :reorder] + SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :create_with, :from, :reorder, :reverse_order] include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches # These are explicitly delegated to improve performance (avoids method_missing) delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to => :to_a - delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key, :to => :klass + delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key, :connection, :column_hash,:to => :klass attr_reader :table, :klass, :loaded attr_accessor :extensions, :default_scoped diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index a785f38e89..aabe5c269b 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -196,7 +196,7 @@ module ActiveRecord def execute_simple_calculation(operation, column_name, distinct) #:nodoc: # Postgresql doesn't like ORDER BY when there are no GROUP BY - relation = reorder(nil) + relation = with_default_scope.reorder(nil) if operation == "count" && (relation.limit_value || relation.offset_value) # Shortcut when limit is zero. @@ -245,7 +245,7 @@ module ActiveRecord "#{field} AS #{aliaz}" } - relation = except(:group).group(group.join(',')) + relation = with_default_scope.except(:group).group(group.join(',')) relation.select_values = select_values calculated_data = @klass.connection.select_all(relation.to_sql) diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 94aa999715..739363415c 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -9,7 +9,7 @@ module ActiveRecord :select_values, :group_values, :order_values, :joins_values, :where_values, :having_values, :bind_values, :limit_value, :offset_value, :lock_value, :readonly_value, :create_with_value, - :from_value, :reorder_value + :from_value, :reorder_value, :reverse_order_value def includes(*args) args.reject! {|a| a.blank? } @@ -158,13 +158,9 @@ module ActiveRecord end def reverse_order - order_clause = arel.order_clauses - - order = order_clause.empty? ? - "#{table_name}.#{primary_key} DESC" : - reverse_sql_order(order_clause).join(', ') - - except(:order).order(Arel.sql(order)) + relation = clone + relation.reverse_order_value = !relation.reverse_order_value + relation end def arel @@ -186,6 +182,7 @@ module ActiveRecord arel.group(*@group_values.uniq.reject{|g| g.blank?}) unless @group_values.empty? order = @reorder_value ? @reorder_value : @order_values + order = reverse_sql_order(order) if @reverse_order_value arel.order(*order.uniq.reject{|o| o.blank?}) unless order.empty? build_select(arel, @select_values.uniq) @@ -306,6 +303,8 @@ module ActiveRecord end def reverse_sql_order(order_query) + order_query = ["#{quoted_table_name}.#{quoted_primary_key} ASC"] if order_query.empty? + order_query.join(', ').split(',').collect do |s| s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC') end diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb index 62e6999736..19585f6214 100644 --- a/activerecord/lib/active_record/schema_dumper.rb +++ b/activerecord/lib/active_record/schema_dumper.rb @@ -106,7 +106,7 @@ HEADER spec = {} spec[:name] = column.name.inspect - # AR has an optimisation which handles zero-scale decimals as integers. This + # AR has an optimization which handles zero-scale decimals as integers. This # code ensures that the dumper still dumps the column as a decimal. spec[:type] = if column.type == :integer && [/^numeric/, /^decimal/].any? { |e| e.match(column.sql_type) } 'decimal' diff --git a/activerecord/lib/active_record/serialization.rb b/activerecord/lib/active_record/serialization.rb index be4354ce6a..e3185a9c5a 100644 --- a/activerecord/lib/active_record/serialization.rb +++ b/activerecord/lib/active_record/serialization.rb @@ -31,9 +31,6 @@ module ActiveRecord #:nodoc: def serializable_add_includes(options = {}) return unless include_associations = options.delete(:include) - base_only_or_except = { :except => options[:except], - :only => options[:only] } - include_has_options = include_associations.is_a?(Hash) associations = include_has_options ? include_associations.keys : Array.wrap(include_associations) @@ -46,9 +43,8 @@ module ActiveRecord #:nodoc: end if records - association_options = include_has_options ? include_associations[association] : base_only_or_except - opts = options.merge(association_options) - yield(association, records, opts) + association_options = include_has_options ? include_associations[association] : {} + yield(association, records, association_options) end end diff --git a/activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb b/activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb index 8f0bf1ef0d..9ea3248513 100644 --- a/activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb +++ b/activerecord/lib/rails/generators/active_record/session_migration/templates/migration.rb @@ -1,5 +1,5 @@ class <%= migration_class_name %> < ActiveRecord::Migration - def up + def change create_table :<%= session_table_name %> do |t| t.string :session_id, :null => false t.text :data @@ -9,8 +9,4 @@ class <%= migration_class_name %> < ActiveRecord::Migration add_index :<%= session_table_name %>, :session_id add_index :<%= session_table_name %>, :updated_at end - - def down - drop_table :<%= session_table_name %> - end end diff --git a/activerecord/test/.gitignore b/activerecord/test/.gitignore new file mode 100644 index 0000000000..a0ec5967dd --- /dev/null +++ b/activerecord/test/.gitignore @@ -0,0 +1 @@ +/config.yml diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb index 49b2e945c3..e7a3bb9ced 100644 --- a/activerecord/test/cases/adapter_test.rb +++ b/activerecord/test/cases/adapter_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) class AdapterTest < ActiveRecord::TestCase def setup @@ -43,7 +43,7 @@ class AdapterTest < ActiveRecord::TestCase def test_current_database if @connection.respond_to?(:current_database) - assert_equal ENV['ARUNIT_DB_NAME'] || "activerecord_unittest", @connection.current_database + assert_equal ARTest.connection_config['arunit']['database'], @connection.current_database end end @@ -68,7 +68,12 @@ class AdapterTest < ActiveRecord::TestCase begin assert_nothing_raised do ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['arunit'].except(:database)) - ActiveRecord::Base.connection.execute "SELECT activerecord_unittest.pirates.*, activerecord_unittest2.courses.* FROM activerecord_unittest.pirates, activerecord_unittest2.courses" + + config = ARTest.connection_config + ActiveRecord::Base.connection.execute( + "SELECT #{config['arunit']['database']}.pirates.*, #{config['arunit2']['database']}.courses.* " \ + "FROM #{config['arunit']['database']}.pirates, #{config['arunit2']['database']}.courses" + ) end ensure ActiveRecord::Base.establish_connection 'arunit' diff --git a/activerecord/test/cases/adapters/firebird/connection_test.rb b/activerecord/test/cases/adapters/firebird/connection_test.rb index f57ea686a5..47e8859ac6 100644 --- a/activerecord/test/cases/adapters/firebird/connection_test.rb +++ b/activerecord/test/cases/adapters/firebird/connection_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) class FirebirdConnectionTest < ActiveRecord::TestCase def test_charset_properly_set diff --git a/activerecord/test/cases/adapters/firebird/default_test.rb b/activerecord/test/cases/adapters/firebird/default_test.rb index 713c7e11bf..2d5e45dd74 100644 --- a/activerecord/test/cases/adapters/firebird/default_test.rb +++ b/activerecord/test/cases/adapters/firebird/default_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) require 'models/default' class DefaultTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/adapters/firebird/migration_test.rb b/activerecord/test/cases/adapters/firebird/migration_test.rb index 710661b9bd..0fe3d4a858 100644 --- a/activerecord/test/cases/adapters/firebird/migration_test.rb +++ b/activerecord/test/cases/adapters/firebird/migration_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) require 'models/course' class FirebirdMigrationTest < ActiveRecord::TestCase @@ -24,7 +24,7 @@ class FirebirdMigrationTest < ActiveRecord::TestCase assert !sequence_exists?('foo_seq') assert sequence_exists?('foo_custom_seq') - assert_nothing_raised { @connection.drop_table(:foo, :sequence => 'foo_custom_seq') } + assert_nothing_raised { @connection.drop_table(:foo) } assert !sequence_exists?('foo_custom_seq') ensure FireRuby::Generator.new('foo_custom_seq', @fireruby_connection).drop rescue nil diff --git a/activerecord/test/cases/adapters/mysql/active_schema_test.rb b/activerecord/test/cases/adapters/mysql/active_schema_test.rb index 509baacaef..c817b259b4 100644 --- a/activerecord/test/cases/adapters/mysql/active_schema_test.rb +++ b/activerecord/test/cases/adapters/mysql/active_schema_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) class ActiveSchemaTest < ActiveRecord::TestCase def setup diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb index eee771ecff..703eb5a8bd 100644 --- a/activerecord/test/cases/adapters/mysql/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql/connection_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) class MysqlConnectionTest < ActiveRecord::TestCase def setup diff --git a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb index 146b77a95c..756115e5c9 100644 --- a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb +++ b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb @@ -1,6 +1,6 @@ # encoding: utf-8 -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) module ActiveRecord module ConnectionAdapters diff --git a/activerecord/test/cases/adapters/mysql/quoting_test.rb b/activerecord/test/cases/adapters/mysql/quoting_test.rb index 9673e2bb46..7933800440 100644 --- a/activerecord/test/cases/adapters/mysql/quoting_test.rb +++ b/activerecord/test/cases/adapters/mysql/quoting_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) module ActiveRecord module ConnectionAdapters @@ -23,4 +23,3 @@ module ActiveRecord end end end - diff --git a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb index 292c7efebb..2750831b93 100644 --- a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb +++ b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) class Group < ActiveRecord::Base Group.table_name = 'group' diff --git a/activerecord/test/cases/adapters/mysql/schema_test.rb b/activerecord/test/cases/adapters/mysql/schema_test.rb index a2155d1dd1..8b26d303bf 100644 --- a/activerecord/test/cases/adapters/mysql/schema_test.rb +++ b/activerecord/test/cases/adapters/mysql/schema_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) require 'models/post' require 'models/comment' diff --git a/activerecord/test/cases/adapters/mysql/sp_test.rb b/activerecord/test/cases/adapters/mysql/sp_test.rb index 3ca2917ca4..baa44fab70 100644 --- a/activerecord/test/cases/adapters/mysql/sp_test.rb +++ b/activerecord/test/cases/adapters/mysql/sp_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) require 'models/topic' class StoredProcedureTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/adapters/mysql2/active_schema_test.rb b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb index a83399d0cd..ca716f7016 100644 --- a/activerecord/test/cases/adapters/mysql2/active_schema_test.rb +++ b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) class ActiveSchemaTest < ActiveRecord::TestCase def setup diff --git a/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb b/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb index cd9c1041dc..7bb35d755a 100644 --- a/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb +++ b/activerecord/test/cases/adapters/mysql2/bind_parameter_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) require 'models/topic' module ActiveRecord diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb index 26091c713b..1c523dad69 100644 --- a/activerecord/test/cases/adapters/mysql2/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) class MysqlConnectionTest < ActiveRecord::TestCase def setup diff --git a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb index 752b864818..9cb30b0fd1 100644 --- a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb +++ b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) class Group < ActiveRecord::Base Group.table_name = 'group' diff --git a/activerecord/test/cases/adapters/mysql2/schema_test.rb b/activerecord/test/cases/adapters/mysql2/schema_test.rb index 858d1da2dd..ec89972360 100644 --- a/activerecord/test/cases/adapters/mysql2/schema_test.rb +++ b/activerecord/test/cases/adapters/mysql2/schema_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) require 'models/post' require 'models/comment' diff --git a/activerecord/test/cases/adapters/oracle/synonym_test.rb b/activerecord/test/cases/adapters/oracle/synonym_test.rb index b9a422a6ca..4cbca6dcb2 100644 --- a/activerecord/test/cases/adapters/oracle/synonym_test.rb +++ b/activerecord/test/cases/adapters/oracle/synonym_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) require 'models/topic' require 'models/subject' diff --git a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb index e4746d4aa3..1802e2be24 100644 --- a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require File.expand_path('../../../helper', __FILE__) class PostgresqlActiveSchemaTest < ActiveRecord::TestCase def setup diff --git a/activerecord/test/cases/adapters/postgresql/datatype_test.rb b/activerecord/test/cases/adapters/postgresql/datatype_test.rb index ce08e4c6a7..c383e8b6fb 100644 --- a/activerecord/test/cases/adapters/postgresql/datatype_test.rb +++ b/activerecord/test/cases/adapters/postgresql/datatype_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) class PostgresqlArray < ActiveRecord::Base end diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb index 7c49236854..14e78ed982 100644 --- a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb +++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb @@ -1,5 +1,5 @@ # encoding: utf-8 -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) module ActiveRecord module ConnectionAdapters diff --git a/activerecord/test/cases/adapters/postgresql/quoting_test.rb b/activerecord/test/cases/adapters/postgresql/quoting_test.rb index 172055f15c..e95d10c594 100644 --- a/activerecord/test/cases/adapters/postgresql/quoting_test.rb +++ b/activerecord/test/cases/adapters/postgresql/quoting_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) module ActiveRecord module ConnectionAdapters diff --git a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb index d5e1838543..8b9c4d337a 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) class SchemaThing < ActiveRecord::Base end diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb index a5c3e69af9..6f3dba4168 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) class SchemaTest < ActiveRecord::TestCase self.use_transactional_fixtures = false diff --git a/activerecord/test/cases/adapters/postgresql/timestamp_test.rb b/activerecord/test/cases/adapters/postgresql/timestamp_test.rb new file mode 100644 index 0000000000..fb4616dc76 --- /dev/null +++ b/activerecord/test/cases/adapters/postgresql/timestamp_test.rb @@ -0,0 +1,30 @@ +require File.expand_path('../../../helper', __FILE__) +require 'models/developer' + +class TimestampTest < ActiveRecord::TestCase + def test_load_infinity_and_beyond + unless current_adapter?(:PostgreSQLAdapter) + return skip("only tested on postgresql") + end + + d = Developer.find_by_sql("select 'infinity'::timestamp as updated_at") + assert d.first.updated_at.infinite?, 'timestamp should be infinite' + + d = Developer.find_by_sql("select '-infinity'::timestamp as updated_at") + time = d.first.updated_at + assert time.infinite?, 'timestamp should be infinite' + assert_operator time, :<, 0 + end + + def test_save_infinity_and_beyond + unless current_adapter?(:PostgreSQLAdapter) + return skip("only tested on postgresql") + end + + d = Developer.create!(:name => 'aaron', :updated_at => 1.0 / 0.0) + assert_equal(1.0 / 0.0, d.updated_at) + + d = Developer.create!(:name => 'aaron', :updated_at => -1.0 / 0.0) + assert_equal(-1.0 / 0.0, d.updated_at) + end +end diff --git a/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb b/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb index 575b4806c1..899df1d59a 100644 --- a/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) class CopyTableTest < ActiveRecord::TestCase fixtures :customers, :companies, :comments diff --git a/activerecord/test/cases/adapters/sqlite3/quoting_test.rb b/activerecord/test/cases/adapters/sqlite3/quoting_test.rb index 0d9db92447..51f01c262d 100644 --- a/activerecord/test/cases/adapters/sqlite3/quoting_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/quoting_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) require 'bigdecimal' require 'yaml' diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index 6ff04e3eb3..d58a804815 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -1,5 +1,5 @@ # encoding: utf-8 -require "cases/helper" +require File.expand_path('../../../helper', __FILE__) module ActiveRecord module ConnectionAdapters diff --git a/activerecord/test/cases/aggregations_test.rb b/activerecord/test/cases/aggregations_test.rb index 3e0e6dce2c..d296364d7f 100644 --- a/activerecord/test/cases/aggregations_test.rb +++ b/activerecord/test/cases/aggregations_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/customer' require 'active_support/core_ext/exception' diff --git a/activerecord/test/cases/ar_schema_test.rb b/activerecord/test/cases/ar_schema_test.rb index 588adc38e3..eb4488899f 100644 --- a/activerecord/test/cases/ar_schema_test.rb +++ b/activerecord/test/cases/ar_schema_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) if ActiveRecord::Base.connection.supports_migrations? diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 5a900e0605..d7293aa1e3 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/developer' require 'models/project' require 'models/company' diff --git a/activerecord/test/cases/associations/callbacks_test.rb b/activerecord/test/cases/associations/callbacks_test.rb index 2d0d4541b4..387a25b7b1 100644 --- a/activerecord/test/cases/associations/callbacks_test.rb +++ b/activerecord/test/cases/associations/callbacks_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/post' require 'models/author' require 'models/project' diff --git a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb index 49d8722aff..d21afff978 100644 --- a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb +++ b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/post' require 'models/comment' require 'models/author' @@ -8,10 +8,12 @@ require 'models/company' require 'models/topic' require 'models/reply' require 'models/person' +require 'models/vertex' +require 'models/edge' class CascadedEagerLoadingTest < ActiveRecord::TestCase fixtures :authors, :mixins, :companies, :posts, :topics, :accounts, :comments, - :categorizations, :people, :categories + :categorizations, :people, :categories, :edges, :vertices def test_eager_association_loading_with_cascaded_two_levels authors = Author.find(:all, :include=>{:posts=>:comments}, :order=>"authors.id") @@ -164,12 +166,6 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase authors[2].post_about_thinking.comments.first end end -end - -require 'models/vertex' -require 'models/edge' -class CascadedEagerLoadingTest < ActiveRecord::TestCase - fixtures :edges, :vertices def test_eager_association_loading_with_recursive_cascading_four_levels_has_many_through source = Vertex.find(:first, :include=>{:sinks=>{:sinks=>{:sinks=>:sinks}}}, :order => 'vertices.id') diff --git a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb index d75791cab9..41cf745f91 100644 --- a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb +++ b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require File.expand_path('../../helper', __FILE__) require 'models/post' require 'models/tagging' diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb index 2cf9f89c3c..de1f47873f 100644 --- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb +++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require File.expand_path('../../helper', __FILE__) require 'models/post' require 'models/tag' require 'models/author' diff --git a/activerecord/test/cases/associations/eager_singularization_test.rb b/activerecord/test/cases/associations/eager_singularization_test.rb index 07d0b24613..ffb5411a5b 100644 --- a/activerecord/test/cases/associations/eager_singularization_test.rb +++ b/activerecord/test/cases/associations/eager_singularization_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) class Virus < ActiveRecord::Base belongs_to :octopus diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index 5028cee32d..945edad48a 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/post' require 'models/tagging' require 'models/tag' @@ -380,6 +380,18 @@ class EagerAssociationTest < ActiveRecord::TestCase assert_equal subscriptions, subscriber.subscriptions.sort_by(&:id) end + def test_string_id_column_joins + s = Subscriber.create! do |c| + c.id = "PL" + end + + b = Book.create! + + Subscription.create!(:subscriber_id => "PL", :book_id => b.id) + s.reload + s.book_ids = s.book_ids + end + def test_eager_load_has_many_through_with_string_keys books = books(:awdr, :rfr) subscriber = Subscriber.find(subscribers(:second).id, :include => :books) diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb index 24830a661a..c0a8f74834 100644 --- a/activerecord/test/cases/associations/extension_test.rb +++ b/activerecord/test/cases/associations/extension_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/post' require 'models/comment' require 'models/project' diff --git a/activerecord/test/cases/associations/habtm_join_table_test.rb b/activerecord/test/cases/associations/habtm_join_table_test.rb index 745f169ad7..cc0a6cd6c2 100644 --- a/activerecord/test/cases/associations/habtm_join_table_test.rb +++ b/activerecord/test/cases/associations/habtm_join_table_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require File.expand_path('../../helper', __FILE__) class MyReader < ActiveRecord::Base has_and_belongs_to_many :my_books @@ -32,13 +32,4 @@ class HabtmJoinTableTest < ActiveRecord::TestCase ActiveRecord::Base.connection.drop_table :my_readers ActiveRecord::Base.connection.drop_table :my_books_my_readers end - - uses_transaction :test_should_raise_exception_when_join_table_has_a_primary_key - def test_should_raise_exception_when_join_table_has_a_primary_key - if ActiveRecord::Base.connection.supports_primary_key? - assert_raise ActiveRecord::HasAndBelongsToManyAssociationWithPrimaryKeyError do - MyReader.has_and_belongs_to_many :my_books - end - end - end end diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index f4d14853d3..171177ad1d 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/developer' require 'models/project' require 'models/company' @@ -101,6 +101,16 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase assert_equal 't1', record[1] end + def test_proper_usage_of_primary_keys_and_join_table + setup_data_for_habtm_case + + assert_equal 'country_id', Country.primary_key + assert_equal 'treaty_id', Treaty.primary_key + + country = Country.first + assert_equal 1, country.treaties.count + end + def test_has_and_belongs_to_many david = Developer.find(1) @@ -235,6 +245,21 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated end + def test_new_aliased_to_build + devel = Developer.find(1) + proj = assert_no_queries { devel.projects.new("name" => "Projekt") } + assert !devel.projects.loaded? + + assert_equal devel.projects.last, proj + assert devel.projects.loaded? + + assert !proj.persisted? + devel.save + assert proj.persisted? + assert_equal devel.projects.last, proj + assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated + end + def test_build_by_new_record devel = Developer.new(:name => "Marcel", :salary => 75000) devel.projects.build(:name => "Make bed") diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 43974fd895..b87a1744c1 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1,7 +1,8 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/developer' require 'models/project' require 'models/company' +require 'models/contract' require 'models/topic' require 'models/reply' require 'models/category' @@ -536,6 +537,16 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal 3, companies(:first_firm).clients_of_firm(true).size end + def test_new_aliased_to_build + company = companies(:first_firm) + new_client = assert_no_queries { company.clients_of_firm.new("name" => "Another Client") } + assert !company.clients_of_firm.loaded? + + assert_equal "Another Client", new_client.name + assert !new_client.persisted? + assert_equal new_client, company.clients_of_firm.last + end + def test_build company = companies(:first_firm) new_client = assert_no_queries { company.clients_of_firm.build("name" => "Another Client") } @@ -1475,4 +1486,12 @@ class HasManyAssociationsTest < ActiveRecord::TestCase tagging = Tagging.create! :taggable => post assert_equal [tagging], post.taggings end + + def test_dont_call_save_callbacks_twice_on_has_many + firm = companies(:first_firm) + contract = firm.contracts.create! + + assert_equal 1, contract.hi_count + assert_equal 1, contract.bye_count + end end diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 877148bd5e..476bc637f6 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/post' require 'models/person' require 'models/reference' diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index 299688d840..9bafe0f57d 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/developer' require 'models/project' require 'models/company' diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index 2503349c08..24576fb580 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/club' require 'models/member_type' require 'models/member' diff --git a/activerecord/test/cases/associations/identity_map_test.rb b/activerecord/test/cases/associations/identity_map_test.rb index 9b8635774c..0dd6c76efd 100644 --- a/activerecord/test/cases/associations/identity_map_test.rb +++ b/activerecord/test/cases/associations/identity_map_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/author' require 'models/post' diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb index e5e9ca6131..1c0fe8368f 100644 --- a/activerecord/test/cases/associations/inner_join_association_test.rb +++ b/activerecord/test/cases/associations/inner_join_association_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/post' require 'models/comment' require 'models/author' diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb index 76282213d8..9e4975566b 100644 --- a/activerecord/test/cases/associations/inverse_associations_test.rb +++ b/activerecord/test/cases/associations/inverse_associations_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/man' require 'models/face' require 'models/interest' diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index b59ce4efeb..c869e6fbc5 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'active_support/core_ext/object/inclusion' require 'models/tag' require 'models/tagging' diff --git a/activerecord/test/cases/associations/nested_through_associations_test.rb b/activerecord/test/cases/associations/nested_through_associations_test.rb index dd450a2a8e..b13b8d5e36 100644 --- a/activerecord/test/cases/associations/nested_through_associations_test.rb +++ b/activerecord/test/cases/associations/nested_through_associations_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/author' require 'models/post' require 'models/person' diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index 49d82ba2df..8bff37907d 100644 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/developer' require 'models/project' require 'models/company' diff --git a/activerecord/test/cases/attribute_methods/read_test.rb b/activerecord/test/cases/attribute_methods/read_test.rb index 3641031d12..bb0dcb2a77 100644 --- a/activerecord/test/cases/attribute_methods/read_test.rb +++ b/activerecord/test/cases/attribute_methods/read_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'active_support/core_ext/object/inclusion' module ActiveRecord diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index 54c4d4ae90..bf6408be0f 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'active_support/core_ext/object/inclusion' require 'models/minimalistic' require 'models/developer' @@ -134,7 +134,12 @@ class AttributeMethodsTest < ActiveRecord::TestCase if current_adapter?(:MysqlAdapter) def test_read_attributes_before_type_cast_on_boolean bool = Boolean.create({ "value" => false }) - assert_equal 0, bool.reload.attributes_before_type_cast["value"] + if RUBY_PLATFORM =~ /java/ + # JRuby will return the value before typecast as string + assert_equal "0", bool.reload.attributes_before_type_cast["value"] + else + assert_equal 0, bool.reload.attributes_before_type_cast["value"] + end end end diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 8f55b7ebe6..b14c458435 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require File.expand_path('../helper', __FILE__) require 'models/bird' require 'models/company' require 'models/customer' diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 39043447fc..5eb9a825b7 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/post' require 'models/author' require 'models/topic' @@ -1766,6 +1766,13 @@ class BasicsTest < ActiveRecord::TestCase end end + def test_compute_type_argument_error + ActiveSupport::Dependencies.stubs(:constantize).raises(ArgumentError) + assert_raises ArgumentError do + ActiveRecord::Base.send :compute_type, 'InvalidModel' + end + end + def test_clear_cache! # preheat cache c1 = Post.columns diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb index 6620464d6a..31e00c998c 100644 --- a/activerecord/test/cases/batches_test.rb +++ b/activerecord/test/cases/batches_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require File.expand_path('../helper', __FILE__) require 'models/post' class EachTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/binary_test.rb b/activerecord/test/cases/binary_test.rb index 06c14cb108..365c16679e 100644 --- a/activerecord/test/cases/binary_test.rb +++ b/activerecord/test/cases/binary_test.rb @@ -1,5 +1,5 @@ # encoding: utf-8 -require "cases/helper" +require File.expand_path('../helper', __FILE__) # Without using prepared statements, it makes no sense to test # BLOB data with DB2 or Firebird, because the length of a statement diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb index 3652255c38..bfd4c2afdf 100644 --- a/activerecord/test/cases/bind_parameter_test.rb +++ b/activerecord/test/cases/bind_parameter_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require File.expand_path('../helper', __FILE__) require 'models/topic' module ActiveRecord diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 56f6d795b6..cedd5c3d41 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/company' require 'models/topic' require 'models/edge' diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb index 7f4d25790b..c2b43438fc 100644 --- a/activerecord/test/cases/callbacks_test.rb +++ b/activerecord/test/cases/callbacks_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) class CallbackDeveloper < ActiveRecord::Base set_table_name 'developers' diff --git a/activerecord/test/cases/clone_test.rb b/activerecord/test/cases/clone_test.rb index d91646efca..b25340c205 100644 --- a/activerecord/test/cases/clone_test.rb +++ b/activerecord/test/cases/clone_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/topic' module ActiveRecord diff --git a/activerecord/test/cases/coders/yaml_column_test.rb b/activerecord/test/cases/coders/yaml_column_test.rb index c7dcc21809..55aba713e8 100644 --- a/activerecord/test/cases/coders/yaml_column_test.rb +++ b/activerecord/test/cases/coders/yaml_column_test.rb @@ -1,5 +1,4 @@ - -require "cases/helper" +require File.expand_path('../../helper', __FILE__) module ActiveRecord module Coders diff --git a/activerecord/test/cases/column_alias_test.rb b/activerecord/test/cases/column_alias_test.rb index 40707d9cb2..1b6ac870e4 100644 --- a/activerecord/test/cases/column_alias_test.rb +++ b/activerecord/test/cases/column_alias_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/topic' class TestColumnAlias < ActiveRecord::TestCase diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb index d1dddd4c2c..4d046eb9ba 100644 --- a/activerecord/test/cases/column_definition_test.rb +++ b/activerecord/test/cases/column_definition_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) module ActiveRecord module ConnectionAdapters diff --git a/activerecord/test/cases/connection_adapters/connection_handler_test.rb b/activerecord/test/cases/connection_adapters/connection_handler_test.rb index abf317768f..0bf33f86cf 100644 --- a/activerecord/test/cases/connection_adapters/connection_handler_test.rb +++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) module ActiveRecord module ConnectionAdapters diff --git a/activerecord/test/cases/connection_management_test.rb b/activerecord/test/cases/connection_management_test.rb index 85871aebdf..2b2deb6732 100644 --- a/activerecord/test/cases/connection_management_test.rb +++ b/activerecord/test/cases/connection_management_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) module ActiveRecord module ConnectionAdapters diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb index f92f4e62c5..7aa765dc4f 100644 --- a/activerecord/test/cases/connection_pool_test.rb +++ b/activerecord/test/cases/connection_pool_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) module ActiveRecord module ConnectionAdapters diff --git a/activerecord/test/cases/counter_cache_test.rb b/activerecord/test/cases/counter_cache_test.rb index 3ed96a3ec8..31faef5f0f 100644 --- a/activerecord/test/cases/counter_cache_test.rb +++ b/activerecord/test/cases/counter_cache_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require File.expand_path('../helper', __FILE__) require 'models/topic' require 'models/car' require 'models/wheel' diff --git a/activerecord/test/cases/custom_locking_test.rb b/activerecord/test/cases/custom_locking_test.rb index d63ecdbcc5..1d4385eac0 100644 --- a/activerecord/test/cases/custom_locking_test.rb +++ b/activerecord/test/cases/custom_locking_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/person' module ActiveRecord diff --git a/activerecord/test/cases/database_statements_test.rb b/activerecord/test/cases/database_statements_test.rb index c689e97d83..8fa2c9ca44 100644 --- a/activerecord/test/cases/database_statements_test.rb +++ b/activerecord/test/cases/database_statements_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) class DatabaseStatementsTest < ActiveRecord::TestCase def setup diff --git a/activerecord/test/cases/date_time_test.rb b/activerecord/test/cases/date_time_test.rb index 3deb0dac99..a9e477bd76 100644 --- a/activerecord/test/cases/date_time_test.rb +++ b/activerecord/test/cases/date_time_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/topic' require 'models/task' diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb index b3a281d960..8cf008871b 100644 --- a/activerecord/test/cases/defaults_test.rb +++ b/activerecord/test/cases/defaults_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'active_support/core_ext/object/inclusion' require 'models/default' require 'models/entrant' diff --git a/activerecord/test/cases/deprecated_finder_test.rb b/activerecord/test/cases/deprecated_finder_test.rb index 2afc91b769..1819bfc5ca 100644 --- a/activerecord/test/cases/deprecated_finder_test.rb +++ b/activerecord/test/cases/deprecated_finder_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/entrant' class DeprecatedFinderTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb index b1ce846218..7d58781eca 100644 --- a/activerecord/test/cases/dirty_test.rb +++ b/activerecord/test/cases/dirty_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require File.expand_path('../helper', __FILE__) require 'models/topic' # For booleans require 'models/pirate' # For timestamps require 'models/parrot' diff --git a/activerecord/test/cases/dup_test.rb b/activerecord/test/cases/dup_test.rb index 0236f9b0a1..9acf5fdd32 100644 --- a/activerecord/test/cases/dup_test.rb +++ b/activerecord/test/cases/dup_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/topic' module ActiveRecord diff --git a/activerecord/test/cases/dynamic_finder_match_test.rb b/activerecord/test/cases/dynamic_finder_match_test.rb index e576870317..693a8e2180 100644 --- a/activerecord/test/cases/dynamic_finder_match_test.rb +++ b/activerecord/test/cases/dynamic_finder_match_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) module ActiveRecord class DynamicFinderMatchTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/finder_respond_to_test.rb b/activerecord/test/cases/finder_respond_to_test.rb index 235805a67c..7952e9a46a 100644 --- a/activerecord/test/cases/finder_respond_to_test.rb +++ b/activerecord/test/cases/finder_respond_to_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/topic' class FinderRespondToTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 4e75eafe3d..3920f306f9 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/post' require 'models/author' require 'models/categorization' diff --git a/activerecord/test/cases/fixtures/file_test.rb b/activerecord/test/cases/fixtures/file_test.rb index 8dbf92ae9a..9ff4455394 100644 --- a/activerecord/test/cases/fixtures/file_test.rb +++ b/activerecord/test/cases/fixtures/file_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'tempfile' module ActiveRecord diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 306b437fb3..e645a9a47c 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/post' require 'models/binary' require 'models/topic' diff --git a/activerecord/test/cases/habtm_destroy_order_test.rb b/activerecord/test/cases/habtm_destroy_order_test.rb index f2b91d977e..776ed3f517 100644 --- a/activerecord/test/cases/habtm_destroy_order_test.rb +++ b/activerecord/test/cases/habtm_destroy_order_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require "models/lesson" require "models/student" diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index fbb4ee6f7b..7a214fa75a 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -1,5 +1,8 @@ require File.expand_path('../../../../load_paths', __FILE__) +test = File.expand_path('../..', __FILE__) +$:.unshift(test) unless $:.include?('test') || $:.include?(test) + lib = File.expand_path("#{File.dirname(__FILE__)}/../../lib") $:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) @@ -11,14 +14,13 @@ require 'mocha' require 'active_record' require 'active_support/dependencies' -begin - require 'connection' -rescue LoadError - # If we cannot load connection we assume that driver was not loaded for this test case, so we load sqlite3 as default one. - # This allows for running separate test cases by simply running test file. - connection_type = defined?(JRUBY_VERSION) ? 'jdbc' : 'native' - require "test/connections/#{connection_type}_sqlite3/connection" -end + +require 'support/config' +require 'support/connection' + +ARTest.connect + +# TODO: Move all these random hacks into the ARTest namespace and into the support/ dir # Show backtraces for deprecated behavior for quicker cleanup. ActiveSupport::Deprecation.debug = true @@ -26,8 +28,8 @@ ActiveSupport::Deprecation.debug = true # Quote "type" if it's a reserved word for the current connection. QUOTED_TYPE = ActiveRecord::Base.connection.quote_column_name('type') -# Enable Identity Map for testing -ActiveRecord::IdentityMap.enabled = (ENV['IM'] == "false" ? false : true) +# Enable Identity Map only when ENV['IM'] is set to "true" +ActiveRecord::IdentityMap.enabled = (ENV['IM'] == "true") def current_adapter?(*types) types.any? do |type| diff --git a/activerecord/test/cases/i18n_test.rb b/activerecord/test/cases/i18n_test.rb index 469f513e68..d96dc5fba9 100644 --- a/activerecord/test/cases/i18n_test.rb +++ b/activerecord/test/cases/i18n_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/topic' require 'models/reply' @@ -43,4 +43,3 @@ class ActiveRecordI18nTests < ActiveRecord::TestCase assert_equal 'topic model', Reply.model_name.human end end - diff --git a/activerecord/test/cases/identity_map/middleware_test.rb b/activerecord/test/cases/identity_map/middleware_test.rb index 60dcad4586..047192c244 100644 --- a/activerecord/test/cases/identity_map/middleware_test.rb +++ b/activerecord/test/cases/identity_map/middleware_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) module ActiveRecord module IdentityMap diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index a0e16400d2..d814f1cc92 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -1,5 +1,4 @@ -require "cases/helper" - +require File.expand_path('../helper', __FILE__) require 'models/developer' require 'models/project' require 'models/company' @@ -140,7 +139,7 @@ class IdentityMapTest < ActiveRecord::TestCase assert_not_same(p1, p2) end end - + def test_inherited_with_type_attribute_without_identity_map ActiveRecord::IdentityMap.without do c = comments(:sub_special_comment) diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb index b5d8314541..5bfc572ea8 100644 --- a/activerecord/test/cases/inheritance_test.rb +++ b/activerecord/test/cases/inheritance_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/company' require 'models/project' require 'models/subscriber' diff --git a/activerecord/test/cases/invalid_date_test.rb b/activerecord/test/cases/invalid_date_test.rb index 2de50b224c..65d326bc12 100644 --- a/activerecord/test/cases/invalid_date_test.rb +++ b/activerecord/test/cases/invalid_date_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require File.expand_path('../helper', __FILE__) require 'models/topic' class InvalidDateTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/invertible_migration_test.rb b/activerecord/test/cases/invertible_migration_test.rb index afec64750e..d145ff7427 100644 --- a/activerecord/test/cases/invertible_migration_test.rb +++ b/activerecord/test/cases/invertible_migration_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) module ActiveRecord class InvertibleMigrationTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/json_serialization_test.rb b/activerecord/test/cases/json_serialization_test.rb index 8664d63e8f..aef7403a09 100644 --- a/activerecord/test/cases/json_serialization_test.rb +++ b/activerecord/test/cases/json_serialization_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/contact' require 'models/post' require 'models/author' @@ -161,6 +161,15 @@ class DatabaseConnectedJsonEncodingTest < ActiveRecord::TestCase assert_match %r{"tag":\{"name":"General"\}}, json end + def test_includes_doesnt_merge_opts_from_base + json = @david.to_json( + :only => :id, + :include => :posts + ) + + assert_match %{"title":"Welcome to the weblog"}, json + end + def test_should_not_call_methods_on_associations_that_dont_respond def @david.favorite_quote; "Constraints are liberating"; end json = @david.to_json(:include => :posts, :methods => :favorite_quote) diff --git a/activerecord/test/cases/lifecycle_test.rb b/activerecord/test/cases/lifecycle_test.rb index 643e949087..7d47f7e21b 100644 --- a/activerecord/test/cases/lifecycle_test.rb +++ b/activerecord/test/cases/lifecycle_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require File.expand_path('../helper', __FILE__) require 'models/topic' require 'models/developer' require 'models/reply' diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index 61baa55027..88861df86a 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -1,5 +1,5 @@ require 'thread' -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/person' require 'models/job' require 'models/reader' diff --git a/activerecord/test/cases/log_subscriber_test.rb b/activerecord/test/cases/log_subscriber_test.rb index c6c6079490..f29ced4526 100644 --- a/activerecord/test/cases/log_subscriber_test.rb +++ b/activerecord/test/cases/log_subscriber_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require "models/developer" require "models/post" require "active_support/log_subscriber/test_helper" diff --git a/activerecord/test/cases/mass_assignment_security_test.rb b/activerecord/test/cases/mass_assignment_security_test.rb index 33737e12a8..a41ce539c7 100644 --- a/activerecord/test/cases/mass_assignment_security_test.rb +++ b/activerecord/test/cases/mass_assignment_security_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/company' require 'models/subscriber' require 'models/keyboard' diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb index a0cb5dbdc5..52e76cb91a 100644 --- a/activerecord/test/cases/method_scoping_test.rb +++ b/activerecord/test/cases/method_scoping_test.rb @@ -2,7 +2,7 @@ # All the tests were already ported to relation_scoping_test.rb when the new # relation scoping API was added. -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/post' require 'models/author' require 'models/developer' diff --git a/activerecord/test/cases/migration/command_recorder_test.rb b/activerecord/test/cases/migration/command_recorder_test.rb index ae531ebb4c..986dc7173d 100644 --- a/activerecord/test/cases/migration/command_recorder_test.rb +++ b/activerecord/test/cases/migration/command_recorder_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) module ActiveRecord class Migration @@ -86,6 +86,18 @@ module ActiveRecord assert_equal [:remove_index, [:table, {:column => [:one, :two]}]], remove end + def test_invert_add_index_with_name + @recorder.record :add_index, [:table, [:one, :two], {:name => "new_index"}] + remove = @recorder.inverse.first + assert_equal [:remove_index, [:table, {:name => "new_index"}]], remove + end + + def test_invert_add_index_with_no_options + @recorder.record :add_index, [:table, [:one, :two]] + remove = @recorder.inverse.first + assert_equal [:remove_index, [:table, {:column => [:one, :two]}]], remove + end + def test_invert_rename_index @recorder.record :rename_index, [:old, :new] rename = @recorder.inverse.first diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index bf7565a0d0..01f7575653 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'bigdecimal/util' require 'models/person' diff --git a/activerecord/test/cases/mixin_test.rb b/activerecord/test/cases/mixin_test.rb index f927c13979..65101199b8 100644 --- a/activerecord/test/cases/mixin_test.rb +++ b/activerecord/test/cases/mixin_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) class Mixin < ActiveRecord::Base end diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb index a2041af16a..df5e66ea3c 100644 --- a/activerecord/test/cases/modules_test.rb +++ b/activerecord/test/cases/modules_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/company_in_module' require 'models/shop' diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb index bd51388e05..fca832e50b 100644 --- a/activerecord/test/cases/multiple_db_test.rb +++ b/activerecord/test/cases/multiple_db_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/entrant' require 'models/bird' diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index 34188e4915..2403645940 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'active_support/core_ext/array/random_access' require 'models/post' require 'models/topic' @@ -456,6 +456,14 @@ class NamedScopeTest < ActiveRecord::TestCase end end + def test_scopes_to_get_newest + post = posts(:welcome) + old_last_comment = post.comments.newest + new_comment = post.comments.create(:body => "My new comment") + assert_equal new_comment, post.comments.newest + assert_not_equal old_last_comment, post.comments.newest + end + def test_scopes_are_reset_on_association_reload post = posts(:welcome) diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index 6568eb1d18..d94d4768a9 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require "models/pirate" require "models/ship" require "models/ship_part" diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb index 57d1441128..00543f7350 100644 --- a/activerecord/test/cases/persistence_test.rb +++ b/activerecord/test/cases/persistence_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/post' require 'models/comment' require 'models/author' diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index 379cf5b44e..0321c5208f 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require "models/project" require "timeout" diff --git a/activerecord/test/cases/primary_keys_test.rb b/activerecord/test/cases/primary_keys_test.rb index 05a41d8a0a..e810a155a0 100644 --- a/activerecord/test/cases/primary_keys_test.rb +++ b/activerecord/test/cases/primary_keys_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/topic' require 'models/reply' require 'models/subscriber' diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb index a61180cfaf..b08443b455 100644 --- a/activerecord/test/cases/query_cache_test.rb +++ b/activerecord/test/cases/query_cache_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/topic' require 'models/task' require 'models/category' diff --git a/activerecord/test/cases/quoting_test.rb b/activerecord/test/cases/quoting_test.rb index 80ee74e41e..4cb38118c9 100644 --- a/activerecord/test/cases/quoting_test.rb +++ b/activerecord/test/cases/quoting_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) module ActiveRecord module ConnectionAdapters diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb index e21109baae..88168776b1 100644 --- a/activerecord/test/cases/readonly_test.rb +++ b/activerecord/test/cases/readonly_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/post' require 'models/comment' require 'models/developer' diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 58c78ab058..c7288baaba 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/topic' require 'models/customer' require 'models/company' diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb index 8f8e72f052..5067384fb6 100644 --- a/activerecord/test/cases/relation_scoping_test.rb +++ b/activerecord/test/cases/relation_scoping_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/post' require 'models/author' require 'models/developer' @@ -11,6 +11,14 @@ require 'models/reference' class RelationScopingTest < ActiveRecord::TestCase fixtures :authors, :developers, :projects, :comments, :posts, :developers_projects + def test_reverse_order + assert_equal Developer.order("id DESC").to_a.reverse, Developer.order("id DESC").reverse_order + end + + def test_double_reverse_order_produces_original_order + assert_equal Developer.order("name DESC"), Developer.order("name DESC").reverse_order.reverse_order + end + def test_scoped_find Developer.where("name = 'David'").scoping do assert_nothing_raised { Developer.find(1) } @@ -471,7 +479,23 @@ class DefaultScopingTest < ActiveRecord::TestCase assert_equal 10, DeveloperCalledJamis.unscoped.poor.length end + def test_default_scope_select_ignored_by_aggregations + assert_equal DeveloperWithSelect.all.count, DeveloperWithSelect.count + end + + def test_default_scope_select_ignored_by_grouped_aggregations + assert_equal Hash[Developer.all.group_by(&:salary).map { |s, d| [s, d.count] }], + DeveloperWithSelect.group(:salary).count + end + def test_default_scope_order_ignored_by_aggregations assert_equal DeveloperOrderedBySalary.all.count, DeveloperOrderedBySalary.count end + + def test_default_scope_find_last + assert DeveloperOrderedBySalary.count > 1, "need more than one row for test" + + lowest_salary_dev = DeveloperOrderedBySalary.find(developers(:poor_jamis).id) + assert_equal lowest_salary_dev, DeveloperOrderedBySalary.last + end end diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb index 6874bd18f8..5ad089c875 100644 --- a/activerecord/test/cases/relation_test.rb +++ b/activerecord/test/cases/relation_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/post' require 'models/comment' @@ -20,7 +20,7 @@ module ActiveRecord end def test_single_values - assert_equal [:limit, :offset, :lock, :readonly, :create_with, :from, :reorder].map(&:to_s).sort, + assert_equal [:limit, :offset, :lock, :readonly, :create_with, :from, :reorder, :reverse_order].map(&:to_s).sort, Relation::SINGLE_VALUE_METHODS.map(&:to_s).sort end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index fc9df8c7a3..ecc68b19d4 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/tag' require 'models/tagging' require 'models/post' diff --git a/activerecord/test/cases/reload_models_test.rb b/activerecord/test/cases/reload_models_test.rb index 0d16a3526f..0ac46a2768 100644 --- a/activerecord/test/cases/reload_models_test.rb +++ b/activerecord/test/cases/reload_models_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/owner' require 'models/pet' diff --git a/activerecord/test/cases/sanitize_test.rb b/activerecord/test/cases/sanitize_test.rb index 817897ceac..7c30bcf4c8 100644 --- a/activerecord/test/cases/sanitize_test.rb +++ b/activerecord/test/cases/sanitize_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/binary' class SanitizeTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index e8f2f44189..e765fdfe70 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'stringio' @@ -230,4 +230,3 @@ class SchemaDumperTest < ActiveRecord::TestCase assert_match %r{t.string[[:space:]]+"id",[[:space:]]+:null => false$}, match[2], "non-primary key id column not preserved" end end - diff --git a/activerecord/test/cases/serialization_test.rb b/activerecord/test/cases/serialization_test.rb index 677d659f39..9c976f4999 100644 --- a/activerecord/test/cases/serialization_test.rb +++ b/activerecord/test/cases/serialization_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/contact' require 'models/topic' require 'models/reply' diff --git a/activerecord/test/cases/session_store/session_test.rb b/activerecord/test/cases/session_store/session_test.rb index 669c0b7b4d..fb6f4cfd44 100644 --- a/activerecord/test/cases/session_store/session_test.rb +++ b/activerecord/test/cases/session_store/session_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require File.expand_path('../../helper', __FILE__) require 'action_dispatch' require 'active_record/session_store' diff --git a/activerecord/test/cases/session_store/sql_bypass.rb b/activerecord/test/cases/session_store/sql_bypass.rb index 7402b2afd6..97ccb1f5c9 100644 --- a/activerecord/test/cases/session_store/sql_bypass.rb +++ b/activerecord/test/cases/session_store/sql_bypass.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require File.expand_path('../../helper', __FILE__) require 'action_dispatch' require 'active_record/session_store' diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index 22d4cac422..ce6419c0da 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -1,4 +1,4 @@ -require 'cases/helper' +require File.expand_path('../helper', __FILE__) require 'models/developer' require 'models/owner' require 'models/pet' @@ -14,32 +14,6 @@ class TimestampTest < ActiveRecord::TestCase @previously_updated_at = @developer.updated_at end - def test_load_infinity_and_beyond - unless current_adapter?(:PostgreSQLAdapter) - return skip("only tested on postgresql") - end - - d = Developer.find_by_sql("select 'infinity'::timestamp as updated_at") - assert d.first.updated_at.infinite?, 'timestamp should be infinite' - - d = Developer.find_by_sql("select '-infinity'::timestamp as updated_at") - time = d.first.updated_at - assert time.infinite?, 'timestamp should be infinite' - assert_operator time, :<, 0 - end - - def test_save_infinity_and_beyond - unless current_adapter?(:PostgreSQLAdapter) - return skip("only tested on postgresql") - end - - d = Developer.create!(:name => 'aaron', :updated_at => 1.0 / 0.0) - assert_equal(1.0 / 0.0, d.updated_at) - - d = Developer.create!(:name => 'aaron', :updated_at => -1.0 / 0.0) - assert_equal(-1.0 / 0.0, d.updated_at) - end - def test_saving_a_changed_record_updates_its_timestamp @developer.name = "Jack Bauer" @developer.save! diff --git a/activerecord/test/cases/transaction_callbacks_test.rb b/activerecord/test/cases/transaction_callbacks_test.rb index 85f222bca2..2d88e660b3 100644 --- a/activerecord/test/cases/transaction_callbacks_test.rb +++ b/activerecord/test/cases/transaction_callbacks_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/topic' class TransactionCallbacksTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index 110a18772f..fa33ffaed3 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/topic' require 'models/reply' require 'models/developer' diff --git a/activerecord/test/cases/unconnected_test.rb b/activerecord/test/cases/unconnected_test.rb index f85fb4e5da..a6aaf1eb3d 100644 --- a/activerecord/test/cases/unconnected_test.rb +++ b/activerecord/test/cases/unconnected_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) class TestRecord < ActiveRecord::Base end diff --git a/activerecord/test/cases/validations/association_validation_test.rb b/activerecord/test/cases/validations/association_validation_test.rb index 56e345990f..45290680f9 100644 --- a/activerecord/test/cases/validations/association_validation_test.rb +++ b/activerecord/test/cases/validations/association_validation_test.rb @@ -1,5 +1,5 @@ # encoding: utf-8 -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/topic' require 'models/reply' require 'models/owner' diff --git a/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb b/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb index 628029f8df..922fb5dce7 100644 --- a/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb +++ b/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/topic' class I18nGenerateMessageValidationTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/validations/i18n_validation_test.rb b/activerecord/test/cases/validations/i18n_validation_test.rb index 15b97c02c8..46f0c3c49d 100644 --- a/activerecord/test/cases/validations/i18n_validation_test.rb +++ b/activerecord/test/cases/validations/i18n_validation_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/topic' require 'models/reply' diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb index 0f1b3667cc..218f673451 100644 --- a/activerecord/test/cases/validations/uniqueness_validation_test.rb +++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb @@ -1,5 +1,5 @@ # encoding: utf-8 -require "cases/helper" +require File.expand_path('../../helper', __FILE__) require 'models/topic' require 'models/reply' require 'models/warehouse_thing' diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb index c3e494866b..8764a22d40 100644 --- a/activerecord/test/cases/validations_test.rb +++ b/activerecord/test/cases/validations_test.rb @@ -1,5 +1,5 @@ # encoding: utf-8 -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/topic' require 'models/reply' require 'models/person' diff --git a/activerecord/test/cases/xml_serialization_test.rb b/activerecord/test/cases/xml_serialization_test.rb index 756c8a32eb..c48957e7a7 100644 --- a/activerecord/test/cases/xml_serialization_test.rb +++ b/activerecord/test/cases/xml_serialization_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/contact' require 'models/post' require 'models/author' diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb index 0b54c309d1..6caa782a97 100644 --- a/activerecord/test/cases/yaml_serialization_test.rb +++ b/activerecord/test/cases/yaml_serialization_test.rb @@ -1,4 +1,4 @@ -require "cases/helper" +require File.expand_path('../helper', __FILE__) require 'models/topic' class YamlSerializationTest < ActiveRecord::TestCase diff --git a/activerecord/test/config.example.yml b/activerecord/test/config.example.yml new file mode 100644 index 0000000000..6ed38db66d --- /dev/null +++ b/activerecord/test/config.example.yml @@ -0,0 +1,136 @@ +default_connection: <%= defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3' %> + +connections: + jdbcderby: + arunit: activerecord_unittest + arunit2: activerecord_unittest2 + + jdbch2: + arunit: activerecord_unittest + arunit2: activerecord_unittest2 + + jdbchsqldb: + arunit: activerecord_unittest + arunit2: activerecord_unittest2 + + jdbcmysql: + arunit: + username: rails + encoding: utf8 + arunit2: + username: rails + encoding: utf8 + + jdbcpostgresql: + arunit: + username: <%= ENV['user'] || 'rails' %> + arunit2: + username: <%= ENV['user'] || 'rails' %> + + jdbcsqlite3: + arunit: + database: <%= FIXTURES_ROOT %>/fixture_database.sqlite3 + timeout: 5000 + arunit2: + database: <%= FIXTURES_ROOT %>/fixture_database_2.sqlite3 + timeout: 5000 + + db2: + arunit: + host: localhost + username: arunit + password: arunit + database: arunit + arunit2: + host: localhost + username: arunit + password: arunit + database: arunit2 + + firebird: + arunit: + host: localhost + username: rails + password: rails + charset: UTF8 + arunit2: + host: localhost + username: rails + password: rails + charset: UTF8 + + frontbase: + arunit: + host: localhost + username: rails + session_name: unittest-<%= $$ %> + arunit2: + host: localhost + username: rails + session_name: unittest-<%= $$ %> + + mysql: + arunit: + username: rails + encoding: utf8 + arunit2: + username: rails + encoding: utf8 + + mysql2: + arunit: + username: rails + encoding: utf8 + arunit2: + username: rails + encoding: utf8 + + openbase: + arunit: + username: admin + arunit2: + username: admin + + oracle: + arunit: + adapter: oracle_enhanced + database: <%= ENV['ARUNIT_DB_NAME'] || 'orcl' %> + username: arunit + password: arunit + emulate_oracle_adapter: true + arunit: + adapter: oracle_enhanced + database: <%= ENV['ARUNIT_DB_NAME'] || 'orcl' %> + username: arunit2 + password: arunit2 + emulate_oracle_adapter: true + + postgresql: + arunit: + min_messages: warning + arunit2: + min_messages: warning + + sqlite3: + arunit: + database: <%= FIXTURES_ROOT %>/fixture_database.sqlite3 + timeout: 5000 + arunit2: + database: <%= FIXTURES_ROOT %>/fixture_database_2.sqlite3 + timeout: 5000 + + sqlite3_mem: + arunit: + adapter: sqlite3 + database: ':memory:' + arunit2: + adapter: sqlite3 + database: ':memory:' + + sybase: + arunit: + host: database_ASE + username: sa + arunit2: + host: database_ASE + username: sa diff --git a/activerecord/test/connections/db2.rb b/activerecord/test/connections/db2.rb new file mode 100644 index 0000000000..f43b3fda57 --- /dev/null +++ b/activerecord/test/connections/db2.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'db2' diff --git a/activerecord/test/connections/firebird.rb b/activerecord/test/connections/firebird.rb new file mode 100644 index 0000000000..fa874c0bb3 --- /dev/null +++ b/activerecord/test/connections/firebird.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'firebird' diff --git a/activerecord/test/connections/frontbase.rb b/activerecord/test/connections/frontbase.rb new file mode 100644 index 0000000000..9d1d5597d4 --- /dev/null +++ b/activerecord/test/connections/frontbase.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'frontbase' diff --git a/activerecord/test/connections/jdbc_jdbcderby/connection.rb b/activerecord/test/connections/jdbc_jdbcderby/connection.rb deleted file mode 100644 index 222ef5db38..0000000000 --- a/activerecord/test/connections/jdbc_jdbcderby/connection.rb +++ /dev/null @@ -1,18 +0,0 @@ -print "Using Derby via JRuby, activerecord-jdbc-adapter and activerecord-jdbcderby-adapter\n" -require_dependency 'models/course' -require 'logger' -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'jdbcderby', - :database => 'activerecord_unittest' - }, - 'arunit2' => { - :adapter => 'jdbcderby', - :database => 'activerecord_unittest2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' diff --git a/activerecord/test/connections/jdbc_jdbch2/connection.rb b/activerecord/test/connections/jdbc_jdbch2/connection.rb deleted file mode 100644 index 9d2875e8e7..0000000000 --- a/activerecord/test/connections/jdbc_jdbch2/connection.rb +++ /dev/null @@ -1,18 +0,0 @@ -print "Using H2 via JRuby, activerecord-jdbc-adapter and activerecord-jdbch2-adapter\n" -require_dependency 'models/course' -require 'logger' -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'jdbch2', - :database => 'activerecord_unittest' - }, - 'arunit2' => { - :adapter => 'jdbch2', - :database => 'activerecord_unittest2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' diff --git a/activerecord/test/connections/jdbc_jdbchsqldb/connection.rb b/activerecord/test/connections/jdbc_jdbchsqldb/connection.rb deleted file mode 100644 index fa943c2c76..0000000000 --- a/activerecord/test/connections/jdbc_jdbchsqldb/connection.rb +++ /dev/null @@ -1,18 +0,0 @@ -print "Using HSQLDB via JRuby, activerecord-jdbc-adapter and activerecord-jdbchsqldb-adapter\n" -require_dependency 'models/course' -require 'logger' -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'jdbchsqldb', - :database => 'activerecord_unittest' - }, - 'arunit2' => { - :adapter => 'jdbchsqldb', - :database => 'activerecord_unittest2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' diff --git a/activerecord/test/connections/jdbc_jdbcmysql/connection.rb b/activerecord/test/connections/jdbc_jdbcmysql/connection.rb deleted file mode 100644 index e2517a50eb..0000000000 --- a/activerecord/test/connections/jdbc_jdbcmysql/connection.rb +++ /dev/null @@ -1,26 +0,0 @@ -print "Using MySQL via JRuby, activerecord-jdbc-adapter and activerecord-jdbcmysql-adapter\n" -require_dependency 'models/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -# GRANT ALL PRIVILEGES ON activerecord_unittest.* to 'rails'@'localhost'; -# GRANT ALL PRIVILEGES ON activerecord_unittest2.* to 'rails'@'localhost'; - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'jdbcmysql', - :username => 'rails', - :encoding => 'utf8', - :database => 'activerecord_unittest', - }, - 'arunit2' => { - :adapter => 'jdbcmysql', - :username => 'rails', - :database => 'activerecord_unittest2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' - diff --git a/activerecord/test/connections/jdbc_jdbcpostgresql/connection.rb b/activerecord/test/connections/jdbc_jdbcpostgresql/connection.rb deleted file mode 100644 index 0685da4433..0000000000 --- a/activerecord/test/connections/jdbc_jdbcpostgresql/connection.rb +++ /dev/null @@ -1,26 +0,0 @@ -print "Using Postgrsql via JRuby, activerecord-jdbc-adapter and activerecord-postgresql-adapter\n" -require_dependency 'models/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -# createuser rails --createdb --no-superuser --no-createrole -# createdb -O rails activerecord_unittest -# createdb -O rails activerecord_unittest2 - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'jdbcpostgresql', - :username => ENV['USER'] || 'rails', - :database => 'activerecord_unittest' - }, - 'arunit2' => { - :adapter => 'jdbcpostgresql', - :username => ENV['USER'] || 'rails', - :database => 'activerecord_unittest2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' - diff --git a/activerecord/test/connections/jdbc_jdbcsqlite3/connection.rb b/activerecord/test/connections/jdbc_jdbcsqlite3/connection.rb deleted file mode 100644 index 26d4676ff3..0000000000 --- a/activerecord/test/connections/jdbc_jdbcsqlite3/connection.rb +++ /dev/null @@ -1,25 +0,0 @@ -print "Using SQLite3 via JRuby, activerecord-jdbc-adapter and activerecord-jdbcsqlite3-adapter\n" -require_dependency 'models/course' -require 'logger' -ActiveRecord::Base.logger = Logger.new("debug.log") - -class SqliteError < StandardError -end - -BASE_DIR = FIXTURES_ROOT -sqlite_test_db = "#{BASE_DIR}/fixture_database.sqlite3" -sqlite_test_db2 = "#{BASE_DIR}/fixture_database_2.sqlite3" - -def make_connection(clazz, db_file) - ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'jdbcsqlite3', :database => db_file, :timeout => 5000 } } - unless File.exist?(db_file) - puts "SQLite3 database not found at #{db_file}. Rebuilding it." - sqlite_command = %Q{sqlite3 "#{db_file}" "create table a (a integer); drop table a;"} - puts "Executing '#{sqlite_command}'" - raise SqliteError.new("Seems that there is no sqlite3 executable available") unless system(sqlite_command) - end - clazz.establish_connection(clazz.name) -end - -make_connection(ActiveRecord::Base, sqlite_test_db) -make_connection(Course, sqlite_test_db2) diff --git a/activerecord/test/connections/jdbcderby.rb b/activerecord/test/connections/jdbcderby.rb new file mode 100644 index 0000000000..1c7b63ccdc --- /dev/null +++ b/activerecord/test/connections/jdbcderby.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'jdbcderby' diff --git a/activerecord/test/connections/jdbch2.rb b/activerecord/test/connections/jdbch2.rb new file mode 100644 index 0000000000..d2fb177ae3 --- /dev/null +++ b/activerecord/test/connections/jdbch2.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'jdbch2' diff --git a/activerecord/test/connections/jdbchsqldb.rb b/activerecord/test/connections/jdbchsqldb.rb new file mode 100644 index 0000000000..22e6d8729e --- /dev/null +++ b/activerecord/test/connections/jdbchsqldb.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'jdbchsqldb' diff --git a/activerecord/test/connections/jdbcmysql.rb b/activerecord/test/connections/jdbcmysql.rb new file mode 100644 index 0000000000..f1aaad93a3 --- /dev/null +++ b/activerecord/test/connections/jdbcmysql.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'jdbcmysql' diff --git a/activerecord/test/connections/jdbcpostgresql.rb b/activerecord/test/connections/jdbcpostgresql.rb new file mode 100644 index 0000000000..6809115f36 --- /dev/null +++ b/activerecord/test/connections/jdbcpostgresql.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'jdbcpostgresql' diff --git a/activerecord/test/connections/jdbcsqlite3.rb b/activerecord/test/connections/jdbcsqlite3.rb new file mode 100644 index 0000000000..9cc872905a --- /dev/null +++ b/activerecord/test/connections/jdbcsqlite3.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'jdbcsqlite3' diff --git a/activerecord/test/connections/mysql.rb b/activerecord/test/connections/mysql.rb new file mode 100644 index 0000000000..2f30603098 --- /dev/null +++ b/activerecord/test/connections/mysql.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'mysql' diff --git a/activerecord/test/connections/mysql2.rb b/activerecord/test/connections/mysql2.rb new file mode 100644 index 0000000000..10aa9171bd --- /dev/null +++ b/activerecord/test/connections/mysql2.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'mysql2' diff --git a/activerecord/test/connections/native_db2/connection.rb b/activerecord/test/connections/native_db2/connection.rb deleted file mode 100644 index 324315d2c8..0000000000 --- a/activerecord/test/connections/native_db2/connection.rb +++ /dev/null @@ -1,25 +0,0 @@ -print "Using native DB2\n" -require_dependency 'models/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'db2', - :host => 'localhost', - :username => 'arunit', - :password => 'arunit', - :database => 'arunit' - }, - 'arunit2' => { - :adapter => 'db2', - :host => 'localhost', - :username => 'arunit', - :password => 'arunit', - :database => 'arunit2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' diff --git a/activerecord/test/connections/native_firebird/connection.rb b/activerecord/test/connections/native_firebird/connection.rb deleted file mode 100644 index 67a936ca97..0000000000 --- a/activerecord/test/connections/native_firebird/connection.rb +++ /dev/null @@ -1,26 +0,0 @@ -print "Using native Firebird\n" -require_dependency 'models/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'firebird', - :host => 'localhost', - :username => 'rails', - :password => 'rails', - :database => 'activerecord_unittest', - :charset => 'UTF8' - }, - 'arunit2' => { - :adapter => 'firebird', - :host => 'localhost', - :username => 'rails', - :password => 'rails', - :database => 'activerecord_unittest2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' diff --git a/activerecord/test/connections/native_frontbase/connection.rb b/activerecord/test/connections/native_frontbase/connection.rb deleted file mode 100644 index c01d864a8b..0000000000 --- a/activerecord/test/connections/native_frontbase/connection.rb +++ /dev/null @@ -1,27 +0,0 @@ -puts 'Using native Frontbase' -require_dependency 'models/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'frontbase', - :host => 'localhost', - :username => 'rails', - :password => '', - :database => 'activerecord_unittest', - :session_name => "unittest-#{$$}" - }, - 'arunit2' => { - :adapter => 'frontbase', - :host => 'localhost', - :username => 'rails', - :password => '', - :database => 'activerecord_unittest2', - :session_name => "unittest-#{$$}" - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' diff --git a/activerecord/test/connections/native_mysql/connection.rb b/activerecord/test/connections/native_mysql/connection.rb deleted file mode 100644 index 140e06d631..0000000000 --- a/activerecord/test/connections/native_mysql/connection.rb +++ /dev/null @@ -1,25 +0,0 @@ -print "Using native MySQL\n" -require_dependency 'models/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -# GRANT ALL PRIVILEGES ON activerecord_unittest.* to 'rails'@'localhost'; -# GRANT ALL PRIVILEGES ON activerecord_unittest2.* to 'rails'@'localhost'; - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'mysql', - :username => 'rails', - :encoding => 'utf8', - :database => 'activerecord_unittest', - }, - 'arunit2' => { - :adapter => 'mysql', - :username => 'rails', - :database => 'activerecord_unittest2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' diff --git a/activerecord/test/connections/native_mysql2/connection.rb b/activerecord/test/connections/native_mysql2/connection.rb deleted file mode 100644 index c6f198b1ac..0000000000 --- a/activerecord/test/connections/native_mysql2/connection.rb +++ /dev/null @@ -1,25 +0,0 @@ -print "Using native Mysql2\n" -require_dependency 'models/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -# GRANT ALL PRIVILEGES ON activerecord_unittest.* to 'rails'@'localhost'; -# GRANT ALL PRIVILEGES ON activerecord_unittest2.* to 'rails'@'localhost'; - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'mysql2', - :username => 'rails', - :encoding => 'utf8', - :database => 'activerecord_unittest', - }, - 'arunit2' => { - :adapter => 'mysql2', - :username => 'rails', - :database => 'activerecord_unittest2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' diff --git a/activerecord/test/connections/native_openbase/connection.rb b/activerecord/test/connections/native_openbase/connection.rb deleted file mode 100644 index 655cb9ca26..0000000000 --- a/activerecord/test/connections/native_openbase/connection.rb +++ /dev/null @@ -1,21 +0,0 @@ -print "Using native OpenBase\n" -require_dependency 'models/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'openbase', - :username => 'admin', - :database => 'activerecord_unittest', - }, - 'arunit2' => { - :adapter => 'openbase', - :username => 'admin', - :database => 'activerecord_unittest2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' diff --git a/activerecord/test/connections/native_oracle/connection.rb b/activerecord/test/connections/native_oracle/connection.rb deleted file mode 100644 index 99f921879c..0000000000 --- a/activerecord/test/connections/native_oracle/connection.rb +++ /dev/null @@ -1,35 +0,0 @@ -# uses oracle_enhanced adapter in ENV['ORACLE_ENHANCED_PATH'] or from github.com/rsim/oracle-enhanced.git -require 'active_record/connection_adapters/oracle_enhanced_adapter' - -# otherwise failed with silence_warnings method missing exception -require 'active_support/core_ext/kernel/reporting' - -print "Using Oracle\n" -require_dependency 'models/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -# Set these to your database connection strings -ENV['ARUNIT_DB_NAME'] ||= 'orcl' - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'oracle_enhanced', - :database => ENV['ARUNIT_DB_NAME'], - :username => 'arunit', - :password => 'arunit', - :emulate_oracle_adapter => true - }, - 'arunit2' => { - :adapter => 'oracle_enhanced', - :database => ENV['ARUNIT_DB_NAME'], - :username => 'arunit2', - :password => 'arunit2', - :emulate_oracle_adapter => true - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' - diff --git a/activerecord/test/connections/native_postgresql/connection.rb b/activerecord/test/connections/native_postgresql/connection.rb deleted file mode 100644 index 3b5ff90003..0000000000 --- a/activerecord/test/connections/native_postgresql/connection.rb +++ /dev/null @@ -1,21 +0,0 @@ -print "Using native PostgreSQL\n" -require_dependency 'models/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'postgresql', - :database => 'activerecord_unittest', - :min_messages => 'warning' - }, - 'arunit2' => { - :adapter => 'postgresql', - :database => 'activerecord_unittest2', - :min_messages => 'warning' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' diff --git a/activerecord/test/connections/native_sqlite3/connection.rb b/activerecord/test/connections/native_sqlite3/connection.rb deleted file mode 100644 index c2aff5551f..0000000000 --- a/activerecord/test/connections/native_sqlite3/connection.rb +++ /dev/null @@ -1,16 +0,0 @@ -print "Using native SQLite3\n" -require_dependency 'models/course' -require 'logger' -ActiveRecord::Base.logger = Logger.new("debug.log") - -BASE_DIR = FIXTURES_ROOT -sqlite_test_db = "#{BASE_DIR}/fixture_database.sqlite3" -sqlite_test_db2 = "#{BASE_DIR}/fixture_database_2.sqlite3" - -def make_connection(clazz, db_file) - ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'sqlite3', :database => db_file, :timeout => 5000 } } - clazz.establish_connection(clazz.name) -end - -make_connection(ActiveRecord::Base, sqlite_test_db) -make_connection(Course, sqlite_test_db2) diff --git a/activerecord/test/connections/native_sqlite3_mem/connection.rb b/activerecord/test/connections/native_sqlite3_mem/connection.rb deleted file mode 100644 index 14e10900d1..0000000000 --- a/activerecord/test/connections/native_sqlite3_mem/connection.rb +++ /dev/null @@ -1,19 +0,0 @@ -# This file connects to an in-memory SQLite3 database, which is a very fast way to run the tests. -# The downside is that disconnect from the database results in the database effectively being -# wiped. For this reason, pooled_connections_test.rb is disabled when using an in-memory database. - -print "Using native SQLite3 (in memory)\n" -require_dependency 'models/course' -require 'logger' -ActiveRecord::Base.logger = Logger.new("debug.log") - -class SqliteError < StandardError -end - -def make_connection(clazz) - ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'sqlite3', :database => ':memory:' } } - clazz.establish_connection(clazz.name) -end - -make_connection(ActiveRecord::Base) -make_connection(Course) diff --git a/activerecord/test/connections/native_sybase/connection.rb b/activerecord/test/connections/native_sybase/connection.rb deleted file mode 100644 index 3282d26922..0000000000 --- a/activerecord/test/connections/native_sybase/connection.rb +++ /dev/null @@ -1,23 +0,0 @@ -print "Using native Sybase Open Client\n" -require_dependency 'models/course' -require 'logger' - -ActiveRecord::Base.logger = Logger.new("debug.log") - -ActiveRecord::Base.configurations = { - 'arunit' => { - :adapter => 'sybase', - :host => 'database_ASE', - :username => 'sa', - :database => 'activerecord_unittest' - }, - 'arunit2' => { - :adapter => 'sybase', - :host => 'database_ASE', - :username => 'sa', - :database => 'activerecord_unittest2' - } -} - -ActiveRecord::Base.establish_connection 'arunit' -Course.establish_connection 'arunit2' diff --git a/activerecord/test/connections/openbase.rb b/activerecord/test/connections/openbase.rb new file mode 100644 index 0000000000..bf072579f4 --- /dev/null +++ b/activerecord/test/connections/openbase.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'openbase' diff --git a/activerecord/test/connections/oracle.rb b/activerecord/test/connections/oracle.rb new file mode 100644 index 0000000000..dc64f7c5fc --- /dev/null +++ b/activerecord/test/connections/oracle.rb @@ -0,0 +1,7 @@ +ENV['ARCONN'] = 'oracle' + +# uses oracle_enhanced adapter in ENV['ORACLE_ENHANCED_PATH'] or from github.com/rsim/oracle-enhanced.git +require 'active_record/connection_adapters/oracle_enhanced_adapter' + +# otherwise failed with silence_warnings method missing exception +require 'active_support/core_ext/kernel/reporting' diff --git a/activerecord/test/connections/postgresql.rb b/activerecord/test/connections/postgresql.rb new file mode 100644 index 0000000000..b8bfb6e846 --- /dev/null +++ b/activerecord/test/connections/postgresql.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'postgresql' diff --git a/activerecord/test/connections/sqlite3.rb b/activerecord/test/connections/sqlite3.rb new file mode 100644 index 0000000000..e5c75657a5 --- /dev/null +++ b/activerecord/test/connections/sqlite3.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'sqlite3' diff --git a/activerecord/test/connections/sqlite3_mem.rb b/activerecord/test/connections/sqlite3_mem.rb new file mode 100644 index 0000000000..900a5c7947 --- /dev/null +++ b/activerecord/test/connections/sqlite3_mem.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'sqlite3_mem' diff --git a/activerecord/test/connections/sybase.rb b/activerecord/test/connections/sybase.rb new file mode 100644 index 0000000000..7decdf7f39 --- /dev/null +++ b/activerecord/test/connections/sybase.rb @@ -0,0 +1 @@ +ENV['ARCONN'] = 'sybase' diff --git a/activerecord/test/models/comment.rb b/activerecord/test/models/comment.rb index 2a4c37089a..43650c0427 100644 --- a/activerecord/test/models/comment.rb +++ b/activerecord/test/models/comment.rb @@ -6,7 +6,8 @@ class Comment < ActiveRecord::Base scope :for_first_author, :joins => :post, :conditions => { "posts.author_id" => 1 } - + scope :created + belongs_to :post, :counter_cache => true has_many :ratings diff --git a/activerecord/test/models/contract.rb b/activerecord/test/models/contract.rb index 94fd48e12a..2cf5aa7a85 100644 --- a/activerecord/test/models/contract.rb +++ b/activerecord/test/models/contract.rb @@ -1,4 +1,19 @@ class Contract < ActiveRecord::Base belongs_to :company belongs_to :developer + + before_save :hi + after_save :bye + + attr_accessor :hi_count, :bye_count + + def hi + @hi_count ||= 0 + @hi_count += 1 + end + + def bye + @bye_count ||= 0 + @bye_count += 1 + end end diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb index 41c52f7df0..98d6aa22f7 100644 --- a/activerecord/test/models/developer.rb +++ b/activerecord/test/models/developer.rb @@ -86,6 +86,11 @@ class DeveloperWithBeforeDestroyRaise < ActiveRecord::Base end end +class DeveloperWithSelect < ActiveRecord::Base + self.table_name = 'developers' + default_scope select('name') +end + class DeveloperOrderedBySalary < ActiveRecord::Base self.table_name = 'developers' default_scope :order => 'salary DESC' diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index f2ab7b053e..affa37b02d 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -36,6 +36,10 @@ class Post < ActiveRecord::Base def find_most_recent find(:first, :order => "id DESC") end + + def newest + created.last + end end has_many :author_favorites, :through => :author diff --git a/activerecord/test/support/config.rb b/activerecord/test/support/config.rb new file mode 100644 index 0000000000..3b1598e368 --- /dev/null +++ b/activerecord/test/support/config.rb @@ -0,0 +1,39 @@ +require 'yaml' +require 'erubis' +require 'fileutils' + +module ARTest + class << self + def config + @config ||= read_config + end + + private + + def read_config + unless File.exist?(TEST_ROOT + '/config.yml') + FileUtils.cp TEST_ROOT + '/config.example.yml', TEST_ROOT + '/config.yml' + end + + raw = File.read(TEST_ROOT + '/config.yml') + erb = Erubis::Eruby.new(raw) + expand_config(YAML.parse(erb.result(binding)).transform) + end + + def expand_config(config) + config['connections'].each do |adapter, connection| + dbs = [['arunit', 'activerecord_unittest'], ['arunit2', 'activerecord_unittest2']] + dbs.each do |name, dbname| + unless connection[name].is_a?(Hash) + connection[name] = { 'database' => connection[name] } + end + + connection[name]['database'] ||= dbname + connection[name]['adapter'] ||= adapter + end + end + + config + end + end +end diff --git a/activerecord/test/support/connection.rb b/activerecord/test/support/connection.rb new file mode 100644 index 0000000000..fcd2e4dee5 --- /dev/null +++ b/activerecord/test/support/connection.rb @@ -0,0 +1,20 @@ +require 'logger' +require_dependency 'models/course' + +module ARTest + def self.connection_name + ENV['ARCONN'] || config['default_connection'] + end + + def self.connection_config + config['connections'][connection_name] + end + + def self.connect + puts "Using #{connection_name}" + ActiveRecord::Base.logger = Logger.new("debug.log") + ActiveRecord::Base.configurations = connection_config + ActiveRecord::Base.establish_connection 'arunit' + Course.establish_connection 'arunit2' + end +end diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index 0c272fa093..74730ca01f 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -283,7 +283,7 @@ module ActiveResource # attribute 'name', :string # # # or use the convenience methods and pass >=1 attribute names - # string 'eye_colour', 'hair_colour' + # string 'eye_color', 'hair_color' # integer 'age' # float 'height', 'weight' # diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index bfd1e91bb5..6b7044aeae 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -2,8 +2,13 @@ * Removed ActiveSupport::SecureRandom in favour of SecureRandom from the standard library [Jon Leighton] +* ActiveSupport::OrderedHash now has different behavior for #each and +#each_pair when given a block accepting its parameters with a splat. [Andrew Radev] + *Rails 3.1.0 (unreleased)* +* ActiveSupport::Dependencies now raises NameError if it finds an existing constant in load_missing_constant. This better reflects the nature of the error which is usually caused by calling constantize on a nested constant. [Andrew White] + * Deprecated ActiveSupport::SecureRandom in favour of SecureRandom from the standard library [Jon Leighton] * New reporting method Kernel#quietly. [fxn] diff --git a/activesupport/lib/active_support/benchmarkable.rb b/activesupport/lib/active_support/benchmarkable.rb index 21c0296269..e303eaa5ce 100644 --- a/activesupport/lib/active_support/benchmarkable.rb +++ b/activesupport/lib/active_support/benchmarkable.rb @@ -31,13 +31,8 @@ module ActiveSupport # <% end %> def benchmark(message = "Benchmarking", options = {}) if logger - if options.is_a?(Symbol) - ActiveSupport::Deprecation.warn("use benchmark('#{message}', :level => :#{options}) instead", caller) - options = { :level => options, :silence => false } - else - options.assert_valid_keys(:level, :silence) - options[:level] ||= :info - end + options.assert_valid_keys(:level, :silence) + options[:level] ||= :info result = nil ms = Benchmark.ms { result = options[:silence] ? logger.silence { yield } : yield } diff --git a/activesupport/lib/active_support/cache/compressed_mem_cache_store.rb b/activesupport/lib/active_support/cache/compressed_mem_cache_store.rb deleted file mode 100644 index 7c7d1c4b00..0000000000 --- a/activesupport/lib/active_support/cache/compressed_mem_cache_store.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActiveSupport - module Cache - class CompressedMemCacheStore < MemCacheStore - def initialize(*args) - ActiveSupport::Deprecation.warn('ActiveSupport::Cache::CompressedMemCacheStore has been deprecated in favor of ActiveSupport::Cache::MemCacheStore(:compress => true).', caller) - addresses = args.dup - options = addresses.extract_options! - args = addresses + [options.merge(:compress => true)] - super(*args) - end - end - end -end diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb index a1376ae52a..c4da04e532 100644 --- a/activesupport/lib/active_support/cache/file_store.rb +++ b/activesupport/lib/active_support/cache/file_store.rb @@ -77,19 +77,7 @@ module ActiveSupport def read_entry(key, options) file_name = key_file_path(key) if File.exist?(file_name) - entry = File.open(file_name) { |f| Marshal.load(f) } - if entry && !entry.expired? && !entry.expires_in && !self.options[:expires_in] - # Check for deprecated use of +:expires_in+ option from versions < 3.0 - deprecated_expires_in = options[:expires_in] - if deprecated_expires_in - ActiveSupport::Deprecation.warn('Setting :expires_in on read has been deprecated in favor of setting it on write.', caller) - if entry.created_at + deprecated_expires_in.to_f <= Time.now.to_f - delete_entry(key, options) - entry = nil - end - end - end - entry + File.open(file_name) { |f| Marshal.load(f) } end rescue nil diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb index 7ef1497ac2..64d2c3bff6 100644 --- a/activesupport/lib/active_support/cache/mem_cache_store.rb +++ b/activesupport/lib/active_support/cache/mem_cache_store.rb @@ -31,7 +31,7 @@ module ActiveSupport DELETED = "DELETED\r\n" end - ESCAPE_KEY_CHARS = /[\x00-\x20%\x7F-\xFF]/ + ESCAPE_KEY_CHARS = /[\x00-\x20%\x7F-\xFF]/n def self.build_mem_cache(*addresses) addresses = addresses.flatten diff --git a/activesupport/lib/active_support/cache/synchronized_memory_store.rb b/activesupport/lib/active_support/cache/synchronized_memory_store.rb deleted file mode 100644 index 37caa6b6f1..0000000000 --- a/activesupport/lib/active_support/cache/synchronized_memory_store.rb +++ /dev/null @@ -1,11 +0,0 @@ -module ActiveSupport - module Cache - # Like MemoryStore, but thread-safe. - class SynchronizedMemoryStore < MemoryStore - def initialize(*args) - ActiveSupport::Deprecation.warn('ActiveSupport::Cache::SynchronizedMemoryStore has been deprecated in favor of ActiveSupport::Cache::MemoryStore.', caller) - super - end - end - end -end diff --git a/activesupport/lib/active_support/core_ext/array/access.rb b/activesupport/lib/active_support/core_ext/array/access.rb index 2df4fd1da1..6162f7af27 100644 --- a/activesupport/lib/active_support/core_ext/array/access.rb +++ b/activesupport/lib/active_support/core_ext/array/access.rb @@ -16,7 +16,7 @@ class Array # %w( a b c d ).to(10) # => %w( a b c d ) # %w().to(0) # => %w() def to(position) - self[0..position] + self.first position + 1 end # Equal to <tt>self[1]</tt>. diff --git a/activesupport/lib/active_support/core_ext/class.rb b/activesupport/lib/active_support/core_ext/class.rb index 6f308a0d62..86b752c2f3 100644 --- a/activesupport/lib/active_support/core_ext/class.rb +++ b/activesupport/lib/active_support/core_ext/class.rb @@ -1,5 +1,4 @@ require 'active_support/core_ext/class/attribute' require 'active_support/core_ext/class/attribute_accessors' -require 'active_support/core_ext/class/inheritable_attributes' require 'active_support/core_ext/class/delegating_attributes' require 'active_support/core_ext/class/subclasses' diff --git a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb b/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb deleted file mode 100644 index 1650602d24..0000000000 --- a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb +++ /dev/null @@ -1,178 +0,0 @@ -require 'active_support/core_ext/object/duplicable' -require 'active_support/core_ext/array/extract_options' -require 'active_support/deprecation' - -# Retained for backward compatibility. Methods are now included in Class. -module ClassInheritableAttributes # :nodoc: - DEPRECATION_WARNING_MESSAGE = "class_inheritable_attribute is deprecated, please use class_attribute method instead. Notice their behavior are slightly different, so refer to class_attribute documentation first" -end - -# It is recommended to use <tt>class_attribute</tt> over methods defined in this file. Please -# refer to documentation for <tt>class_attribute</tt> for more information. Officially it is not -# deprecated but <tt>class_attribute</tt> is faster. -# -# Allows attributes to be shared within an inheritance hierarchy. Each descendant gets a copy of -# their parents' attributes, instead of just a pointer to the same. This means that the child can add elements -# to, for example, an array without those additions being shared with either their parent, siblings, or -# children. This is unlike the regular class-level attributes that are shared across the entire hierarchy. -# -# The copies of inheritable parent attributes are added to subclasses when they are created, via the -# +inherited+ hook. -# -# class Person -# class_inheritable_accessor :hair_colors -# end -# -# Person.hair_colors = [:brown, :black, :blonde, :red] -# Person.hair_colors # => [:brown, :black, :blonde, :red] -# Person.new.hair_colors # => [:brown, :black, :blonde, :red] -# -# To opt out of the instance writer method, pass :instance_writer => false. -# To opt out of the instance reader method, pass :instance_reader => false. -# -# class Person -# class_inheritable_accessor :hair_colors :instance_writer => false, :instance_reader => false -# end -# -# Person.new.hair_colors = [:brown] # => NoMethodError -# Person.new.hair_colors # => NoMethodError -class Class # :nodoc: - def class_inheritable_reader(*syms) - ActiveSupport::Deprecation.warn ClassInheritableAttributes::DEPRECATION_WARNING_MESSAGE - options = syms.extract_options! - syms.each do |sym| - next if sym.is_a?(Hash) - class_eval(<<-EOS, __FILE__, __LINE__ + 1) - def self.#{sym} # def self.after_add - read_inheritable_attribute(:#{sym}) # read_inheritable_attribute(:after_add) - end # end - # - #{" # - def #{sym} # def after_add - self.class.#{sym} # self.class.after_add - end # end - " unless options[:instance_reader] == false } # # the reader above is generated unless options[:instance_reader] == false - EOS - end - end - - def class_inheritable_writer(*syms) - ActiveSupport::Deprecation.warn ClassInheritableAttributes::DEPRECATION_WARNING_MESSAGE - options = syms.extract_options! - syms.each do |sym| - class_eval(<<-EOS, __FILE__, __LINE__ + 1) - def self.#{sym}=(obj) # def self.color=(obj) - write_inheritable_attribute(:#{sym}, obj) # write_inheritable_attribute(:color, obj) - end # end - # - #{" # - def #{sym}=(obj) # def color=(obj) - self.class.#{sym} = obj # self.class.color = obj - end # end - " unless options[:instance_writer] == false } # # the writer above is generated unless options[:instance_writer] == false - EOS - end - end - - def class_inheritable_array_writer(*syms) - ActiveSupport::Deprecation.warn ClassInheritableAttributes::DEPRECATION_WARNING_MESSAGE - options = syms.extract_options! - syms.each do |sym| - class_eval(<<-EOS, __FILE__, __LINE__ + 1) - def self.#{sym}=(obj) # def self.levels=(obj) - write_inheritable_array(:#{sym}, obj) # write_inheritable_array(:levels, obj) - end # end - # - #{" # - def #{sym}=(obj) # def levels=(obj) - self.class.#{sym} = obj # self.class.levels = obj - end # end - " unless options[:instance_writer] == false } # # the writer above is generated unless options[:instance_writer] == false - EOS - end - end - - def class_inheritable_hash_writer(*syms) - ActiveSupport::Deprecation.warn ClassInheritableAttributes::DEPRECATION_WARNING_MESSAGE - options = syms.extract_options! - syms.each do |sym| - class_eval(<<-EOS, __FILE__, __LINE__ + 1) - def self.#{sym}=(obj) # def self.nicknames=(obj) - write_inheritable_hash(:#{sym}, obj) # write_inheritable_hash(:nicknames, obj) - end # end - # - #{" # - def #{sym}=(obj) # def nicknames=(obj) - self.class.#{sym} = obj # self.class.nicknames = obj - end # end - " unless options[:instance_writer] == false } # # the writer above is generated unless options[:instance_writer] == false - EOS - end - end - - def class_inheritable_accessor(*syms) - class_inheritable_reader(*syms) - class_inheritable_writer(*syms) - end - - def class_inheritable_array(*syms) - class_inheritable_reader(*syms) - class_inheritable_array_writer(*syms) - end - - def class_inheritable_hash(*syms) - class_inheritable_reader(*syms) - class_inheritable_hash_writer(*syms) - end - - def inheritable_attributes - @inheritable_attributes ||= EMPTY_INHERITABLE_ATTRIBUTES - end - - def write_inheritable_attribute(key, value) - if inheritable_attributes.equal?(EMPTY_INHERITABLE_ATTRIBUTES) - @inheritable_attributes = {} - end - inheritable_attributes[key] = value - end - - def write_inheritable_array(key, elements) - write_inheritable_attribute(key, []) if read_inheritable_attribute(key).nil? - write_inheritable_attribute(key, read_inheritable_attribute(key) + elements) - end - - def write_inheritable_hash(key, hash) - write_inheritable_attribute(key, {}) if read_inheritable_attribute(key).nil? - write_inheritable_attribute(key, read_inheritable_attribute(key).merge(hash)) - end - - def read_inheritable_attribute(key) - inheritable_attributes[key] - end - - def reset_inheritable_attributes - ActiveSupport::Deprecation.warn ClassInheritableAttributes::DEPRECATION_WARNING_MESSAGE - @inheritable_attributes = EMPTY_INHERITABLE_ATTRIBUTES - end - - private - # Prevent this constant from being created multiple times - EMPTY_INHERITABLE_ATTRIBUTES = {}.freeze - - def inherited_with_inheritable_attributes(child) - inherited_without_inheritable_attributes(child) if respond_to?(:inherited_without_inheritable_attributes) - - if inheritable_attributes.equal?(EMPTY_INHERITABLE_ATTRIBUTES) - new_inheritable_attributes = EMPTY_INHERITABLE_ATTRIBUTES - else - new_inheritable_attributes = Hash[inheritable_attributes.map do |(key, value)| - [key, value.duplicable? ? value.dup : value] - end] - end - - child.instance_variable_set('@inheritable_attributes', new_inheritable_attributes) - end - - alias inherited_without_inheritable_attributes inherited - alias inherited inherited_with_inheritable_attributes -end diff --git a/activesupport/lib/active_support/core_ext/module.rb b/activesupport/lib/active_support/core_ext/module.rb index f59fcd123c..9fed346b7c 100644 --- a/activesupport/lib/active_support/core_ext/module.rb +++ b/activesupport/lib/active_support/core_ext/module.rb @@ -4,7 +4,6 @@ require 'active_support/core_ext/module/anonymous' require 'active_support/core_ext/module/reachable' require 'active_support/core_ext/module/attribute_accessors' require 'active_support/core_ext/module/attr_internal' -require 'active_support/core_ext/module/attr_accessor_with_default' require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/module/synchronization' require 'active_support/core_ext/module/deprecation' diff --git a/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb b/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb deleted file mode 100644 index 984f6fb957..0000000000 --- a/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb +++ /dev/null @@ -1,31 +0,0 @@ -class Module - # Declare an attribute accessor with an initial default return value. - # - # To give attribute <tt>:age</tt> the initial value <tt>25</tt>: - # - # class Person - # attr_accessor_with_default :age, 25 - # end - # - # person = Person.new - # person.age # => 25 - # - # person.age = 26 - # person.age # => 26 - # - # To give attribute <tt>:element_name</tt> a dynamic default value, evaluated - # in scope of self: - # - # attr_accessor_with_default(:element_name) { name.underscore } - # - def attr_accessor_with_default(sym, default = Proc.new) - ActiveSupport::Deprecation.warn "attr_accessor_with_default is deprecated. Use Ruby instead!" - define_method(sym, block_given? ? default : Proc.new { default }) - module_eval(<<-EVAL, __FILE__, __LINE__ + 1) - def #{sym}=(value) # def age=(value) - class << self; attr_accessor :#{sym} end # class << self; attr_accessor :age end - @#{sym} = value # @age = value - end # end - EVAL - end -end diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index c361c33162..26c5c157cb 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -5,7 +5,6 @@ require 'active_support/core_ext/module/aliasing' require 'active_support/core_ext/module/attribute_accessors' require 'active_support/core_ext/module/introspection' require 'active_support/core_ext/module/anonymous' -require 'active_support/core_ext/module/deprecation' require 'active_support/core_ext/object/blank' require 'active_support/core_ext/load_error' require 'active_support/core_ext/name_error' @@ -474,7 +473,7 @@ module ActiveSupport #:nodoc: raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!" end - raise ArgumentError, "#{from_mod} is not missing constant #{const_name}!" if local_const_defined?(from_mod, const_name) + raise NameError, "#{from_mod} is not missing constant #{const_name}!" if local_const_defined?(from_mod, const_name) qualified_name = qualified_name_for from_mod, const_name path_suffix = qualified_name.underscore @@ -550,23 +549,6 @@ module ActiveSupport #:nodoc: end alias :get :[] - class Getter # :nodoc: - def initialize(name) - @name = name - end - - def get - Reference.get @name - end - deprecate :get - end - - def new(name) - self[name] = name - Getter.new(name) - end - deprecate :new - def store(name) self[name] = name self @@ -579,11 +561,6 @@ module ActiveSupport #:nodoc: Reference = ClassCache.new - def ref(name) - Reference.new(name) - end - deprecate :ref - # Store a reference to a class +klass+. def reference(klass) Reference.store klass diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb index c2c45e9f9d..67698c1cff 100644 --- a/activesupport/lib/active_support/json/encoding.rb +++ b/activesupport/lib/active_support/json/encoding.rb @@ -1,6 +1,5 @@ require 'active_support/core_ext/object/to_json' require 'active_support/core_ext/module/delegation' -require 'active_support/deprecation' require 'active_support/json/variable' require 'active_support/ordered_hash' @@ -139,8 +138,6 @@ module ActiveSupport self.use_standard_json_time_format = true self.escape_html_entities_in_json = false end - - CircularReferenceError = Deprecation::DeprecatedConstantProxy.new('ActiveSupport::JSON::CircularReferenceError', Encoding::CircularReferenceError) end end diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index 762a64a881..68f4bd66da 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -158,7 +158,11 @@ module ActiveSupport self end - alias_method :each_pair, :each + def each_pair + return to_enum(:each_pair) unless block_given? + @keys.each {|key| yield key, self[key]} + self + end alias_method :select, :find_all diff --git a/activesupport/lib/active_support/xml_mini/jdom.rb b/activesupport/lib/active_support/xml_mini/jdom.rb index 7aefabfdd1..6c222b83ba 100644 --- a/activesupport/lib/active_support/xml_mini/jdom.rb +++ b/activesupport/lib/active_support/xml_mini/jdom.rb @@ -41,7 +41,7 @@ module ActiveSupport xml_string_reader = StringReader.new(data) xml_input_source = InputSource.new(xml_string_reader) doc = @dbf.new_document_builder.parse(xml_input_source) - merge_element!({}, doc.document_element) + merge_element!({CONTENT_KEY => ''}, doc.document_element) end end @@ -54,9 +54,14 @@ module ActiveSupport # element:: # XML element to merge into hash def merge_element!(hash, element) + delete_empty(hash) merge!(hash, element.tag_name, collapse(element)) end + def delete_empty(hash) + hash.delete(CONTENT_KEY) if hash[CONTENT_KEY] == '' + end + # Actually converts an XML document element into a data structure. # # element:: @@ -84,6 +89,7 @@ module ActiveSupport # element:: # XML element whose texts are to me merged into the hash def merge_texts!(hash, element) + delete_empty(hash) text_children = texts(element) if text_children.join.empty? hash @@ -128,6 +134,7 @@ module ActiveSupport attribute_hash = {} attributes = element.attributes for i in 0...attributes.length + attribute_hash[CONTENT_KEY] ||= '' attribute_hash[attributes.item(i).name] = attributes.item(i).value end attribute_hash diff --git a/activesupport/test/benchmarkable_test.rb b/activesupport/test/benchmarkable_test.rb index 766956f50f..06f5172e1f 100644 --- a/activesupport/test/benchmarkable_test.rb +++ b/activesupport/test/benchmarkable_test.rb @@ -26,17 +26,6 @@ class BenchmarkableTest < ActiveSupport::TestCase assert_last_logged 'test_run' end - def test_with_message_and_deprecated_level - i_was_run = false - - assert_deprecated do - benchmark('debug_run', :debug) { i_was_run = true } - end - - assert i_was_run - assert_last_logged 'debug_run' - end - def test_within_level logger.level = ActiveSupport::BufferedLogger::DEBUG benchmark('included_debug_run', :level => :debug) { } diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index 476d55fffd..ed5ccb44de 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -531,26 +531,6 @@ class FileStoreTest < ActiveSupport::TestCase include CacheDeleteMatchedBehavior include CacheIncrementDecrementBehavior - def test_deprecated_expires_in_on_read - ActiveSupport::Deprecation.silence do - old_cache = ActiveSupport::Cache.lookup_store(:file_store, cache_dir) - - time = Time.local(2008, 4, 24) - Time.stubs(:now).returns(time) - - old_cache.write("foo", "bar") - assert_equal 'bar', old_cache.read('foo', :expires_in => 60) - - Time.stubs(:now).returns(time + 30) - assert_equal 'bar', old_cache.read('foo', :expires_in => 60) - - Time.stubs(:now).returns(time + 61) - assert_equal 'bar', old_cache.read('foo') - assert_nil old_cache.read('foo', :expires_in => 60) - assert_nil old_cache.read('foo') - end - end - def test_key_transformation key = @cache.send(:key_file_path, "views/index?id=1") assert_equal "views/index?id=1", @cache.send(:file_path_key, key) @@ -628,18 +608,6 @@ class MemoryStoreTest < ActiveSupport::TestCase end end -class SynchronizedStoreTest < ActiveSupport::TestCase - def setup - ActiveSupport::Deprecation.silence do - @cache = ActiveSupport::Cache.lookup_store(:memory_store, :expires_in => 60) - end - end - - include CacheStoreBehavior - include CacheDeleteMatchedBehavior - include CacheIncrementDecrementBehavior -end - uses_memcached 'memcached backed store' do class MemCacheStoreTest < ActiveSupport::TestCase def setup @@ -672,18 +640,6 @@ uses_memcached 'memcached backed store' do end end end - - class CompressedMemCacheStore < ActiveSupport::TestCase - def setup - ActiveSupport::Deprecation.silence do - @cache = ActiveSupport::Cache.lookup_store(:compressed_mem_cache_store, :expires_in => 60) - @cache.clear - end - end - - include CacheStoreBehavior - include CacheIncrementDecrementBehavior - end end class CacheStoreLoggerTest < ActiveSupport::TestCase diff --git a/activesupport/test/class_cache_test.rb b/activesupport/test/class_cache_test.rb index fc2d54515d..752c0ee478 100644 --- a/activesupport/test/class_cache_test.rb +++ b/activesupport/test/class_cache_test.rb @@ -51,20 +51,6 @@ module ActiveSupport assert_equal @cache[ClassCacheTest], @cache.get(ClassCacheTest.name) end - def test_new - assert_deprecated do - @cache.new ClassCacheTest - end - assert @cache.key?(ClassCacheTest.name) - end - - def test_new_rejects_strings_when_called_on_a_new_string - assert_deprecated do - @cache.new ClassCacheTest.name - end - assert !@cache.key?(ClassCacheTest.name) - end - def test_new_rejects_strings @cache.store ClassCacheTest.name assert !@cache.key?(ClassCacheTest.name) @@ -74,35 +60,6 @@ module ActiveSupport x = @cache.store ClassCacheTest assert_equal @cache, x end - - def test_new_returns_proxy - v = nil - assert_deprecated do - v = @cache.new ClassCacheTest.name - end - - assert_deprecated do - assert_equal ClassCacheTest, v.get - end - end - - def test_anonymous_class_fail - assert_raises(ArgumentError) do - assert_deprecated do - @cache.new Class.new - end - end - - assert_raises(ArgumentError) do - x = Class.new - @cache[x] = x - end - - assert_raises(ArgumentError) do - x = Class.new - @cache.store x - end - end end end end diff --git a/activesupport/test/core_ext/class/class_inheritable_attributes_test.rb b/activesupport/test/core_ext/class/class_inheritable_attributes_test.rb deleted file mode 100644 index 020dfce56a..0000000000 --- a/activesupport/test/core_ext/class/class_inheritable_attributes_test.rb +++ /dev/null @@ -1,230 +0,0 @@ -require 'abstract_unit' -require 'active_support/core_ext/class/inheritable_attributes' - -class ClassInheritableAttributesTest < Test::Unit::TestCase - def setup - ActiveSupport::Deprecation.silenced = true - @klass = Class.new - end - - def teardown - ActiveSupport::Deprecation.silenced = false - end - - def test_reader_declaration - assert_nothing_raised do - @klass.class_inheritable_reader :a - assert_respond_to @klass, :a - assert_respond_to @klass.new, :a - end - end - - def test_writer_declaration - assert_nothing_raised do - @klass.class_inheritable_writer :a - assert_respond_to @klass, :a= - assert_respond_to @klass.new, :a= - end - end - - def test_writer_declaration_without_instance_writer - assert_nothing_raised do - @klass.class_inheritable_writer :a, :instance_writer => false - assert_respond_to @klass, :a= - assert !@klass.new.respond_to?(:a=) - end - end - - def test_accessor_declaration - assert_nothing_raised do - @klass.class_inheritable_accessor :a - assert_respond_to @klass, :a - assert_respond_to @klass.new, :a - assert_respond_to @klass, :a= - assert_respond_to @klass.new, :a= - end - end - - def test_accessor_declaration_without_instance_writer - assert_nothing_raised do - @klass.class_inheritable_accessor :a, :instance_writer => false - assert_respond_to @klass, :a - assert_respond_to @klass.new, :a - assert_respond_to @klass, :a= - assert !@klass.new.respond_to?(:a=) - end - end - - def test_array_declaration - assert_nothing_raised do - @klass.class_inheritable_array :a - assert_respond_to @klass, :a - assert_respond_to @klass.new, :a - assert_respond_to @klass, :a= - assert_respond_to @klass.new, :a= - end - end - - def test_array_declaration_without_instance_writer - assert_nothing_raised do - @klass.class_inheritable_array :a, :instance_writer => false - assert_respond_to @klass, :a - assert_respond_to @klass.new, :a - assert_respond_to @klass, :a= - assert !@klass.new.respond_to?(:a=) - end - end - - def test_hash_declaration - assert_nothing_raised do - @klass.class_inheritable_hash :a - assert_respond_to @klass, :a - assert_respond_to @klass.new, :a - assert_respond_to @klass, :a= - assert_respond_to @klass.new, :a= - end - end - - def test_hash_declaration_without_instance_writer - assert_nothing_raised do - @klass.class_inheritable_hash :a, :instance_writer => false - assert_respond_to @klass, :a - assert_respond_to @klass.new, :a - assert_respond_to @klass, :a= - assert !@klass.new.respond_to?(:a=) - end - end - - def test_reader - @klass.class_inheritable_reader :a - assert_nil @klass.a - assert_nil @klass.new.a - - @klass.send(:write_inheritable_attribute, :a, 'a') - - assert_equal 'a', @klass.a - assert_equal 'a', @klass.new.a - assert_equal @klass.a, @klass.new.a - assert_equal @klass.a.object_id, @klass.new.a.object_id - end - - def test_writer - @klass.class_inheritable_reader :a - @klass.class_inheritable_writer :a - - assert_nil @klass.a - assert_nil @klass.new.a - - @klass.a = 'a' - assert_equal 'a', @klass.a - @klass.new.a = 'A' - assert_equal 'A', @klass.a - end - - def test_array - @klass.class_inheritable_array :a - - assert_nil @klass.a - assert_nil @klass.new.a - - @klass.a = %w(a b c) - assert_equal %w(a b c), @klass.a - assert_equal %w(a b c), @klass.new.a - - @klass.new.a = %w(A B C) - assert_equal %w(a b c A B C), @klass.a - assert_equal %w(a b c A B C), @klass.new.a - end - - def test_hash - @klass.class_inheritable_hash :a - - assert_nil @klass.a - assert_nil @klass.new.a - - @klass.a = { :a => 'a' } - assert_equal({ :a => 'a' }, @klass.a) - assert_equal({ :a => 'a' }, @klass.new.a) - - @klass.new.a = { :b => 'b' } - assert_equal({ :a => 'a', :b => 'b' }, @klass.a) - assert_equal({ :a => 'a', :b => 'b' }, @klass.new.a) - end - - def test_inheritance - @klass.class_inheritable_accessor :a - @klass.a = 'a' - - @sub = eval("class FlogMe < @klass; end; FlogMe") - - @klass.class_inheritable_accessor :b - - assert_respond_to @sub, :a - assert_respond_to @sub, :b - assert_equal @klass.a, @sub.a - assert_equal @klass.b, @sub.b - assert_equal 'a', @sub.a - assert_nil @sub.b - - @klass.b = 'b' - assert_not_equal @klass.b, @sub.b - assert_equal 'b', @klass.b - assert_nil @sub.b - - @sub.a = 'A' - assert_not_equal @klass.a, @sub.a - assert_equal 'a', @klass.a - assert_equal 'A', @sub.a - - @sub.b = 'B' - assert_not_equal @klass.b, @sub.b - assert_equal 'b', @klass.b - assert_equal 'B', @sub.b - end - - def test_array_inheritance - @klass.class_inheritable_accessor :a - @klass.a = [] - - @sub = eval("class SubbyArray < @klass; end; SubbyArray") - - assert_equal [], @klass.a - assert_equal [], @sub.a - - @sub.a << :first - - assert_equal [:first], @sub.a - assert_equal [], @klass.a - end - - def test_array_inheritance_ - @klass.class_inheritable_accessor :a - @klass.a = {} - - @sub = eval("class SubbyHash < @klass; end; SubbyHash") - - assert_equal Hash.new, @klass.a - assert_equal Hash.new, @sub.a - - @sub.a[:first] = :first - - assert_equal 1, @sub.a.keys.size - assert_equal 0, @klass.a.keys.size - end - - def test_reset_inheritable_attributes - @klass.class_inheritable_accessor :a - @klass.a = 'a' - - @sub = eval("class Inheriting < @klass; end; Inheriting") - - assert_equal 'a', @klass.a - assert_equal 'a', @sub.a - - @klass.reset_inheritable_attributes - @sub = eval("class NotInheriting < @klass; end; NotInheriting") - - assert_nil @klass.a - assert_nil @sub.a - end -end diff --git a/activesupport/test/core_ext/module/attr_accessor_with_default_test.rb b/activesupport/test/core_ext/module/attr_accessor_with_default_test.rb deleted file mode 100644 index 0ecd16b051..0000000000 --- a/activesupport/test/core_ext/module/attr_accessor_with_default_test.rb +++ /dev/null @@ -1,39 +0,0 @@ -require 'abstract_unit' -require 'active_support/core_ext/module/attr_accessor_with_default' - -class AttrAccessorWithDefaultTest < ActiveSupport::TestCase - def setup - @target = Class.new do - def helper - 'helper' - end - end - @instance = @target.new - end - - def test_default_arg - assert_deprecated do - @target.attr_accessor_with_default :foo, :bar - end - assert_equal(:bar, @instance.foo) - @instance.foo = nil - assert_nil(@instance.foo) - end - - def test_default_proc - assert_deprecated do - @target.attr_accessor_with_default(:foo) {helper.upcase} - end - assert_equal('HELPER', @instance.foo) - @instance.foo = nil - assert_nil(@instance.foo) - end - - def test_invalid_args - assert_raise(ArgumentError) do - assert_deprecated do - @target.attr_accessor_with_default :foo - end - end - end -end diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index 2ddbce5150..b4edf0f51d 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -441,7 +441,7 @@ class DependenciesTest < Test::Unit::TestCase with_autoloading_fixtures do require_dependency '././counting_loader' assert_equal 1, $counting_loaded_times - assert_raise(ArgumentError) { ActiveSupport::Dependencies.load_missing_constant Object, :CountingLoader } + assert_raise(NameError) { ActiveSupport::Dependencies.load_missing_constant Object, :CountingLoader } assert_equal 1, $counting_loaded_times end end diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index f3dcd7b068..bf851dbcbc 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -114,6 +114,9 @@ class OrderedHashTest < Test::Unit::TestCase end assert_equal @values, values assert_equal @keys, keys + + expected_class = RUBY_VERSION < '1.9' ? Enumerable::Enumerator : Enumerator + assert_kind_of expected_class, @ordered_hash.each_pair end def test_find_all @@ -257,6 +260,26 @@ class OrderedHashTest < Test::Unit::TestCase assert_equal @values, values end + def test_each_when_yielding_to_block_with_splat + hash_values = [] + ordered_hash_values = [] + + @hash.each { |*v| hash_values << v } + @ordered_hash.each { |*v| ordered_hash_values << v } + + assert_equal hash_values.sort, ordered_hash_values.sort + end + + def test_each_pair_when_yielding_to_block_with_splat + hash_values = [] + ordered_hash_values = [] + + @hash.each_pair { |*v| hash_values << v } + @ordered_hash.each_pair { |*v| ordered_hash_values << v } + + assert_equal hash_values.sort, ordered_hash_values.sort + end + def test_order_after_yaml_serialization @deserialized_ordered_hash = YAML.load(YAML.dump(@ordered_hash)) diff --git a/activesupport/test/xml_mini/jdom_engine_test.rb b/activesupport/test/xml_mini/jdom_engine_test.rb index 3fe5e4fd78..7f809e7898 100644 --- a/activesupport/test/xml_mini/jdom_engine_test.rb +++ b/activesupport/test/xml_mini/jdom_engine_test.rb @@ -15,20 +15,20 @@ if RUBY_PLATFORM =~ /java/ XmlMini.backend = @default_backend end - # def test_file_from_xml - # hash = Hash.from_xml(<<-eoxml) - # <blog> - # <logo type="file" name="logo.png" content_type="image/png"> - # </logo> - # </blog> - # eoxml - # assert hash.has_key?('blog') - # assert hash['blog'].has_key?('logo') - # - # file = hash['blog']['logo'] - # assert_equal 'logo.png', file.original_filename - # assert_equal 'image/png', file.content_type - # end + def test_file_from_xml + hash = Hash.from_xml(<<-eoxml) + <blog> + <logo type="file" name="logo.png" content_type="image/png"> + </logo> + </blog> + eoxml + assert hash.has_key?('blog') + assert hash['blog'].has_key?('logo') + + file = hash['blog']['logo'] + assert_equal 'logo.png', file.original_filename + assert_equal 'image/png', file.content_type + end def test_exception_thrown_on_expansion_attack assert_raise NativeException do diff --git a/load_paths.rb b/load_paths.rb index 15345e31e3..590af69330 100644 --- a/load_paths.rb +++ b/load_paths.rb @@ -1,9 +1,8 @@ # bust gem prelude if defined? Gem - Gem.source_index gem 'bundler' else require 'rubygems' end require 'bundler' -Bundler.setup
\ No newline at end of file +Bundler.setup diff --git a/railties/CHANGELOG b/railties/CHANGELOG index c465b08594..c77d03c39f 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,3 +1,10 @@ +*Rails 3.2.0 (unreleased)* + +* Removed old plugin generator (`rails generate plugin`) in favor of `rails plugin new` command. [Guillermo Iguaran] + +* Removed old 'config.paths.app.controller' API in favor of 'config.paths["app/controller"]' API. [Guillermo Iguaran] + + *Rails 3.1.0 (unreleased)* * Application and plugin generation run bundle install unless --skip-gemfile or --skip-bundle. [fxn] diff --git a/railties/guides/assets/images/radar.png b/railties/guides/assets/images/radar.png Binary files differnew file mode 100644 index 0000000000..f61e08763f --- /dev/null +++ b/railties/guides/assets/images/radar.png diff --git a/railties/guides/assets/images/vijaydev.jpg b/railties/guides/assets/images/vijaydev.jpg Binary files differnew file mode 100644 index 0000000000..e21d3cabfc --- /dev/null +++ b/railties/guides/assets/images/vijaydev.jpg diff --git a/railties/guides/rails_guides/helpers.rb b/railties/guides/rails_guides/helpers.rb index d466c76c7c..463df8a7a8 100644 --- a/railties/guides/rails_guides/helpers.rb +++ b/railties/guides/rails_guides/helpers.rb @@ -15,7 +15,7 @@ module RailsGuides def author(name, nick, image = 'credits_pic_blank.gif', &block) image = "images/#{image}" - result = content_tag(:img, nil, :src => image, :class => 'left pic', :alt => name) + result = content_tag(:img, nil, :src => image, :class => 'left pic', :alt => name, :width => 91, :height => 91) result << content_tag(:h3, name) result << content_tag(:p, capture(&block)) content_tag(:div, result, :class => 'clearfix', :id => nick) diff --git a/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile index b17f800702..50e86e05a8 100644 --- a/railties/guides/source/api_documentation_guidelines.textile +++ b/railties/guides/source/api_documentation_guidelines.textile @@ -33,6 +33,10 @@ Spell names correctly: Arel, Test::Unit, RSpec, HTML, MySQL, JavaScript, ERB. Wh Use the article "an" for "SQL", as in "an SQL statement". Also "an SQLite database". +h3. English + +Please use American English (_color_, _center_, _modularize_, etc.). See "a list of American and British English spelling differences here":http://en.wikipedia.org/wiki/American_and_British_English_spelling_differences. + h3. Example Code Choose meaningful examples that depict and cover the basics as well as interesting points or gotchas. diff --git a/railties/guides/source/credits.html.erb b/railties/guides/source/credits.html.erb index 65e396be95..da6bd6acdf 100644 --- a/railties/guides/source/credits.html.erb +++ b/railties/guides/source/credits.html.erb @@ -9,18 +9,14 @@ Ruby on Rails Guides: Credits <% end %> -<h3 class="section">Rails Documentation Team</h3> +<h3 class="section">Rails Guides Reviewers</h3> -<%= author('Mike Gunderloy', 'mgunderloy') do %> - Mike Gunderloy is a consultant with <a href="http://www.actionrails.com">ActionRails</a>. He brings 25 years of experience in a variety of languages to bear on his current work with Rails. His near-daily links and other blogging can be found at <a href="http://afreshcup.com">A Fresh Cup</a> and he <a href="http://twitter.com/MikeG1">twitters</a> too much. -<% end %> - -<%= author('Pratik Naik', 'lifo') do %> - Pratik Naik is a Ruby on Rails consultant with <a href="http://www.actionrails.com">ActionRails</a> and also a member of the <a href="http://rubyonrails.org/core">Rails core team</a>. He maintains a blog at <a href="http://m.onkey.org">has_many :bugs, :through => :rails</a> and has an active <a href="http://twitter.com/lifo">twitter account</a>. +<%= author('Vijay Dev', 'vijaydev', 'vijaydev.jpg') do %> + Vijayakumar, found as Vijay Dev on the web, is a web applications developer and an open source enthusiast who lives in Chennai, India. He started using Rails in 2009 and began actively contributing to Rails documentation in late 2010. He <a href="https://twitter.com/vijay_dev">tweets</a> a lot and also <a href="http://vijaydev.wordpress.com">blogs</a>. <% end %> <%= author('Xavier Noria', 'fxn', 'fxn.png') do %> - Xavier Noria has been into Ruby on Rails since 2005. He is a Rails committer and enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Xavier is currently a Ruby on Rails consultant. Oh, he also <a href="http://twitter.com/fxn">tweets</a> and can be found everywhere as "fxn". + Xavier Noria has been into Ruby on Rails since 2005. He is a Rails core team member and enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Xavier is currently an independent Ruby on Rails consultant. Oh, he also <a href="http://twitter.com/fxn">tweets</a> and can be found everywhere as "fxn". <% end %> <h3 class="section">Rails Guides Designers</h3> @@ -31,6 +27,10 @@ Ruby on Rails Guides: Credits <h3 class="section">Rails Guides Authors</h3> +<%= author('Ryan Bigg', 'radar', 'radar.png') do %> +Ryan Bigg works as a consultant at <a href="http://rubyx.com">RubyX</a> and has been working with Rails since 2006. He's co-authoring a book called <a href="http://manning.com/katz">Rails 3 in Action</a> and he's written many gems which can be seen on <a href="http://github.com/radar">his GitHub page</a> and he also tweets prolifically as <a href="http://twitter.com/ryanbigg">@ryanbigg</a>. +<% end %> + <%= author('Frederick Cheung', 'fcheung') do %> Frederick Cheung is Chief Wizard at Texperts where he has been using Rails since 2006. He is based in Cambridge (UK) and when not consuming fine ales he blogs at <a href="http://www.spacevatican.org">spacevatican.org</a>. <% end %> @@ -43,6 +43,10 @@ Ruby on Rails Guides: Credits Jeff Dean is a software engineer with <a href="http://pivotallabs.com">Pivotal Labs</a>. <% end %> +<%= author('Mike Gunderloy', 'mgunderloy') do %> + Mike Gunderloy is a consultant with <a href="http://www.actionrails.com">ActionRails</a>. He brings 25 years of experience in a variety of languages to bear on his current work with Rails. His near-daily links and other blogging can be found at <a href="http://afreshcup.com">A Fresh Cup</a> and he <a href="http://twitter.com/MikeG1">twitters</a> too much. +<% end %> + <%= author('Mikel Lindsaar', 'raasdnil') do %> Mikel Lindsaar has been working with Rails since 2006 and is the author of the Ruby <a href="https://github.com/mikel/mail">Mail gem</a> and core contributor (he helped re-write Action Mailer's API). Mikel is the founder of <a href="http://rubyx.com/">RubyX</a>, has a <a href="http://lindsaar.net/">blog</a> and <a href="http://twitter.com/raasdnil">tweets</a>. <% end %> @@ -55,6 +59,10 @@ Ruby on Rails Guides: Credits James Miller is a software developer for <a href="http://www.jk-tech.com">JK Tech</a> in San Diego, CA. You can find James on GitHub, Gmail, Twitter, and Freenode as "bensie". <% end %> +<%= author('Pratik Naik', 'lifo') do %> + Pratik Naik is a Ruby on Rails consultant with <a href="http://www.actionrails.com">ActionRails</a> and also a member of the <a href="http://rubyonrails.org/core">Rails core team</a>. He maintains a blog at <a href="http://m.onkey.org">has_many :bugs, :through => :rails</a> and has an active <a href="http://twitter.com/lifo">twitter account</a>. +<% end %> + <%= author('Emilio Tagua', 'miloops') do %> Emilio Tagua —a.k.a. miloops— is an Argentinian entrepreneur, developer, open source contributor and Rails evangelist. Cofounder of <a href="http://eventioz.com">Eventioz</a>. He has been using Rails since 2006 and contributing since early 2008. Can be found at gmail, twitter, freenode, everywhere as "miloops". <% end %> diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index caa9c1016c..7972c72c1e 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -128,7 +128,7 @@ module Rails end def comment_if(value) - options[value] ? '#' : '' + options[value] ? '# ' : '' end def rails_gemfile_entry diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt index 19294b3478..f33a7f4ac2 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt +++ b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt @@ -1,9 +1,15 @@ -// This is a manifest file that'll be compiled into including all the files listed below. -// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically -// be included in the compiled file accessible from http://example.com/assets/application.js +// This is a manifest file that'll be compiled into application.js, which will include all the files +// listed below. +// +// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, +// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. +// // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // +// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD +// GO AFTER THE REQUIRES BELOW. +// <% unless options[:skip_javascript] -%> //= require <%= options[:javascript] %> //= require <%= options[:javascript] %>_ujs diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css index fc25b5723f..9e07c7d9a9 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css +++ b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css @@ -1,7 +1,13 @@ /* - * This is a manifest file that'll automatically include all the stylesheets available in this directory - * and any sub-directories. You're free to add application-wide styles to this file and they'll appear at - * the top of the compiled file, but it's generally better to create a new file per style scope. + * This is a manifest file that'll be compiled into application.css, which will include all the files + * listed below. + * + * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, + * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. + * + * You're free to add application-wide styles to this file and they'll appear at the top of the + * compiled file, but it's generally better to create a new file per style scope. + * *= require_self *= require_tree . */
\ No newline at end of file diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb index a097c77391..37c2fb1263 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/application.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb @@ -4,7 +4,7 @@ require File.expand_path('../boot', __FILE__) require 'rails/all' <% else -%> # Pick the frameworks you want: -<%= comment_if :skip_active_record %> require "active_record/railtie" +<%= comment_if :skip_active_record %>require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "active_resource/railtie" diff --git a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb index 4967d1793c..11867a4cd7 100644 --- a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb +++ b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb @@ -118,7 +118,7 @@ task :default => :test return if options.skip_javascript? if mountable? - copy_file "#{app_templates_dir}/app/assets/javascripts/application.js.tt", + template "#{app_templates_dir}/app/assets/javascripts/application.js.tt", "app/assets/javascripts/application.js" elsif full? empty_directory_with_gitkeep "app/assets/javascripts" @@ -258,7 +258,7 @@ task :default => :test elsif RESERVED_NAMES.include?(name) raise Error, "Invalid plugin name #{name}. Please give a name which does not match one of the reserved rails words." elsif Object.const_defined?(camelized) - raise Error, "Invalid plugin name #{name}, constant #{camelized} is already in use. Please choose another application name." + raise Error, "Invalid plugin name #{name}, constant #{camelized} is already in use. Please choose another plugin name." end end diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile index 29900c93dc..c28e568711 100644 --- a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile +++ b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile @@ -6,6 +6,10 @@ source "http://rubygems.org" <%= database_gemfile_entry -%> <% end -%> +<% if mountable? -%> +<%= gem_for_javascript -%> +<% end -%> + if RUBY_VERSION < '1.9' gem "ruby-debug", ">= 0.10.3" end diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb index aa8ea77bae..967668fe66 100644 --- a/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb +++ b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb @@ -1,5 +1,5 @@ module <%= camelized %> - class Engine < Rails::Engine + class Engine < ::Rails::Engine <% if mountable? -%> isolate_namespace <%= camelized %> <% end -%> diff --git a/railties/lib/rails/tasks/assets.rake b/railties/lib/rails/tasks/assets.rake index 5d2f02af13..5f87edc9e2 100644 --- a/railties/lib/rails/tasks/assets.rake +++ b/railties/lib/rails/tasks/assets.rake @@ -7,4 +7,12 @@ namespace :assets do assets = Rails.application.config.assets.precompile Rails.application.assets.precompile(*assets) end + + desc "Remove compiled assets" + task :clean => :environment do + assets = Rails.application.config.assets + public_asset_path = Rails.public_path + assets.prefix + file_list = FileList.new("#{public_asset_path}/*.js", "#{public_asset_path}/*.css") + file_list.each{ |file| rm file } + end end diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index 98a702f134..2b593005a2 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -11,6 +11,10 @@ module ApplicationTests boot_rails end + def teardown + teardown_app + end + def app @app ||= Rails.application end diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 0e27c9606d..477dada820 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -35,6 +35,7 @@ module ApplicationTests end def teardown + teardown_app FileUtils.rm_rf(new_app) if File.directory?(new_app) end diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb index db8f1f2ac6..1528d5dd87 100644 --- a/railties/test/application/console_test.rb +++ b/railties/test/application/console_test.rb @@ -1,13 +1,17 @@ require 'isolation/abstract_unit' class ConsoleTest < Test::Unit::TestCase - include ActiveSupport::Testing::Isolation + include ActiveSupport::Testing::Isolation def setup build_app boot_rails end + def teardown + teardown_app + end + def load_environment(sandbox = false) require "#{rails_root}/config/environment" Rails.application.sandbox = sandbox diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb index 1ca9515335..4365d00b1f 100644 --- a/railties/test/application/generators_test.rb +++ b/railties/test/application/generators_test.rb @@ -9,6 +9,10 @@ module ApplicationTests boot_rails end + def teardown + teardown_app + end + def app_const @app_const ||= Class.new(Rails::Application) end diff --git a/railties/test/application/initializers/boot_test.rb b/railties/test/application/initializers/boot_test.rb index 5ec562f12f..b1e01dc13f 100644 --- a/railties/test/application/initializers/boot_test.rb +++ b/railties/test/application/initializers/boot_test.rb @@ -9,8 +9,12 @@ module ApplicationTests # boot_rails end + def teardown + # teardown_app + end + test "booting rails sets the load paths correctly" do # This test is pending reworking the boot process end end -end
\ No newline at end of file +end diff --git a/railties/test/application/initializers/check_ruby_version_test.rb b/railties/test/application/initializers/check_ruby_version_test.rb index 5b6196307d..df7e9696a9 100644 --- a/railties/test/application/initializers/check_ruby_version_test.rb +++ b/railties/test/application/initializers/check_ruby_version_test.rb @@ -9,6 +9,10 @@ module ApplicationTests boot_rails end + def teardown + teardown_app + end + test "rails initializes with ruby 1.8.7 or later, except for 1.9.1" do if RUBY_VERSION < '1.8.7' assert_rails_does_not_boot diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index 196d121c14..446c85d65a 100644 --- a/railties/test/application/initializers/frameworks_test.rb +++ b/railties/test/application/initializers/frameworks_test.rb @@ -10,6 +10,10 @@ module ApplicationTests FileUtils.rm_rf "#{app_path}/config/environments" end + def teardown + teardown_app + end + # AC & AM test "set load paths set only if action controller or action mailer are in use" do assert_nothing_raised NameError do diff --git a/railties/test/application/initializers/hooks_test.rb b/railties/test/application/initializers/hooks_test.rb index 198abbe861..8c7726339c 100644 --- a/railties/test/application/initializers/hooks_test.rb +++ b/railties/test/application/initializers/hooks_test.rb @@ -10,6 +10,10 @@ module ApplicationTests FileUtils.rm_rf "#{app_path}/config/environments" end + def teardown + teardown_app + end + test "load initializers" do app_file "config/initializers/foo.rb", "$foo = true" require "#{app_path}/config/environment" diff --git a/railties/test/application/initializers/i18n_test.rb b/railties/test/application/initializers/i18n_test.rb index 390f65ab5c..aa4db6e12a 100644 --- a/railties/test/application/initializers/i18n_test.rb +++ b/railties/test/application/initializers/i18n_test.rb @@ -11,6 +11,10 @@ module ApplicationTests require "rails/all" end + def teardown + teardown_app + end + def load_app require "#{app_path}/config/environment" end diff --git a/railties/test/application/initializers/load_path_test.rb b/railties/test/application/initializers/load_path_test.rb index 714d62311d..644b8208a9 100644 --- a/railties/test/application/initializers/load_path_test.rb +++ b/railties/test/application/initializers/load_path_test.rb @@ -10,6 +10,10 @@ module ApplicationTests FileUtils.rm_rf "#{app_path}/config/environments" end + def teardown + teardown_app + end + test "initializing an application adds the application paths to the load path" do add_to_config <<-RUBY config.root = "#{app_path}" diff --git a/railties/test/application/initializers/notifications_test.rb b/railties/test/application/initializers/notifications_test.rb index c87433db0d..b72c14eaf0 100644 --- a/railties/test/application/initializers/notifications_test.rb +++ b/railties/test/application/initializers/notifications_test.rb @@ -9,6 +9,10 @@ module ApplicationTests boot_rails end + def teardown + teardown_app + end + def instrument(*args, &block) ActiveSupport::Notifications.instrument(*args, &block) end diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb index c340465e87..47c6fd5c6e 100644 --- a/railties/test/application/loading_test.rb +++ b/railties/test/application/loading_test.rb @@ -8,6 +8,10 @@ class LoadingTest < Test::Unit::TestCase boot_rails end + def teardown + teardown_app + end + def app @app ||= Rails.application end diff --git a/railties/test/application/middleware/best_practices_test.rb b/railties/test/application/middleware/best_practices_test.rb index 5b722e7510..1c88b9bf06 100644 --- a/railties/test/application/middleware/best_practices_test.rb +++ b/railties/test/application/middleware/best_practices_test.rb @@ -12,6 +12,10 @@ module ApplicationTests simple_controller end + def teardown + teardown_app + end + test "simple controller in production mode returns best standards" do get '/foo' assert_equal "IE=Edge,chrome=1", last_response.headers["X-UA-Compatible"] diff --git a/railties/test/application/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb index a8033d2b23..e656ada3c0 100644 --- a/railties/test/application/middleware/cache_test.rb +++ b/railties/test/application/middleware/cache_test.rb @@ -11,6 +11,10 @@ module ApplicationTests extend Rack::Test::Methods end + def teardown + teardown_app + end + def simple_controller controller :expires, <<-RUBY class ExpiresController < ApplicationController diff --git a/railties/test/application/middleware/remote_ip_test.rb b/railties/test/application/middleware/remote_ip_test.rb index f28302d70a..da291f061c 100644 --- a/railties/test/application/middleware/remote_ip_test.rb +++ b/railties/test/application/middleware/remote_ip_test.rb @@ -10,6 +10,10 @@ module ApplicationTests FileUtils.rm_rf "#{app_path}/config/environments" end + def teardown + teardown_app + end + def app @app ||= Rails.application end diff --git a/railties/test/application/middleware/sendfile_test.rb b/railties/test/application/middleware/sendfile_test.rb index 0128261cd4..c7a1c573f9 100644 --- a/railties/test/application/middleware/sendfile_test.rb +++ b/railties/test/application/middleware/sendfile_test.rb @@ -10,6 +10,10 @@ module ApplicationTests FileUtils.rm_rf "#{app_path}/config/environments" end + def teardown + teardown_app + end + def app @app ||= Rails.application end diff --git a/railties/test/application/middleware/show_exceptions_test.rb b/railties/test/application/middleware/show_exceptions_test.rb index 5487e41e0a..e3f27f63c3 100644 --- a/railties/test/application/middleware/show_exceptions_test.rb +++ b/railties/test/application/middleware/show_exceptions_test.rb @@ -10,6 +10,10 @@ module ApplicationTests FileUtils.rm_rf "#{app_path}/config/environments" end + def teardown + teardown_app + end + def app @app ||= Rails.application end diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb index 715798ca08..6a0a272073 100644 --- a/railties/test/application/middleware_test.rb +++ b/railties/test/application/middleware_test.rb @@ -11,6 +11,10 @@ module ApplicationTests FileUtils.rm_rf "#{app_path}/config/environments" end + def teardown + teardown_app + end + def app @app ||= Rails.application end @@ -200,4 +204,4 @@ module ApplicationTests AppTemplate::Application.middleware.map(&:klass).map(&:name) end end -end
\ No newline at end of file +end diff --git a/railties/test/application/paths_test.rb b/railties/test/application/paths_test.rb index 03e0247556..0d22d8c19a 100644 --- a/railties/test/application/paths_test.rb +++ b/railties/test/application/paths_test.rb @@ -20,6 +20,10 @@ module ApplicationTests @paths = Rails.application.config.paths end + def teardown + teardown_app + end + def root(*path) app_path(*path).to_s end diff --git a/railties/test/application/rack/logger_test.rb b/railties/test/application/rack/logger_test.rb index 715af5c642..8b2b2f1802 100644 --- a/railties/test/application/rack/logger_test.rb +++ b/railties/test/application/rack/logger_test.rb @@ -14,6 +14,10 @@ module ApplicationTests super end + def teardown + teardown_app + end + def logs @logs ||= @logger.logged(:info) end diff --git a/railties/test/application/rackup_test.rb b/railties/test/application/rackup_test.rb index b0a9925890..ff9cdcadc7 100644 --- a/railties/test/application/rackup_test.rb +++ b/railties/test/application/rackup_test.rb @@ -15,6 +15,10 @@ module ApplicationTests boot_rails end + def teardown + teardown_app + end + test "rails app is present" do assert File.exist?(app_path("config")) end diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb index ab36ace5e5..44ac6615de 100644 --- a/railties/test/application/rake_test.rb +++ b/railties/test/application/rake_test.rb @@ -10,6 +10,10 @@ module ApplicationTests FileUtils.rm_rf("#{app_path}/config/environments") end + def teardown + teardown_app + end + def test_gems_tasks_are_loaded_first_than_application_ones app_file "lib/tasks/app.rake", <<-RUBY $task_loaded = Rake::Task.task_defined?("db:create:all") @@ -113,7 +117,7 @@ module ApplicationTests end require "#{rails_root}/config/environment" - + # loading a specific fixture errormsg = Dir.chdir(app_path) { `rake db:fixtures:load FIXTURES=products` } assert $?.success?, errormsg diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb index e3a7f8a63c..3adf0ccd3e 100644 --- a/railties/test/application/routing_test.rb +++ b/railties/test/application/routing_test.rb @@ -11,6 +11,10 @@ module ApplicationTests boot_rails end + def teardown + teardown_app + end + test "rails/info/properties in development" do app("development") get "/rails/info/properties" diff --git a/railties/test/application/runner_test.rb b/railties/test/application/runner_test.rb index 292d1e247f..4104bacae5 100644 --- a/railties/test/application/runner_test.rb +++ b/railties/test/application/runner_test.rb @@ -18,6 +18,10 @@ module ApplicationTests MODEL end + def teardown + teardown_app + end + def test_should_include_runner_in_shebang_line_in_help assert_match "/rails runner", Dir.chdir(app_path) { `bundle exec rails runner --help` } end diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb index f96319f472..27a7959e84 100644 --- a/railties/test/application/test_test.rb +++ b/railties/test/application/test_test.rb @@ -9,6 +9,10 @@ module ApplicationTests boot_rails end + def teardown + teardown_app + end + test "truth" do app_file 'test/unit/foo_test.rb', <<-RUBY require 'test_helper' diff --git a/railties/test/generators/plugin_new_generator_test.rb b/railties/test/generators/plugin_new_generator_test.rb index b93e33f61a..b272638026 100644 --- a/railties/test/generators/plugin_new_generator_test.rb +++ b/railties/test/generators/plugin_new_generator_test.rb @@ -112,6 +112,28 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase assert_file "app/assets/javascripts/application.js" end + def test_jquery_is_the_default_javascript_library + run_generator [destination_root, "--mountable"] + assert_file "app/assets/javascripts/application.js" do |contents| + assert_match %r{^//= require jquery}, contents + assert_match %r{^//= require jquery_ujs}, contents + end + assert_file 'Gemfile' do |contents| + assert_match(/^gem 'jquery-rails'/, contents) + end + end + + def test_other_javascript_libraries + run_generator [destination_root, "--mountable", '-j', 'prototype'] + assert_file "app/assets/javascripts/application.js" do |contents| + assert_match %r{^//= require prototype}, contents + assert_match %r{^//= require prototype_ujs}, contents + end + assert_file 'Gemfile' do |contents| + assert_match(/^gem 'prototype-rails'/, contents) + end + end + def test_skip_javascripts run_generator [destination_root, "--skip-javascript", "--mountable"] assert_no_file "app/assets/javascripts/application.js" @@ -148,7 +170,7 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase assert_file "app/views" assert_file "app/helpers" assert_file "config/routes.rb", /Rails.application.routes.draw do/ - assert_file "lib/bukkits/engine.rb", /module Bukkits\n class Engine < Rails::Engine\n end\nend/ + assert_file "lib/bukkits/engine.rb", /module Bukkits\n class Engine < ::Rails::Engine\n end\nend/ assert_file "lib/bukkits.rb", /require "bukkits\/engine"/ end diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index 69208ce4c3..335e639692 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -91,6 +91,9 @@ module TestHelpers module Generation # Build an application by invoking the generator and going through the whole stack. def build_app(options = {}) + @prev_rails_env = ENV['RAILS_ENV'] + ENV['RAILS_ENV'] = 'development' + FileUtils.rm_rf(app_path) FileUtils.cp_r(tmp_path('app_template'), app_path) @@ -115,6 +118,10 @@ module TestHelpers add_to_config 'config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"; config.session_store :cookie_store, :key => "_myapp_session"; config.active_support.deprecation = :log' end + def teardown_app + ENV['RAILS_ENV'] = @prev_rails_env if @prev_rails_env + end + # Make a very basic app, without creating the whole directory structure. # This is faster and simpler than the method above. def make_basic_app diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb index b5b21f9ebe..44cee2b164 100644 --- a/railties/test/railties/engine_test.rb +++ b/railties/test/railties/engine_test.rb @@ -25,6 +25,10 @@ module RailtiesTest end end + def teardown + teardown_app + end + test "Rails::Engine itself does not respond to config" do boot_rails assert !Rails::Engine.respond_to?(:config) diff --git a/railties/test/railties/mounted_engine_test.rb b/railties/test/railties/mounted_engine_test.rb index 47a4753e78..b793a7401f 100644 --- a/railties/test/railties/mounted_engine_test.rb +++ b/railties/test/railties/mounted_engine_test.rb @@ -106,6 +106,10 @@ module ApplicationTests boot_rails end + def teardown + teardown_app + end + def app @app ||= begin require "#{app_path}/config/environment" @@ -116,7 +120,7 @@ module ApplicationTests def reset_script_name! Rails.application.routes.default_url_options = {} end - + def script_name(script_name) Rails.application.routes.default_url_options = {:script_name => script_name} end @@ -171,4 +175,3 @@ module ApplicationTests end end end - diff --git a/railties/test/railties/plugin_ordering_test.rb b/railties/test/railties/plugin_ordering_test.rb index f6ca493fdf..1cfaf557e9 100644 --- a/railties/test/railties/plugin_ordering_test.rb +++ b/railties/test/railties/plugin_ordering_test.rb @@ -12,6 +12,10 @@ module RailtiesTest plugin "c_plugin", "$arr << :c" end + def teardown + teardown_app + end + def boot_rails super require "#{app_path}/config/environment" @@ -69,4 +73,4 @@ module RailtiesTest assert $bar end end -end
\ No newline at end of file +end diff --git a/railties/test/railties/plugin_test.rb b/railties/test/railties/plugin_test.rb index c15ac05103..f307d53cf7 100644 --- a/railties/test/railties/plugin_test.rb +++ b/railties/test/railties/plugin_test.rb @@ -15,6 +15,10 @@ module RailtiesTest end end + def teardown + teardown_app + end + test "Rails::Plugin itself does not respond to config" do boot_rails assert !Rails::Plugin.respond_to?(:config) diff --git a/railties/test/railties/railtie_test.rb b/railties/test/railties/railtie_test.rb index 18fdf59fe3..55f85c7202 100644 --- a/railties/test/railties/railtie_test.rb +++ b/railties/test/railties/railtie_test.rb @@ -11,6 +11,10 @@ module RailtiesTest require "rails/all" end + def teardown + teardown_app + end + def app @app ||= Rails.application end |