aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Gemfile3
-rw-r--r--Gemfile.lock12
-rw-r--r--actionpack/CHANGELOG.md10
-rw-r--r--actionpack/lib/abstract_controller/base.rb8
-rw-r--r--actionpack/lib/action_controller/metal/implicit_render.rb19
-rw-r--r--actionpack/lib/action_controller/metal/strong_parameters.rb16
-rw-r--r--actionpack/lib/action_controller/test_case.rb215
-rw-r--r--actionpack/lib/action_dispatch.rb1
-rw-r--r--actionpack/lib/action_dispatch/http/parameter_filter.rb24
-rw-r--r--actionpack/lib/action_dispatch/journey/router.rb3
-rw-r--r--actionpack/lib/action_dispatch/middleware/cookies.rb14
-rw-r--r--actionpack/lib/action_dispatch/middleware/load_interlock.rb21
-rw-r--r--actionpack/lib/action_dispatch/middleware/params_parser.rb31
-rw-r--r--actionpack/lib/action_dispatch/routing/url_for.rb22
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/routing.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/test_process.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/test_request.rb31
-rw-r--r--actionpack/test/controller/base_test.rb2
-rw-r--r--actionpack/test/controller/caching_test.rb13
-rw-r--r--actionpack/test/controller/filters_test.rb7
-rw-r--r--actionpack/test/controller/helper_test.rb19
-rw-r--r--actionpack/test/controller/mime/respond_to_test.rb100
-rw-r--r--actionpack/test/controller/request/test_request_test.rb6
-rw-r--r--actionpack/test/controller/request_forgery_protection_test.rb3
-rw-r--r--actionpack/test/controller/resources_test.rb4
-rw-r--r--actionpack/test/controller/send_file_test.rb2
-rw-r--r--actionpack/test/controller/test_case_test.rb49
-rw-r--r--actionpack/test/controller/url_rewriter_test.rb3
-rw-r--r--actionpack/test/dispatch/cookies_test.rb6
-rw-r--r--actionpack/test/dispatch/request_test.rb1
-rw-r--r--actionpack/test/dispatch/routing_test.rb5
-rw-r--r--actionpack/test/dispatch/test_request_test.rb20
-rw-r--r--actionview/CHANGELOG.md23
-rw-r--r--actionview/lib/action_view/helpers/asset_url_helper.rb2
-rw-r--r--actionview/lib/action_view/helpers/cache_helper.rb39
-rw-r--r--actionview/lib/action_view/helpers/date_helper.rb12
-rw-r--r--actionview/lib/action_view/helpers/form_options_helper.rb12
-rw-r--r--actionview/lib/action_view/helpers/text_helper.rb12
-rw-r--r--actionview/lib/action_view/renderer/partial_renderer.rb2
-rw-r--r--actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb2
-rw-r--r--actionview/lib/action_view/template.rb17
-rw-r--r--actionview/lib/action_view/template/handlers/erb.rb11
-rw-r--r--actionview/lib/action_view/test_case.rb2
-rw-r--r--actionview/test/actionpack/controller/view_paths_test.rb2
-rw-r--r--actionview/test/template/asset_tag_helper_test.rb5
-rw-r--r--actionview/test/template/render_test.rb17
-rw-r--r--actionview/test/template/template_test.rb32
-rw-r--r--actionview/test/template/text_helper_test.rb12
-rw-r--r--activejob/lib/active_job/arguments.rb21
-rw-r--r--activejob/test/cases/argument_serialization_test.rb7
-rw-r--r--activemodel/README.rdoc2
-rw-r--r--activemodel/lib/active_model/validations.rb6
-rw-r--r--activemodel/lib/active_model/validations/acceptance.rb7
-rw-r--r--activemodel/lib/active_model/validations/exclusion.rb4
-rw-r--r--activemodel/lib/active_model/validations/helper_methods.rb13
-rw-r--r--activemodel/lib/active_model/validations/inclusion.rb6
-rw-r--r--activemodel/lib/active_model/validations/length.rb15
-rw-r--r--activemodel/lib/active_model/validations/with.rb10
-rw-r--r--activemodel/test/cases/errors_test.rb33
-rw-r--r--activemodel/test/cases/helper.rb5
-rw-r--r--activemodel/test/cases/validations/acceptance_validation_test.rb14
-rw-r--r--activemodel/test/cases/validations/exclusion_validation_test.rb17
-rw-r--r--activemodel/test/cases/validations/i18n_validation_test.rb128
-rw-r--r--activemodel/test/cases/validations/with_validation_test.rb2
-rw-r--r--activerecord/CHANGELOG.md47
-rw-r--r--activerecord/lib/active_record/associations/association.rb9
-rw-r--r--activerecord/lib/active_record/associations/association_scope.rb1
-rw-r--r--activerecord/lib/active_record/associations/preloader.rb8
-rw-r--r--activerecord/lib/active_record/associations/singular_association.rb2
-rw-r--r--activerecord/lib/active_record/associations/through_association.rb6
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb5
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb20
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb3
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb3
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb4
-rw-r--r--activerecord/lib/active_record/fixtures.rb4
-rw-r--r--activerecord/lib/active_record/log_subscriber.rb19
-rw-r--r--activerecord/lib/active_record/migration.rb3
-rw-r--r--activerecord/lib/active_record/migration/command_recorder.rb12
-rw-r--r--activerecord/lib/active_record/railties/databases.rake15
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb5
-rw-r--r--activerecord/lib/active_record/relation/merger.rb4
-rw-r--r--activerecord/lib/active_record/table_metadata.rb2
-rw-r--r--activerecord/lib/active_record/type/decimal.rb2
-rw-r--r--activerecord/lib/active_record/validations.rb1
-rw-r--r--activerecord/lib/active_record/validations/absence.rb24
-rw-r--r--activerecord/lib/active_record/validations/length.rb5
-rw-r--r--activerecord/lib/active_record/validations/presence.rb14
-rw-r--r--activerecord/test/cases/adapters/postgresql/money_test.rb2
-rw-r--r--activerecord/test/cases/adapters/postgresql/schema_test.rb5
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb28
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb7
-rw-r--r--activerecord/test/cases/enum_test.rb6
-rw-r--r--activerecord/test/cases/migration/columns_test.rb7
-rw-r--r--activerecord/test/cases/migration/command_recorder_test.rb10
-rw-r--r--activerecord/test/cases/migration/foreign_key_test.rb31
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb10
-rw-r--r--activerecord/test/cases/relations_test.rb19
-rw-r--r--activerecord/test/cases/schema_dumper_test.rb4
-rw-r--r--activerecord/test/cases/touch_later_test.rb21
-rw-r--r--activerecord/test/cases/validations/absence_validation_test.rb75
-rw-r--r--activerecord/test/fixtures/books.yml5
-rw-r--r--activerecord/test/fixtures/nodes.yml29
-rw-r--r--activerecord/test/fixtures/trees.yml3
-rw-r--r--activerecord/test/models/node.rb5
-rw-r--r--activerecord/test/models/post.rb16
-rw-r--r--activerecord/test/models/tree.rb3
-rw-r--r--activerecord/test/schema/schema.rb11
-rw-r--r--activesupport/CHANGELOG.md9
-rw-r--r--activesupport/lib/active_support/concurrency/share_lock.rb138
-rw-r--r--activesupport/lib/active_support/core_ext/module/concerning.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/object/duplicable.rb6
-rw-r--r--activesupport/lib/active_support/dependencies.rb98
-rw-r--r--activesupport/lib/active_support/dependencies/interlock.rb41
-rw-r--r--activesupport/lib/active_support/hash_with_indifferent_access.rb14
-rw-r--r--activesupport/lib/active_support/ordered_options.rb8
-rw-r--r--activesupport/lib/active_support/testing/method_call_assertions.rb35
-rw-r--r--activesupport/test/abstract_unit.rb6
-rw-r--r--activesupport/test/caching_test.rb78
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb42
-rw-r--r--activesupport/test/core_ext/time_with_zone_test.rb25
-rw-r--r--activesupport/test/dependencies_test.rb11
-rw-r--r--activesupport/test/deprecation_test.rb16
-rw-r--r--activesupport/test/hash_with_indifferent_access_test.rb11
-rw-r--r--activesupport/test/log_subscriber_test.rb9
-rw-r--r--activesupport/test/multibyte_unicode_database_test.rb5
-rw-r--r--activesupport/test/testing/method_call_assertions_test.rb98
-rw-r--r--activesupport/test/time_zone_test.rb1
-rw-r--r--activesupport/test/xml_mini_test.rb1
-rw-r--r--guides/assets/images/getting_started/rails_welcome.pngbin94542 -> 142320 bytes
-rw-r--r--guides/source/action_controller_overview.md2
-rw-r--r--guides/source/action_mailer_basics.md18
-rw-r--r--guides/source/action_view_overview.md12
-rw-r--r--guides/source/active_job_basics.md7
-rw-r--r--guides/source/active_record_migrations.md16
-rw-r--r--guides/source/active_record_validations.md5
-rw-r--r--guides/source/active_support_instrumentation.md11
-rw-r--r--guides/source/association_basics.md18
-rw-r--r--guides/source/configuring.md2
-rw-r--r--guides/source/contributing_to_ruby_on_rails.md6
-rw-r--r--guides/source/generators.md8
-rw-r--r--guides/source/getting_started.md12
-rw-r--r--guides/source/i18n.md2
-rw-r--r--guides/source/rails_on_rack.md18
-rw-r--r--guides/source/security.md23
-rw-r--r--railties/CHANGELOG.md8
-rw-r--r--railties/lib/rails/application/default_middleware_stack.rb30
-rw-r--r--railties/lib/rails/application/finisher.rb6
-rw-r--r--railties/lib/rails/commands/server.rb15
-rw-r--r--railties/lib/rails/generators/actions.rb18
-rw-r--r--railties/lib/rails/generators/named_base.rb4
-rw-r--r--railties/lib/rails/generators/rails/app/app_generator.rb4
-rw-r--r--railties/lib/rails/generators/rails/plugin/plugin_generator.rb4
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/test/integration/navigation_test.rb4
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb2
-rw-r--r--railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb2
-rw-r--r--railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb2
-rw-r--r--railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb2
-rw-r--r--railties/lib/rails/test_unit/minitest_plugin.rb6
-rw-r--r--railties/lib/rails/test_unit/reporter.rb12
-rw-r--r--railties/test/application/asset_debugging_test.rb2
-rw-r--r--railties/test/application/assets_test.rb4
-rw-r--r--railties/test/application/initializers/frameworks_test.rb4
-rw-r--r--railties/test/application/middleware_test.rb33
-rw-r--r--railties/test/application/rake/dbs_test.rb38
-rw-r--r--railties/test/application/rake/migrations_test.rb98
-rw-r--r--railties/test/application/rake/notes_test.rb6
-rw-r--r--railties/test/application/rake_test.rb74
-rw-r--r--railties/test/application/runner_test.rb20
-rw-r--r--railties/test/application/test_runner_test.rb2
-rw-r--r--railties/test/generators/actions_test.rb8
-rw-r--r--railties/test/generators/plugin_generator_test.rb2
-rw-r--r--railties/test/generators/scaffold_controller_generator_test.rb11
-rw-r--r--railties/test/generators/scaffold_generator_test.rb14
-rw-r--r--railties/test/generators/shared_generator_tests.rb2
-rw-r--r--railties/test/test_unit/reporter_test.rb2
176 files changed, 2013 insertions, 921 deletions
diff --git a/Gemfile b/Gemfile
index 78224f60ed..de4159d254 100644
--- a/Gemfile
+++ b/Gemfile
@@ -5,6 +5,9 @@ gemspec
# We need a newish Rake since Active Job sets its test tasks' descriptions.
gem 'rake', '>= 10.3'
+# Active Job depends on the URI::GID::MissingModelIDError, which isn't released yet.
+gem 'globalid', github: 'rails/globalid'
+
# This needs to be with require false as it is
# loaded after loading the test library to
# ensure correct loading order
diff --git a/Gemfile.lock b/Gemfile.lock
index 2140881170..960a77af92 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -26,6 +26,13 @@ GIT
arel (7.0.0.alpha)
GIT
+ remote: git://github.com/rails/globalid.git
+ revision: 4df66fb9e9f0c832d29119aa8bc30be55a614b71
+ specs:
+ globalid (0.3.5)
+ activesupport (>= 4.1.0)
+
+GIT
remote: git://github.com/rails/jquery-rails.git
revision: 272abdd319bb3381b23182b928b25320590096b0
branch: master
@@ -138,8 +145,6 @@ GEM
delayed_job (>= 3.0, < 4.1)
erubis (2.7.0)
execjs (2.3.0)
- globalid (0.3.3)
- activesupport (>= 4.1.0)
hitimes (1.2.2)
hitimes (1.2.2-x86-mingw32)
i18n (0.7.0)
@@ -272,6 +277,7 @@ DEPENDENCIES
dalli (>= 2.2.1)
delayed_job
delayed_job_active_record
+ globalid!
jquery-rails!
json
kindlerb (= 0.1.1)
@@ -308,4 +314,4 @@ DEPENDENCIES
w3c_validators
BUNDLED WITH
- 1.10.4
+ 1.10.5
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index cb5e7516fb..46856ffc5d 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,3 +1,13 @@
+* Add ability to filter parameters based on parent keys.
+
+ # matches {credit_card: {code: "xxxx"}}
+ # doesn't match {file: { code: "xxxx"}}
+ config.filter_parameters += [ "credit_card.code" ]
+
+ See #13897.
+
+ *Guillaume Malette*
+
* Deprecate passing first parameter as `Hash` and default status code for `head` method.
*Mehmet Emin İNAÇ*
diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb
index c95b9a4097..ebd02bd9a1 100644
--- a/actionpack/lib/abstract_controller/base.rb
+++ b/actionpack/lib/abstract_controller/base.rb
@@ -88,7 +88,7 @@ module AbstractController
# Returns the full controller name, underscored, without the ending Controller.
#
# class MyApp::MyPostsController < AbstractController::Base
- # end
+ #
# end
#
# MyApp::MyPostsController.controller_path # => "my_app/my_posts"
@@ -148,9 +148,6 @@ module AbstractController
#
# ==== Parameters
# * <tt>action_name</tt> - The name of an action to be tested
- #
- # ==== Returns
- # * <tt>TrueClass</tt>, <tt>FalseClass</tt>
def available_action?(action_name)
_find_action_name(action_name).present?
end
@@ -171,9 +168,6 @@ module AbstractController
# ==== Parameters
# * <tt>name</tt> - The name of an action to be tested
#
- # ==== Returns
- # * <tt>TrueClass</tt>, <tt>FalseClass</tt>
- #
# :api: private
def action_method?(name)
self.class.action_methods.include?(name)
diff --git a/actionpack/lib/action_controller/metal/implicit_render.rb b/actionpack/lib/action_controller/metal/implicit_render.rb
index d66b2214ce..17fcc2fa02 100644
--- a/actionpack/lib/action_controller/metal/implicit_render.rb
+++ b/actionpack/lib/action_controller/metal/implicit_render.rb
@@ -3,12 +3,27 @@ module ActionController
include BasicImplicitRender
+ # Renders the template corresponding to the controller action, if it exists.
+ # The action name, format, and variant are all taken into account.
+ # For example, the "new" action with an HTML format and variant "phone"
+ # would try to render the <tt>new.html+phone.erb</tt> template.
+ #
+ # If no template is found <tt>ActionController::BasicImplicitRender</tt>'s implementation is called, unless
+ # a block is passed. In that case, it will override the super implementation.
+ #
+ # default_render do
+ # head 404 # No template was found
+ # end
def default_render(*args)
if template_exists?(action_name.to_s, _prefixes, variants: request.variant)
render(*args)
else
- logger.info "No template found for #{self.class.name}\##{action_name}, rendering head :no_content" if logger
- super
+ if block_given?
+ yield(*args)
+ else
+ logger.info "No template found for #{self.class.name}\##{action_name}, rendering head :no_content" if logger
+ super
+ end
end
end
diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb
index c98e937423..09867e2407 100644
--- a/actionpack/lib/action_controller/metal/strong_parameters.rb
+++ b/actionpack/lib/action_controller/metal/strong_parameters.rb
@@ -11,9 +11,9 @@ module ActionController
#
# params = ActionController::Parameters.new(a: {})
# params.fetch(:b)
- # # => ActionController::ParameterMissing: param not found: b
+ # # => ActionController::ParameterMissing: param is missing or the value is empty: b
# params.require(:a)
- # # => ActionController::ParameterMissing: param not found: a
+ # # => ActionController::ParameterMissing: param is missing or the value is empty: a
class ParameterMissing < KeyError
attr_reader :param # :nodoc:
@@ -23,11 +23,13 @@ module ActionController
end
end
- # Raised when a supplied parameter is not expected.
+ # Raised when a supplied parameter is not expected and
+ # ActionController::Parameters.action_on_unpermitted_parameters
+ # is set to <tt>:raise</tt>.
#
# params = ActionController::Parameters.new(a: "123", b: "456")
# params.permit(:c)
- # # => ActionController::UnpermittedParameters: found unexpected keys: a, b
+ # # => ActionController::UnpermittedParameters: found unpermitted parameters: a, b
class UnpermittedParameters < IndexError
attr_reader :params # :nodoc:
@@ -236,10 +238,10 @@ module ActionController
# # => {"name"=>"Francesco"}
#
# ActionController::Parameters.new(person: nil).require(:person)
- # # => ActionController::ParameterMissing: param not found: person
+ # # => ActionController::ParameterMissing: param is missing or the value is empty: person
#
# ActionController::Parameters.new(person: {}).require(:person)
- # # => ActionController::ParameterMissing: param not found: person
+ # # => ActionController::ParameterMissing: param is missing or the value is empty: person
def require(key)
value = self[key]
if value.present? || value == false
@@ -356,7 +358,7 @@ module ActionController
#
# params = ActionController::Parameters.new(person: { name: 'Francesco' })
# params.fetch(:person) # => {"name"=>"Francesco"}
- # params.fetch(:none) # => ActionController::ParameterMissing: param not found: none
+ # params.fetch(:none) # => ActionController::ParameterMissing: param is missing or the value is empty: none
# params.fetch(:none, 'Francesco') # => "Francesco"
# params.fetch(:none) { 'Francesco' } # => "Francesco"
def fetch(key, *args)
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index 96f161fb09..43c481339a 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -10,27 +10,45 @@ module ActionController
DEFAULT_ENV = ActionDispatch::TestRequest::DEFAULT_ENV.dup
DEFAULT_ENV.delete 'PATH_INFO'
- def initialize(env = {})
- super
+ def self.new_session
+ TestSession.new
+ end
+
+ # Create a new test request with default `env` values
+ def self.create
+ env = {}
+ env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
+ env["rack.request.cookie_hash"] = {}.with_indifferent_access
+ new(default_env.merge(env), new_session)
+ end
+
+ def self.default_env
+ DEFAULT_ENV
+ end
+ private_class_method :default_env
+
+ def initialize(env, session)
+ super(env)
- self.session = TestSession.new
+ self.session = session
self.session_options = TestSession::DEFAULT_OPTIONS
end
+ def query_string=(string)
+ @env[Rack::QUERY_STRING] = string
+ end
+
+ def request_parameters=(params)
+ @env["action_dispatch.request.request_parameters"] = params
+ end
+
def assign_parameters(routes, controller_path, action, parameters = {})
parameters = parameters.symbolize_keys
- extra_keys = routes.extra_keys(parameters.merge(:controller => controller_path, :action => action))
- non_path_parameters = get? ? query_parameters : request_parameters
+ generated_path, extra_keys = routes.generate_extras(parameters.merge(:controller => controller_path, :action => action))
+ non_path_parameters = {}
+ path_parameters = {}
parameters.each do |key, value|
- if value.is_a?(Array) && (value.frozen? || value.any?(&:frozen?))
- value = value.map{ |v| v.duplicable? ? v.dup : v }
- elsif value.is_a?(Hash) && (value.frozen? || value.any?{ |k,v| v.frozen? })
- value = Hash[value.map{ |k,v| [k, v.duplicable? ? v.dup : v] }]
- elsif value.frozen? && value.duplicable?
- value = value.dup
- end
-
if extra_keys.include?(key) || key == :action || key == :controller
non_path_parameters[key] = value
else
@@ -44,56 +62,80 @@ module ActionController
end
end
- path_parameters[:controller] = controller_path
- path_parameters[:action] = action
+ if get?
+ if self.query_string.blank?
+ self.query_string = non_path_parameters.to_query
+ end
+ else
+ if ENCODER.should_multipart?(non_path_parameters)
+ @env['CONTENT_TYPE'] = ENCODER.content_type
+ data = ENCODER.build_multipart non_path_parameters
+ else
+ @env['CONTENT_TYPE'] ||= 'application/x-www-form-urlencoded'
+
+ # FIXME: setting `request_parametes` is normally handled by the
+ # params parser middleware, and we should remove this roundtripping
+ # when we switch to caling `call` on the controller
+
+ case content_mime_type.ref
+ when :json
+ data = ActiveSupport::JSON.encode(non_path_parameters)
+ params = ActiveSupport::JSON.decode(data).with_indifferent_access
+ self.request_parameters = params
+ when :xml
+ data = non_path_parameters.to_xml
+ params = Hash.from_xml(data)['hash']
+ self.request_parameters = params
+ when :url_encoded_form
+ data = non_path_parameters.to_query
+ else
+ raise "Unknown Content-Type: #{content_type}"
+ end
+ end
- # Clear the combined params hash in case it was already referenced.
- @env.delete("action_dispatch.request.parameters")
+ @env['CONTENT_LENGTH'] = data.length.to_s
+ @env['rack.input'] = StringIO.new(data)
+ end
- # Clear the filter cache variables so they're not stale
- @filtered_parameters = @filtered_env = @filtered_path = nil
+ @env["PATH_INFO"] ||= generated_path
+ path_parameters[:controller] = controller_path
+ path_parameters[:action] = action
- data = request_parameters.to_query
- @env['CONTENT_LENGTH'] = data.length.to_s
- @env['rack.input'] = StringIO.new(data)
+ self.path_parameters = path_parameters
end
- def recycle!
- @formats = nil
- @env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
- @env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
- @method = @request_method = nil
- @fullpath = @ip = @remote_ip = @protocol = 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
+ ENCODER = Class.new do
+ include Rack::Test::Utils
+
+ def should_multipart?(params)
+ # FIXME: lifted from Rack-Test. We should push this separation upstream
+ multipart = false
+ query = lambda { |value|
+ case value
+ when Array
+ value.each(&query)
+ when Hash
+ value.values.each(&query)
+ when Rack::Test::UploadedFile
+ multipart = true
+ end
+ }
+ params.values.each(&query)
+ multipart
+ end
- private
+ public :build_multipart
- def default_env
- DEFAULT_ENV
- end
+ def content_type
+ "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}"
+ end
+ end.new
end
class TestResponse < ActionDispatch::TestResponse
- def recycle!
- initialize
- end
end
class LiveTestResponse < Live::Response
- def recycle!
- @body = nil
- initialize
- end
-
def body
@body ||= super
end
@@ -317,7 +359,9 @@ module ActionController
# Note that the request method is not verified. The different methods are
# available to make the tests more expressive.
def get(action, *args)
- process_with_kwargs("GET", action, *args)
+ res = process_with_kwargs("GET", action, *args)
+ cookies.update res.cookies
+ res
end
# Simulate a POST request with the given parameters and set/volley the response.
@@ -365,19 +409,6 @@ 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[hash_or_array_or_value.map{|key, value| [key, paramify_values(value)] }]
- when Array
- hash_or_array_or_value.map {|i| paramify_values(i)}
- when Rack::Test::UploadedFile, ActionDispatch::Http::UploadedFile
- hash_or_array_or_value
- else
- hash_or_array_or_value.to_param
- end
- end
-
# Simulate a HTTP request to +action+ by specifying request method,
# parameters and set/volley the response.
#
@@ -437,10 +468,6 @@ module ActionController
parameters ||= {}
- # Ensure that numbers and symbols passed as params are converted to
- # proper params, as is the case when engaging rack.
- parameters = paramify_values(parameters) if html_format?(parameters)
-
if format.present?
parameters[:format] = format
end
@@ -451,8 +478,13 @@ module ActionController
@controller.extend(Testing::Functional)
end
- @request.recycle!
- @response.recycle!
+ self.cookies.update @request.cookies
+ @request.env['HTTP_COOKIE'] = cookies.to_header
+ @request.env['action_dispatch.cookies'] = nil
+
+ @request = TestRequest.new scrub_env!(@request.env), @request.session
+ @response = build_response @response_klass
+ @response.request = @request
@controller.recycle!
@request.env['REQUEST_METHOD'] = http_method
@@ -474,14 +506,17 @@ module ActionController
@controller.request = @request
@controller.response = @response
- build_request_uri(controller_class_name, action, parameters)
+ @request.env["SCRIPT_NAME"] ||= @controller.config.relative_url_root
@controller.recycle!
@controller.process(action)
+ @request.env.delete 'HTTP_COOKIE'
+
if cookies = @request.env['action_dispatch.cookies']
unless @response.committed?
cookies.write(@response)
+ self.cookies.update(cookies.instance_variable_get(:@cookies))
end
end
@response.prepare!
@@ -496,6 +531,7 @@ module ActionController
@request.env.delete 'HTTP_X_REQUESTED_WITH'
@request.env.delete 'HTTP_ACCEPT'
end
+ @request.query_string = ''
@response
end
@@ -503,11 +539,11 @@ module ActionController
def setup_controller_request_and_response
@controller = nil unless defined? @controller
- response_klass = TestResponse
+ @response_klass = TestResponse
if klass = self.class.controller_class
if klass < ActionController::Live
- response_klass = LiveTestResponse
+ @response_klass = LiveTestResponse
end
unless @controller
begin
@@ -518,8 +554,8 @@ module ActionController
end
end
- @request = build_request
- @response = build_response response_klass
+ @request = TestRequest.create
+ @response = build_response @response_klass
@response.request = @request
if @controller
@@ -528,10 +564,6 @@ module ActionController
end
end
- def build_request
- TestRequest.new
- end
-
def build_response(klass)
klass.new
end
@@ -545,6 +577,14 @@ module ActionController
private
+ def scrub_env!(env)
+ env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
+ env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
+ env.delete 'action_dispatch.request.query_parameters'
+ env.delete 'action_dispatch.request.request_parameters'
+ env
+ end
+
def process_with_kwargs(http_method, action, *args)
if kwarg_request?(args)
args.first.merge!(method: http_method)
@@ -591,23 +631,6 @@ module ActionController
end
end
- def build_request_uri(controller_class_name, action, parameters)
- unless @request.env["PATH_INFO"]
- options = @controller.respond_to?(:url_options) ? @controller.__send__(:url_options).merge(parameters) : parameters
- options.update(
- :controller => controller_class_name,
- :action => action,
- :relative_url_root => nil,
- :_recall => @request.path_parameters)
-
- url, query_string = @routes.path_for(options).split("?", 2)
-
- @request.env["SCRIPT_NAME"] = @controller.config.relative_url_root
- @request.env["PATH_INFO"] = url
- @request.env["QUERY_STRING"] = query_string || ""
- end
- end
-
def html_format?(parameters)
return true unless parameters.key?(:format)
Mime.fetch(parameters[:format]) { Mime['html'] }.html?
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index dcd3ee0644..f6336c8c7a 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -52,6 +52,7 @@ module ActionDispatch
autoload :DebugExceptions
autoload :ExceptionWrapper
autoload :Flash
+ autoload :LoadInterlock
autoload :ParamsParser
autoload :PublicExceptions
autoload :Reloader
diff --git a/actionpack/lib/action_dispatch/http/parameter_filter.rb b/actionpack/lib/action_dispatch/http/parameter_filter.rb
index df4b073a17..6e058b829e 100644
--- a/actionpack/lib/action_dispatch/http/parameter_filter.rb
+++ b/actionpack/lib/action_dispatch/http/parameter_filter.rb
@@ -30,36 +30,46 @@ module ActionDispatch
when Regexp
regexps << item
else
- strings << item.to_s
+ strings << Regexp.escape(item.to_s)
end
end
+ deep_regexps, regexps = regexps.partition { |r| r.to_s.include?("\\.") }
+ deep_strings, strings = strings.partition { |s| s.include?("\\.") }
+
regexps << Regexp.new(strings.join('|'), true) unless strings.empty?
- new regexps, blocks
+ deep_regexps << Regexp.new(deep_strings.join('|'), true) unless deep_strings.empty?
+
+ new regexps, deep_regexps, blocks
end
- attr_reader :regexps, :blocks
+ attr_reader :regexps, :deep_regexps, :blocks
- def initialize(regexps, blocks)
+ def initialize(regexps, deep_regexps, blocks)
@regexps = regexps
+ @deep_regexps = deep_regexps.any? ? deep_regexps : nil
@blocks = blocks
end
- def call(original_params)
+ def call(original_params, parents = [])
filtered_params = {}
original_params.each do |key, value|
+ parents.push(key) if deep_regexps
if regexps.any? { |r| key =~ r }
value = FILTERED
+ elsif deep_regexps && (joined = parents.join('.')) && deep_regexps.any? { |r| joined =~ r }
+ value = FILTERED
elsif value.is_a?(Hash)
- value = call(value)
+ value = call(value, parents)
elsif value.is_a?(Array)
- value = value.map { |v| v.is_a?(Hash) ? call(v) : v }
+ value = value.map { |v| v.is_a?(Hash) ? call(v, parents) : v }
elsif blocks.any?
key = key.dup if key.duplicable?
value = value.dup if value.duplicable?
blocks.each { |b| b.call(key, value) }
end
+ parents.pop if deep_regexps
filtered_params[key] = value
end
diff --git a/actionpack/lib/action_dispatch/journey/router.rb b/actionpack/lib/action_dispatch/journey/router.rb
index cc4bd6105d..b84aad8eb6 100644
--- a/actionpack/lib/action_dispatch/journey/router.rb
+++ b/actionpack/lib/action_dispatch/journey/router.rb
@@ -121,7 +121,8 @@ module ActionDispatch
end
def match_head_routes(routes, req)
- head_routes = match_routes(routes, req)
+ verb_specific_routes = routes.reject { |route| route.verb == // }
+ head_routes = match_routes(verb_specific_routes, req)
if head_routes.empty?
begin
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index dd1f140051..07d97bd6bd 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -8,7 +8,7 @@ require 'active_support/json'
module ActionDispatch
class Request < Rack::Request
def cookie_jar
- env['action_dispatch.cookies'] ||= Cookies::CookieJar.build(self)
+ env['action_dispatch.cookies'] ||= Cookies::CookieJar.build(env, host, ssl?, cookies)
end
end
@@ -228,16 +228,12 @@ module ActionDispatch
}
end
- def self.build(request)
- env = request.env
+ def self.build(env, host, secure, cookies)
key_generator = env[GENERATOR_KEY]
options = options_for_env env
- host = request.host
- secure = request.ssl?
-
new(key_generator, host, secure, options).tap do |hash|
- hash.update(request.cookies)
+ hash.update(cookies)
end
end
@@ -283,6 +279,10 @@ module ActionDispatch
self
end
+ def to_header
+ @cookies.map { |k,v| "#{k}=#{v}" }.join ';'
+ end
+
def handle_options(options) #:nodoc:
options[:path] ||= "/"
diff --git a/actionpack/lib/action_dispatch/middleware/load_interlock.rb b/actionpack/lib/action_dispatch/middleware/load_interlock.rb
new file mode 100644
index 0000000000..07f498319c
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/load_interlock.rb
@@ -0,0 +1,21 @@
+require 'active_support/dependencies'
+require 'rack/body_proxy'
+
+module ActionDispatch
+ class LoadInterlock
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ interlock = ActiveSupport::Dependencies.interlock
+ interlock.start_running
+ response = @app.call(env)
+ body = Rack::BodyProxy.new(response[2]) { interlock.done_running }
+ response[2] = body
+ response
+ ensure
+ interlock.done_running unless body
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/params_parser.rb b/actionpack/lib/action_dispatch/middleware/params_parser.rb
index 29d43faeed..e2b3b06fd8 100644
--- a/actionpack/lib/action_dispatch/middleware/params_parser.rb
+++ b/actionpack/lib/action_dispatch/middleware/params_parser.rb
@@ -13,40 +13,35 @@ module ActionDispatch
end
end
- DEFAULT_PARSERS = { Mime::JSON => :json }
+ DEFAULT_PARSERS = {
+ Mime::JSON => lambda { |raw_post|
+ data = ActiveSupport::JSON.decode(raw_post)
+ data = {:_json => data} unless data.is_a?(Hash)
+ Request::Utils.deep_munge(data).with_indifferent_access
+ }
+ }
def initialize(app, parsers = {})
@app, @parsers = app, DEFAULT_PARSERS.merge(parsers)
end
def call(env)
- if params = parse_formatted_parameters(env)
- env["action_dispatch.request.request_parameters"] = params
- end
+ default = env["action_dispatch.request.request_parameters"]
+ env["action_dispatch.request.request_parameters"] = parse_formatted_parameters(env, @parsers, default)
@app.call(env)
end
private
- def parse_formatted_parameters(env)
+ def parse_formatted_parameters(env, parsers, default)
request = Request.new(env)
- return false if request.content_length.zero?
+ return default if request.content_length.zero?
- strategy = @parsers[request.content_mime_type]
+ strategy = parsers.fetch(request.content_mime_type) { return default }
- return false unless strategy
+ strategy.call(request.raw_post)
- case strategy
- when Proc
- strategy.call(request.raw_post)
- when :json
- data = ActiveSupport::JSON.decode(request.raw_post)
- data = {:_json => data} unless data.is_a?(Hash)
- Request::Utils.deep_munge(data).with_indifferent_access
- else
- false
- end
rescue => e # JSON or Ruby code block errors
logger(env).debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}"
diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb
index eb554ec383..8379d089df 100644
--- a/actionpack/lib/action_dispatch/routing/url_for.rb
+++ b/actionpack/lib/action_dispatch/routing/url_for.rb
@@ -52,9 +52,11 @@ module ActionDispatch
# argument.
#
# For convenience reasons, mailers provide a shortcut for ActionController::UrlFor#url_for.
- # So within mailers, you only have to type 'url_for' instead of 'ActionController::UrlFor#url_for'
- # in full. However, mailers don't have hostname information, and that's why you'll still
- # have to specify the <tt>:host</tt> argument when generating URLs in mailers.
+ # So within mailers, you only have to type +url_for+ instead of 'ActionController::UrlFor#url_for'
+ # in full. However, mailers don't have hostname information, and you still have to provide
+ # the +:host+ argument or set the default host that will be used in all mailers using the
+ # configuration option +config.action_mailer.default_url_options+. For more information on
+ # url_for in mailers read the ActionMailer#Base documentation.
#
#
# == URL generation for named routes
@@ -147,6 +149,20 @@ module ActionDispatch
# # => 'http://somehost.org/myapp/tasks/testing'
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', script_name: "/myapp", only_path: true
# # => '/myapp/tasks/testing'
+ #
+ # Missing routes keys may be filled in from the current request's parameters
+ # (e.g. +:controller+, +:action+, +:id+ and any other parameters that are
+ # placed in the path). Given that the current action has been reached
+ # through `GET /users/1`:
+ #
+ # url_for(only_path: true) # => '/users/1'
+ # url_for(only_path: true, action: 'edit') # => '/users/1/edit'
+ # url_for(only_path: true, action: 'edit', id: 2) # => '/users/2/edit'
+ #
+ # Notice that no +:id+ parameter was provided to the first +url_for+ call
+ # and the helper used the one from the route's path. Any path parameter
+ # implicitly used by +url_for+ can always be overwritten like shown on the
+ # last +url_for+ calls.
def url_for(options = nil)
case options
when nil
diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
index c94eea9134..543c7b78a1 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
@@ -183,7 +183,7 @@ module ActionDispatch
end
# Assume given controller
- request = ActionController::TestRequest.new
+ request = ActionController::TestRequest.create
if path =~ %r{://}
fail_on(URI::InvalidURIError, msg) do
diff --git a/actionpack/lib/action_dispatch/testing/test_process.rb b/actionpack/lib/action_dispatch/testing/test_process.rb
index 415ef80cd2..494644cd46 100644
--- a/actionpack/lib/action_dispatch/testing/test_process.rb
+++ b/actionpack/lib/action_dispatch/testing/test_process.rb
@@ -19,7 +19,7 @@ module ActionDispatch
end
def cookies
- @request.cookie_jar
+ @cookie_jar ||= Cookies::CookieJar.build(@request.env, @request.host, @request.ssl?, @request.cookies)
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 4b9a088265..ad1a7f7109 100644
--- a/actionpack/lib/action_dispatch/testing/test_request.rb
+++ b/actionpack/lib/action_dispatch/testing/test_request.rb
@@ -4,19 +4,22 @@ require 'rack/utils'
module ActionDispatch
class TestRequest < Request
DEFAULT_ENV = Rack::MockRequest.env_for('/',
- 'HTTP_HOST' => 'test.host',
- 'REMOTE_ADDR' => '0.0.0.0',
- 'HTTP_USER_AGENT' => 'Rails Testing'
+ 'HTTP_HOST' => 'test.host',
+ 'REMOTE_ADDR' => '0.0.0.0',
+ 'HTTP_USER_AGENT' => 'Rails Testing',
)
- def self.new(env = {})
- super
+ # Create a new test request with default `env` values
+ def self.create(env = {})
+ env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
+ env["rack.request.cookie_hash"] ||= {}.with_indifferent_access
+ new(default_env.merge(env))
end
- def initialize(env = {})
- env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
- super(default_env.merge(env))
+ def self.default_env
+ DEFAULT_ENV
end
+ private_class_method :default_env
def request_method=(method)
@env['REQUEST_METHOD'] = method.to_s.upcase
@@ -62,17 +65,5 @@ module ActionDispatch
@env.delete('action_dispatch.request.accepts')
@env['HTTP_ACCEPT'] = Array(mime_types).collect(&:to_s).join(",")
end
-
- alias :rack_cookies :cookies
-
- def cookies
- @cookies ||= {}.with_indifferent_access
- end
-
- private
-
- def default_env
- DEFAULT_ENV
- end
end
end
diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb
index 3240185414..b7fe253de7 100644
--- a/actionpack/test/controller/base_test.rb
+++ b/actionpack/test/controller/base_test.rb
@@ -127,8 +127,6 @@ class PerformActionTest < ActionController::TestCase
# a more accurate simulation of what happens in "real life".
@controller.logger = ActiveSupport::Logger.new(nil)
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
@request.host = "www.nextangle.com"
end
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index f21dd87400..5698159eba 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -22,8 +22,6 @@ class FragmentCachingMetalTest < ActionController::TestCase
@controller.perform_caching = true
@controller.cache_store = @store
@params = { controller: 'posts', action: 'index' }
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
@controller.params = @params
@controller.request = @request
@controller.response = @response
@@ -52,8 +50,6 @@ class FragmentCachingTest < ActionController::TestCase
@controller.perform_caching = true
@controller.cache_store = @store
@params = {:controller => 'posts', :action => 'index'}
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
@controller.params = @params
@controller.request = @request
@controller.response = @response
@@ -166,6 +162,8 @@ class FunctionalCachingController < CachingController
end
def formatted_fragment_cached_with_variant
+ request.variant = :phone if params[:v] == "phone"
+
respond_to do |format|
format.html.phone
format.html
@@ -183,8 +181,6 @@ class FunctionalFragmentCachingTest < ActionController::TestCase
@controller = FunctionalCachingController.new
@controller.perform_caching = true
@controller.cache_store = @store
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
end
def test_fragment_caching
@@ -268,9 +264,7 @@ CACHED
def test_fragment_caching_with_variant
- @request.variant = :phone
-
- get :formatted_fragment_cached_with_variant, format: "html"
+ get :formatted_fragment_cached_with_variant, format: "html", params: { v: :phone }
assert_response :success
expected_body = "<body>\n<p>PHONE</p>\n</body>\n"
@@ -381,6 +375,7 @@ class AutomaticCollectionCacheTest < ActionController::TestCase
@controller.perform_caching = true
@controller.partial_rendered_times = 0
@controller.cache_store = ActiveSupport::Cache::MemoryStore.new
+ ActionView::PartialRenderer.collection_cache = @controller.cache_store
end
def test_collection_fetches_cached_views
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index 9b0487841f..8a6a51c263 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -757,9 +757,8 @@ class FilterTest < ActionController::TestCase
def test_dynamic_dispatch
%w(foo bar baz).each do |action|
- request = ActionController::TestRequest.new
- request.query_parameters[:choose] = action
- response = DynamicDispatchController.action(action).call(request.env).last
+ @request.query_parameters[:choose] = action
+ response = DynamicDispatchController.action(action).call(@request.env).last
assert_equal action, response.body
end
end
@@ -839,8 +838,6 @@ class FilterTest < ActionController::TestCase
private
def test_process(controller, action = "show")
@controller = controller.is_a?(Class) ? controller.new : controller
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
process(action)
end
diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb
index e263ed341f..a96cfa3bf4 100644
--- a/actionpack/test/controller/helper_test.rb
+++ b/actionpack/test/controller/helper_test.rb
@@ -73,14 +73,8 @@ module LocalAbcHelper
end
class HelperPathsTest < ActiveSupport::TestCase
- def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- end
-
def test_helpers_paths_priority
- request = ActionController::TestRequest.new
- responses = HelpersPathsController.action(:index).call(request.env)
+ responses = HelpersPathsController.action(:index).call(ActionController::TestRequest::DEFAULT_ENV.dup)
# helpers1_pack was given as a second path, so pack1_helper should be
# included as the second one
@@ -141,8 +135,7 @@ class HelperTest < ActiveSupport::TestCase
end
def call_controller(klass, action)
- request = ActionController::TestRequest.new
- klass.action(action).call(request.env)
+ klass.action(action).call(ActionController::TestRequest::DEFAULT_ENV.dup)
end
def test_helper_for_nested_controller
@@ -249,7 +242,7 @@ class HelperTest < ActiveSupport::TestCase
end
-class IsolatedHelpersTest < ActiveSupport::TestCase
+class IsolatedHelpersTest < ActionController::TestCase
class A < ActionController::Base
def index
render :inline => '<%= shout %>'
@@ -273,13 +266,11 @@ class IsolatedHelpersTest < ActiveSupport::TestCase
end
def call_controller(klass, action)
- request = ActionController::TestRequest.new
- klass.action(action).call(request.env)
+ klass.action(action).call(@request.env)
end
def setup
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
+ super
@request.action = 'index'
end
diff --git a/actionpack/test/controller/mime/respond_to_test.rb b/actionpack/test/controller/mime/respond_to_test.rb
index 7aef8a50ce..71660c87a2 100644
--- a/actionpack/test/controller/mime/respond_to_test.rb
+++ b/actionpack/test/controller/mime/respond_to_test.rb
@@ -4,6 +4,13 @@ require "active_support/log_subscriber/test_helper"
class RespondToController < ActionController::Base
layout :set_layout
+ before_action {
+ case params[:v]
+ when String then request.variant = params[:v].to_sym
+ when Array then request.variant = params[:v].map(&:to_sym)
+ end
+ }
+
def html_xml_or_rss
respond_to do |type|
type.html { render :text => "HTML" }
@@ -612,8 +619,7 @@ class RespondToControllerTest < ActionController::TestCase
logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new
old_logger, ActionController::Base.logger = ActionController::Base.logger, logger
- @request.variant = :invalid
- get :variant_with_implicit_rendering
+ get :variant_with_implicit_rendering, params: { v: :invalid }
assert_response :no_content
assert_equal 1, logger.logged(:info).select{ |s| s =~ /No template found/ }.size, "Implicit head :no_content not logged"
ensure
@@ -626,28 +632,24 @@ class RespondToControllerTest < ActionController::TestCase
end
def test_variant_with_implicit_rendering
- @request.variant = :implicit
- get :variant_with_implicit_rendering
+ get :variant_with_implicit_rendering, params: { v: :implicit }
assert_response :no_content
end
def test_variant_with_implicit_template_rendering
- @request.variant = :mobile
- get :variant_with_implicit_rendering
+ get :variant_with_implicit_rendering, params: { v: :mobile }
assert_equal "text/html", @response.content_type
assert_equal "mobile", @response.body
end
def test_variant_with_format_and_custom_render
- @request.variant = :phone
- get :variant_with_format_and_custom_render
+ get :variant_with_format_and_custom_render, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "mobile", @response.body
end
def test_multiple_variants_for_format
- @request.variant = :tablet
- get :multiple_variants_for_format
+ get :multiple_variants_for_format, params: { v: :tablet }
assert_equal "text/html", @response.content_type
assert_equal "tablet", @response.body
end
@@ -667,32 +669,27 @@ class RespondToControllerTest < ActionController::TestCase
assert_equal "text/html", @response.content_type
assert_equal "none", @response.body
- @request.variant = :phone
- get :variant_inline_syntax
+ get :variant_inline_syntax, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
end
def test_variant_inline_syntax_without_block
- @request.variant = :phone
- get :variant_inline_syntax_without_block
+ get :variant_inline_syntax_without_block, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
end
def test_variant_any
- @request.variant = :phone
- get :variant_any
+ get :variant_any, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
- @request.variant = :tablet
- get :variant_any
+ get :variant_any, params: { v: :tablet }
assert_equal "text/html", @response.content_type
assert_equal "any", @response.body
- @request.variant = :phablet
- get :variant_any
+ get :variant_any, params: { v: :phablet }
assert_equal "text/html", @response.content_type
assert_equal "any", @response.body
end
@@ -702,54 +699,45 @@ class RespondToControllerTest < ActionController::TestCase
assert_equal "text/html", @response.content_type
assert_equal "any", @response.body
- @request.variant = :phone
- get :variant_any_any
+ get :variant_any_any, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
- @request.variant = :yolo
- get :variant_any_any
+ get :variant_any_any, params: { v: :yolo }
assert_equal "text/html", @response.content_type
assert_equal "any", @response.body
end
def test_variant_inline_any
- @request.variant = :phone
- get :variant_any
+ get :variant_any, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
- @request.variant = :tablet
- get :variant_inline_any
+ get :variant_inline_any, params: { v: :tablet }
assert_equal "text/html", @response.content_type
assert_equal "any", @response.body
- @request.variant = :phablet
- get :variant_inline_any
+ get :variant_inline_any, params: { v: :phablet }
assert_equal "text/html", @response.content_type
assert_equal "any", @response.body
end
def test_variant_inline_any_any
- @request.variant = :phone
- get :variant_inline_any_any
+ get :variant_inline_any_any, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
- @request.variant = :yolo
- get :variant_inline_any_any
+ get :variant_inline_any_any, params: { v: :yolo }
assert_equal "text/html", @response.content_type
assert_equal "any", @response.body
end
def test_variant_any_implicit_render
- @request.variant = :tablet
- get :variant_any_implicit_render
+ get :variant_any_implicit_render, params: { v: :tablet }
assert_equal "text/html", @response.content_type
assert_equal "tablet", @response.body
- @request.variant = :phablet
- get :variant_any_implicit_render
+ get :variant_any_implicit_render, params: { v: :phablet }
assert_equal "text/html", @response.content_type
assert_equal "phablet", @response.body
end
@@ -759,37 +747,53 @@ class RespondToControllerTest < ActionController::TestCase
assert_equal "text/html", @response.content_type
assert_equal "none or phone", @response.body
- @request.variant = :phone
- get :variant_any_with_none
+ get :variant_any_with_none, params: { v: :phone }
assert_equal "text/html", @response.content_type
assert_equal "none or phone", @response.body
end
def test_format_any_variant_any
- @request.variant = :tablet
- get :format_any_variant_any, format: :js
+ get :format_any_variant_any, format: :js, params: { v: :tablet }
assert_equal "text/javascript", @response.content_type
assert_equal "tablet", @response.body
end
def test_variant_negotiation_inline_syntax
- @request.variant = [:tablet, :phone]
- get :variant_inline_syntax_without_block
+ get :variant_inline_syntax_without_block, params: { v: [:tablet, :phone] }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
end
def test_variant_negotiation_block_syntax
- @request.variant = [:tablet, :phone]
- get :variant_plus_none_for_format
+ get :variant_plus_none_for_format, params: { v: [:tablet, :phone] }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
end
def test_variant_negotiation_without_block
- @request.variant = [:tablet, :phone]
- get :variant_inline_syntax_without_block
+ get :variant_inline_syntax_without_block, params: { v: [:tablet, :phone] }
assert_equal "text/html", @response.content_type
assert_equal "phone", @response.body
end
end
+
+class RespondToWithBlockOnDefaultRenderController < ActionController::Base
+ def show
+ default_render do
+ render text: 'default_render yielded'
+ end
+ end
+end
+
+class RespondToWithBlockOnDefaultRenderControllerTest < ActionController::TestCase
+ def setup
+ super
+ @request.host = "www.example.com"
+ end
+
+ def test_default_render_uses_block_when_no_template_exists
+ get :show
+ assert_equal "default_render yielded", @response.body
+ assert_equal "text/html", @response.content_type
+ end
+end
diff --git a/actionpack/test/controller/request/test_request_test.rb b/actionpack/test/controller/request/test_request_test.rb
index 77a2f68b1c..e5d698d5c2 100644
--- a/actionpack/test/controller/request/test_request_test.rb
+++ b/actionpack/test/controller/request/test_request_test.rb
@@ -1,11 +1,7 @@
require 'abstract_unit'
require 'stringio'
-class ActionController::TestRequestTest < ActiveSupport::TestCase
-
- def setup
- @request = ActionController::TestRequest.new
- end
+class ActionController::TestRequestTest < ActionController::TestCase
def test_test_request_has_session_options_initialized
assert @request.session_options
diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb
index 82c808754c..7c17aed632 100644
--- a/actionpack/test/controller/request_forgery_protection_test.rb
+++ b/actionpack/test/controller/request_forgery_protection_test.rb
@@ -484,11 +484,10 @@ end
class FreeCookieControllerTest < ActionController::TestCase
def setup
@controller = FreeCookieController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
@token = "cf50faa3fe97702ca1ae"
SecureRandom.stubs(:base64).returns(@token)
+ super
end
def test_should_not_render_form_with_token_tag
diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb
index f3da2df3ef..5a279639cc 100644
--- a/actionpack/test/controller/resources_test.rb
+++ b/actionpack/test/controller/resources_test.rb
@@ -1207,8 +1207,6 @@ class ResourcesTest < ActionController::TestCase
@controller = "#{options[:options][:controller].camelize}Controller".constantize.new
@controller.singleton_class.include(@routes.url_helpers)
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
get :index, params: options[:options]
options[:options].delete :action
@@ -1277,8 +1275,6 @@ class ResourcesTest < ActionController::TestCase
(options[:options] ||= {})[:controller] ||= singleton_name.to_s.pluralize
@controller = "#{options[:options][:controller].camelize}Controller".constantize.new
@controller.singleton_class.include(@routes.url_helpers)
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
get :show, params: options[:options]
options[:options].delete :action
diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb
index 36c57ec9b2..c0ddcf7f50 100644
--- a/actionpack/test/controller/send_file_test.rb
+++ b/actionpack/test/controller/send_file_test.rb
@@ -34,8 +34,6 @@ class SendFileTest < ActionController::TestCase
def setup
@controller = SendFileController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
end
def test_file_nostream
diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb
index 86ffb898ad..b991232a14 100644
--- a/actionpack/test/controller/test_case_test.rb
+++ b/actionpack/test/controller/test_case_test.rb
@@ -45,11 +45,11 @@ class TestCaseTest < ActionController::TestCase
end
def test_params
- render text: params.inspect
+ render text: ::JSON.dump(params)
end
def test_query_parameters
- render text: request.query_parameters.inspect
+ render text: ::JSON.dump(request.query_parameters)
end
def test_request_parameters
@@ -158,8 +158,6 @@ XML
def setup
super
@controller = TestController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
@request.env['PATH_INFO'] = nil
@routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
r.draw do
@@ -229,7 +227,7 @@ XML
def test_document_body_and_params_with_post
post :test_params, params: { id: 1 }
- assert_equal(%({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}), @response.body)
+ assert_equal({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}, ::JSON.parse(@response.body))
end
def test_document_body_with_post
@@ -485,7 +483,7 @@ XML
assert_deprecated {
get :test_params, page: { name: "Page name", month: '4', year: '2004', day: '6' }
}
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{
'controller' => 'test_case_test/test', 'action' => 'test_params',
@@ -504,7 +502,7 @@ XML
day: '6'
}
}
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{
'controller' => 'test_case_test/test', 'action' => 'test_params',
@@ -516,8 +514,8 @@ XML
def test_query_param_named_action
get :test_query_parameters, params: {action: 'foobar'}
- parsed_params = eval(@response.body)
- assert_equal({action: 'foobar'}, parsed_params)
+ parsed_params = JSON.parse(@response.body)
+ assert_equal({'action' => 'foobar'}, parsed_params)
end
def test_request_param_named_action
@@ -536,7 +534,7 @@ XML
}
}, session: { 'foo' => 'bar' }, flash: { notice: 'created' }
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
@@ -551,7 +549,7 @@ XML
get :test_params, params: {
page: { name: "Page name", month: 4, year: 2004, day: 6 }
}
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
@@ -561,17 +559,17 @@ XML
def test_params_passing_with_fixnums_when_not_html_request
get :test_params, params: { format: 'json', count: 999 }
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
- 'format' => 'json', 'count' => 999 },
+ 'format' => 'json', 'count' => '999' },
parsed_params
)
end
def test_params_passing_path_parameter_is_string_when_not_html_request
get :test_params, params: { format: 'json', id: 1 }
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
'format' => 'json', 'id' => '1' },
@@ -581,7 +579,7 @@ XML
def test_deprecated_params_passing_path_parameter_is_string_when_not_html_request
assert_deprecated { get :test_params, format: 'json', id: 1 }
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
'format' => 'json', 'id' => '1' },
@@ -595,7 +593,7 @@ XML
frozen: 'icy'.freeze, frozens: ['icy'.freeze].freeze, deepfreeze: { frozen: 'icy'.freeze }.freeze
}
end
- parsed_params = eval(@response.body)
+ parsed_params = ::JSON.parse(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
'frozen' => 'icy', 'frozens' => ['icy'], 'deepfreeze' => { 'frozen' => 'icy' }},
@@ -693,13 +691,13 @@ XML
def test_deprecated_xhr_with_params
assert_deprecated { xhr :get, :test_params, params: { id: 1 } }
- assert_equal(%({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}), @response.body)
+ assert_equal({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}, ::JSON.parse(@response.body))
end
def test_xhr_with_params
get :test_params, params: { id: 1 }, xhr: true
- assert_equal(%({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}), @response.body)
+ assert_equal({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}, ::JSON.parse(@response.body))
end
def test_xhr_with_session
@@ -720,12 +718,6 @@ XML
assert_equal 'it works', session[:symbol], "Test session hash should allow indifferent access"
end
- def test_header_properly_reset_after_get_request
- get :test_params
- @request.recycle!
- assert_nil @request.instance_variable_get("@request_method")
- end
-
def test_deprecated_params_reset_between_post_requests
assert_deprecated { post :no_op, foo: "bar" }
assert_equal "bar", @request.params[:foo]
@@ -916,7 +908,7 @@ XML
filename = 'mona_lisa.jpg'
path = "#{FILES_DIR}/#{filename}"
assert_deprecated {
- post :test_file_upload, file: ActionDispatch::Http::UploadedFile.new(filename: path, type: "image/jpg", tempfile: File.open(path))
+ post :test_file_upload, file: Rack::Test::UploadedFile.new(path, "image/jpg", true)
}
assert_equal '159528', @response.body
end
@@ -925,7 +917,7 @@ XML
filename = 'mona_lisa.jpg'
path = "#{FILES_DIR}/#{filename}"
post :test_file_upload, params: {
- file: ActionDispatch::Http::UploadedFile.new(filename: path, type: "image/jpg", tempfile: File.open(path))
+ file: Rack::Test::UploadedFile.new(path, "image/jpg", true)
}
assert_equal '159528', @response.body
end
@@ -957,10 +949,11 @@ class ResponseDefaultHeadersTest < ActionController::TestCase
end
end
- setup do
+ def before_setup
@original = ActionDispatch::Response.default_headers
@defaults = { 'A' => '1', 'B' => '2' }
ActionDispatch::Response.default_headers = @defaults
+ super
end
teardown do
@@ -970,8 +963,6 @@ class ResponseDefaultHeadersTest < ActionController::TestCase
def setup
super
@controller = TestController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
@request.env['PATH_INFO'] = nil
@routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
r.draw do
diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb
index d9a1ae7d4f..5f2abc9606 100644
--- a/actionpack/test/controller/url_rewriter_test.rb
+++ b/actionpack/test/controller/url_rewriter_test.rb
@@ -1,7 +1,7 @@
require 'abstract_unit'
require 'controller/fake_controllers'
-class UrlRewriterTests < ActiveSupport::TestCase
+class UrlRewriterTests < ActionController::TestCase
class Rewriter
def initialize(request)
@options = {
@@ -16,7 +16,6 @@ class UrlRewriterTests < ActiveSupport::TestCase
end
def setup
- @request = ActionController::TestRequest.new
@params = {}
@rewriter = Rewriter.new(@request) #.new(@request, @params)
@routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb
index 6223a52a76..aca28ae8d1 100644
--- a/actionpack/test/dispatch/cookies_test.rb
+++ b/actionpack/test/dispatch/cookies_test.rb
@@ -280,7 +280,7 @@ class CookiesTest < ActionController::TestCase
def test_setting_the_same_value_to_cookie
request.cookies[:user_name] = 'david'
get :authenticate
- assert response.cookies.empty?
+ assert_predicate response.cookies, :empty?
end
def test_setting_the_same_value_to_permanent_cookie
@@ -360,7 +360,7 @@ class CookiesTest < ActionController::TestCase
def test_delete_unexisting_cookie
request.cookies.clear
get :delete_cookie
- assert @response.cookies.empty?
+ assert_predicate @response.cookies, :empty?
end
def test_deleted_cookie_predicate
@@ -378,7 +378,7 @@ class CookiesTest < ActionController::TestCase
def test_cookies_persist_throughout_request
response = get :authenticate
- assert response.headers["Set-Cookie"] =~ /user_name=david/
+ assert_match(/user_name=david/, response.headers["Set-Cookie"])
end
def test_set_permanent_cookie
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index 27ee8603e4..ff63c10e8d 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -989,6 +989,7 @@ class RequestParameterFilter < BaseRequestTest
[{'foo'=>'bar', 'baz'=>'foo'},{'foo'=>'[FILTERED]', 'baz'=>'[FILTERED]'},%w'foo baz'],
[{'bar'=>{'foo'=>'bar','bar'=>'foo'}},{'bar'=>{'foo'=>'[FILTERED]','bar'=>'foo'}},%w'fo'],
[{'foo'=>{'foo'=>'bar','bar'=>'foo'}},{'foo'=>'[FILTERED]'},%w'f banana'],
+ [{'deep'=>{'cc'=>{'code'=>'bar','bar'=>'foo'},'ss'=>{'code'=>'bar'}}},{'deep'=>{'cc'=>{'code'=>'[FILTERED]','bar'=>'foo'},'ss'=>{'code'=>'bar'}}},%w'deep.cc.code'],
[{'baz'=>[{'foo'=>'baz'}, "1"]}, {'baz'=>[{'foo'=>'[FILTERED]'}, "1"]}, [/foo/]]]
test_hashes.each do |before_filter, after_filter, filter_words|
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index 77f86b7a62..26b8636c2f 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -3567,12 +3567,11 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
mount lambda { |env| [200, {}, [env['REQUEST_METHOD']]] }, at: '/'
end
- # TODO: HEAD request should match `get /home` rather than the
+ # HEAD request should match `get /home` rather than the
# lower-precedence Rack app mounted at `/`.
head '/home'
assert_response :ok
- #assert_equal 'test#index', @response.body
- assert_equal 'HEAD', @response.body
+ assert_equal 'test#index', @response.body
# But the Rack app can still respond to its own HEAD requests.
head '/foobar'
diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb
index cc35d4594e..ede1cec4e6 100644
--- a/actionpack/test/dispatch/test_request_test.rb
+++ b/actionpack/test/dispatch/test_request_test.rb
@@ -2,7 +2,7 @@ require 'abstract_unit'
class TestRequestTest < ActiveSupport::TestCase
test "sane defaults" do
- env = ActionDispatch::TestRequest.new.env
+ env = ActionDispatch::TestRequest.create.env
assert_equal "GET", env.delete("REQUEST_METHOD")
assert_equal "off", env.delete("HTTPS")
@@ -24,12 +24,10 @@ class TestRequestTest < ActiveSupport::TestCase
assert_equal true, env.delete("rack.multithread")
assert_equal true, env.delete("rack.multiprocess")
assert_equal false, env.delete("rack.run_once")
-
- assert env.empty?, env.inspect
end
test "cookie jar" do
- req = ActionDispatch::TestRequest.new
+ req = ActionDispatch::TestRequest.create({})
assert_equal({}, req.cookies)
assert_equal nil, req.env["HTTP_COOKIE"]
@@ -57,38 +55,38 @@ class TestRequestTest < ActiveSupport::TestCase
test "does not complain when Rails.application is nil" do
Rails.stubs(:application).returns(nil)
- req = ActionDispatch::TestRequest.new
+ req = ActionDispatch::TestRequest.create({})
assert_equal false, req.env.empty?
end
test "default remote address is 0.0.0.0" do
- req = ActionDispatch::TestRequest.new
+ req = ActionDispatch::TestRequest.create({})
assert_equal '0.0.0.0', req.remote_addr
end
test "allows remote address to be overridden" do
- req = ActionDispatch::TestRequest.new('REMOTE_ADDR' => '127.0.0.1')
+ req = ActionDispatch::TestRequest.create('REMOTE_ADDR' => '127.0.0.1')
assert_equal '127.0.0.1', req.remote_addr
end
test "default host is test.host" do
- req = ActionDispatch::TestRequest.new
+ req = ActionDispatch::TestRequest.create({})
assert_equal 'test.host', req.host
end
test "allows host to be overridden" do
- req = ActionDispatch::TestRequest.new('HTTP_HOST' => 'www.example.com')
+ req = ActionDispatch::TestRequest.create('HTTP_HOST' => 'www.example.com')
assert_equal 'www.example.com', req.host
end
test "default user agent is 'Rails Testing'" do
- req = ActionDispatch::TestRequest.new
+ req = ActionDispatch::TestRequest.create({})
assert_equal 'Rails Testing', req.user_agent
end
test "allows user agent to be overridden" do
- req = ActionDispatch::TestRequest.new('HTTP_USER_AGENT' => 'GoogleBot')
+ req = ActionDispatch::TestRequest.create('HTTP_USER_AGENT' => 'GoogleBot')
assert_equal 'GoogleBot', req.user_agent
end
diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md
index 7b6008d5ed..1f6bb31cd4 100644
--- a/actionview/CHANGELOG.md
+++ b/actionview/CHANGELOG.md
@@ -1,3 +1,26 @@
+* Allow defining explicit collection caching using a `# Template Collection: ...`
+ directive inside templates.
+
+ *Dov Murik*
+
+* Asset helpers raise `ArgumentError` when `nil` is passed as a source.
+
+ *Anton Kolomiychuk*
+
+* Always attach the template digest to the cache key for collection caching
+ even when `virtual_path` is not available from the view context.
+ Which could happen if the rendering was done directly in the controller
+ and not in a template.
+
+ Fixes #20535
+
+ *Roque Pinel*
+
+* Improve detection of partial templates eligible for collection caching,
+ now allowing multi-line comments at the beginning of the template file.
+
+ *Dov Murik*
+
* Raise an ArgumentError when a false value for `include_blank` is passed to a
required select field (to comply with the HTML5 spec).
diff --git a/actionview/lib/action_view/helpers/asset_url_helper.rb b/actionview/lib/action_view/helpers/asset_url_helper.rb
index ef4a6c98c0..b19dc25025 100644
--- a/actionview/lib/action_view/helpers/asset_url_helper.rb
+++ b/actionview/lib/action_view/helpers/asset_url_helper.rb
@@ -121,6 +121,8 @@ module ActionView
# asset_path "application", type: :stylesheet # => /assets/application.css
# asset_path "http://www.example.com/js/xmlhr.js" # => http://www.example.com/js/xmlhr.js
def asset_path(source, options = {})
+ raise ArgumentError, "nil is not a valid asset source" if source.nil?
+
source = source.to_s
return "" unless source.present?
return source if source =~ URI_REGEXP
diff --git a/actionview/lib/action_view/helpers/cache_helper.rb b/actionview/lib/action_view/helpers/cache_helper.rb
index 72e2aa1807..797d029317 100644
--- a/actionview/lib/action_view/helpers/cache_helper.rb
+++ b/actionview/lib/action_view/helpers/cache_helper.rb
@@ -137,7 +137,22 @@ module ActionView
# The automatic cache multi read can be turned off like so:
#
# <%= render @notifications, cache: false %>
- def cache(name = {}, options = nil, &block)
+ #
+ # === Explicit Collection Caching
+ #
+ # If the partial template doesn't start with a clean cache call as
+ # mentioned above, you can still benefit from collection caching by
+ # adding a special comment format anywhere in the template, like:
+ #
+ # <%# Template Collection: notification %>
+ # <% my_helper_that_calls_cache(some_arg, notification) do %>
+ # <%= notification.name %>
+ # <% end %>
+ #
+ # The pattern used to match these is <tt>/# Template Collection: (\S+)/</tt>,
+ # so it's important that you type it out just so.
+ # You can only declare one collection in a partial template file.
+ def cache(name = {}, options = {}, &block)
if controller.respond_to?(:perform_caching) && controller.perform_caching
safe_concat(fragment_for(cache_fragment_name(name, options), options, &block))
else
@@ -153,7 +168,7 @@ module ActionView
# <b>All the topics on this project</b>
# <%= render project.topics %>
# <% end %>
- def cache_if(condition, name = {}, options = nil, &block)
+ def cache_if(condition, name = {}, options = {}, &block)
if condition
cache(name, options, &block)
else
@@ -169,22 +184,23 @@ module ActionView
# <b>All the topics on this project</b>
# <%= render project.topics %>
# <% end %>
- def cache_unless(condition, name = {}, options = nil, &block)
+ def cache_unless(condition, name = {}, options = {}, &block)
cache_if !condition, name, options, &block
end
# This helper returns the name of a cache key for a given fragment cache
- # call. By supplying skip_digest: true to cache, the digestion of cache
+ # call. By supplying +skip_digest:+ true to cache, the digestion of cache
# fragments can be manually bypassed. This is useful when cache fragments
# cannot be manually expired unless you know the exact key which is the
# case when using memcached.
- def cache_fragment_name(name = {}, options = nil)
- skip_digest = options && options[:skip_digest]
-
+ #
+ # The digest will be generated using +virtual_path:+ if it is provided.
+ #
+ def cache_fragment_name(name = {}, skip_digest: nil, virtual_path: nil)
if skip_digest
name
else
- fragment_name_with_digest(name)
+ fragment_name_with_digest(name, virtual_path)
end
end
@@ -198,10 +214,11 @@ module ActionView
private
- def fragment_name_with_digest(name) #:nodoc:
- if @virtual_path
+ def fragment_name_with_digest(name, virtual_path) #:nodoc:
+ virtual_path ||= @virtual_path
+ if virtual_path
names = Array(name.is_a?(Hash) ? controller.url_for(name).split("://").last : name)
- digest = Digestor.digest name: @virtual_path, finder: lookup_context, dependencies: view_cache_dependencies
+ digest = Digestor.digest name: virtual_path, finder: lookup_context, dependencies: view_cache_dependencies
[ *names, digest ]
else
diff --git a/actionview/lib/action_view/helpers/date_helper.rb b/actionview/lib/action_view/helpers/date_helper.rb
index 0633213d5e..9c8edc69a9 100644
--- a/actionview/lib/action_view/helpers/date_helper.rb
+++ b/actionview/lib/action_view/helpers/date_helper.rb
@@ -69,8 +69,8 @@ module ActionView
# distance_of_time_in_words(to_time, from_time, include_seconds: true) # => about 6 years
# distance_of_time_in_words(Time.now, Time.now) # => less than a minute
#
- # With the <tt>scope</tt> you can define a custom scope for Rails lookup
- # the translation.
+ # With the <tt>scope</tt> option, you can define a custom scope for Rails
+ # to lookup the translation.
#
# For example you can define the following in your locale (e.g. en.yml).
#
@@ -78,8 +78,8 @@ module ActionView
# distance_in_words:
# short:
# about_x_hours:
- # one: 1 hr
- # other: '%{count} hr'
+ # one: 'an hour'
+ # other: '%{count} hours'
#
# See https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/en.yml
# for more examples.
@@ -87,8 +87,8 @@ module ActionView
# Which will then result in the following:
#
# from_time = Time.now
- # distance_of_time_in_words(from_time, from_time + 50.minutes, scope: 'datetime.distance_in_words.short') # => 1 hr
- # distance_of_time_in_words(from_time, from_time + 3.hours, scope: 'datetime.distance_in_words.short') # => 3 hr
+ # distance_of_time_in_words(from_time, from_time + 50.minutes, scope: 'datetime.distance_in_words.short') # => "an hour"
+ # distance_of_time_in_words(from_time, from_time + 3.hours, scope: 'datetime.distance_in_words.short') # => "3 hours"
def distance_of_time_in_words(from_time, to_time = 0, options = {})
options = {
scope: :'datetime.distance_in_words'
diff --git a/actionview/lib/action_view/helpers/form_options_helper.rb b/actionview/lib/action_view/helpers/form_options_helper.rb
index 1b7b188d65..8e729b3c39 100644
--- a/actionview/lib/action_view/helpers/form_options_helper.rb
+++ b/actionview/lib/action_view/helpers/form_options_helper.rb
@@ -35,8 +35,8 @@ module ActionView
# <select name="post[person_id]" id="post_person_id">
# <option value="">None</option>
# <option value="1">David</option>
- # <option value="2" selected="selected">Sam</option>
- # <option value="3">Tobias</option>
+ # <option value="2" selected="selected">Eileen</option>
+ # <option value="3">Rafael</option>
# </select>
#
# * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this prepends an option with a generic prompt -- "Please select" -- or the given prompt string.
@@ -48,8 +48,8 @@ module ActionView
# <select name="post[person_id]" id="post_person_id">
# <option value="">Select Person</option>
# <option value="1">David</option>
- # <option value="2">Sam</option>
- # <option value="3">Tobias</option>
+ # <option value="2">Eileen</option>
+ # <option value="3">Rafael</option>
# </select>
#
# * <tt>:index</tt> - like the other form helpers, +select+ can accept an <tt>:index</tt> option to manually set the ID used in the resulting output. Unlike other helpers, +select+ expects this
@@ -112,8 +112,8 @@ module ActionView
# <select name="post[person_id]" id="post_person_id">
# <option value=""></option>
# <option value="1" selected="selected">David</option>
- # <option value="2">Sam</option>
- # <option value="3">Tobias</option>
+ # <option value="2">Eileen</option>
+ # <option value="3">Rafael</option>
# </select>
#
# assuming the associated person has ID 1.
diff --git a/actionview/lib/action_view/helpers/text_helper.rb b/actionview/lib/action_view/helpers/text_helper.rb
index c216d4401f..6a3d01667d 100644
--- a/actionview/lib/action_view/helpers/text_helper.rb
+++ b/actionview/lib/action_view/helpers/text_helper.rb
@@ -206,6 +206,11 @@ module ActionView
# +plural+ is supplied, it will use that when count is > 1, otherwise
# it will use the Inflector to determine the plural form.
#
+ # If passed an optional +locale:+ parameter, the word will be pluralized
+ # using rules defined for that language (you must define your own
+ # inflection rules for languages other than English). See
+ # ActiveSupport::Inflector.pluralize
+ #
# pluralize(1, 'person')
# # => 1 person
#
@@ -217,11 +222,14 @@ module ActionView
#
# pluralize(0, 'person')
# # => 0 people
- def pluralize(count, singular, plural = nil)
+ #
+ # pluralize(2, 'Person', locale: :de)
+ # # => 2 Personen
+ def pluralize(count, singular, plural = nil, locale: nil)
word = if (count == 1 || count =~ /^1(\.0+)?$/)
singular
else
- plural || singular.pluralize
+ plural || singular.pluralize(locale)
end
"#{count || 0} #{word}"
diff --git a/actionview/lib/action_view/renderer/partial_renderer.rb b/actionview/lib/action_view/renderer/partial_renderer.rb
index b751bca31e..780fdabbd1 100644
--- a/actionview/lib/action_view/renderer/partial_renderer.rb
+++ b/actionview/lib/action_view/renderer/partial_renderer.rb
@@ -348,8 +348,6 @@ module ActionView
content
end
- private
-
# Sets up instance variables needed for rendering a partial. This method
# finds the options and details and extracts them. The method also contains
# logic that handles the type of object passed in as the partial.
diff --git a/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb b/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb
index c8268e226e..1147963882 100644
--- a/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb
+++ b/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb
@@ -51,7 +51,7 @@ module ActionView
end
def expanded_cache_key(key)
- key = @view.fragment_cache_key(@view.cache_fragment_name(key))
+ key = @view.fragment_cache_key(@view.cache_fragment_name(key, virtual_path: @template.virtual_path))
key.frozen? ? key.dup : key # #read_multi & #write may require mutability, Dalli 2.6.0.
end
diff --git a/actionview/lib/action_view/template.rb b/actionview/lib/action_view/template.rb
index 377ceb534a..d8585514d5 100644
--- a/actionview/lib/action_view/template.rb
+++ b/actionview/lib/action_view/template.rb
@@ -130,7 +130,7 @@ module ActionView
@source = source
@identifier = identifier
@handler = handler
- @cache_name = extract_resource_cache_call_name
+ @cache_name = extract_resource_cache_name
@compiled = false
@original_encoding = nil
@locals = details[:locals] || []
@@ -351,9 +351,18 @@ module ActionView
ActiveSupport::Notifications.instrument("#{action}.action_view", payload, &block)
end
- def extract_resource_cache_call_name
- $1 if @handler.respond_to?(:resource_cache_call_pattern) &&
- @source =~ @handler.resource_cache_call_pattern
+ EXPLICIT_COLLECTION = /# Template Collection: (?<resource_name>\w+)/
+
+ def extract_resource_cache_name
+ if match = @source.match(EXPLICIT_COLLECTION) || resource_cache_call_match
+ match[:resource_name]
+ end
+ end
+
+ def resource_cache_call_match
+ if @handler.respond_to?(:resource_cache_call_pattern)
+ @source.match(@handler.resource_cache_call_pattern)
+ end
end
def inferred_cache_name
diff --git a/actionview/lib/action_view/template/handlers/erb.rb b/actionview/lib/action_view/template/handlers/erb.rb
index 88a8570706..1f8459c24b 100644
--- a/actionview/lib/action_view/template/handlers/erb.rb
+++ b/actionview/lib/action_view/template/handlers/erb.rb
@@ -125,7 +125,7 @@ module ActionView
# Returns Regexp to extract a cached resource's name from a cache call at the
# first line of a template.
- # The extracted cache name is expected in $1.
+ # The extracted cache name is captured as :resource_name.
#
# <% cache notification do %> # => notification
#
@@ -138,7 +138,14 @@ module ActionView
#
# <% cache notification.event do %> # => nil
def resource_cache_call_pattern
- /\A(?:<%#.*%>\n?)?<% cache\(?\s*(\w+\.?)/
+ /\A
+ (?:<%\#.*%>)* # optional initial comment
+ \s* # followed by optional spaces or newlines
+ <%\s*cache[\(\s] # followed by an ERB call to cache
+ \s* # followed by optional spaces or newlines
+ (?<resource_name>\w+) # capture the cache call argument as :resource_name
+ [\s\)] # followed by a space or close paren
+ /xm
end
private
diff --git a/actionview/lib/action_view/test_case.rb b/actionview/lib/action_view/test_case.rb
index 06810ad14d..b4f36c1f78 100644
--- a/actionview/lib/action_view/test_case.rb
+++ b/actionview/lib/action_view/test_case.rb
@@ -24,7 +24,7 @@ module ActionView
def initialize
super
self.class.controller_path = ""
- @request = ActionController::TestRequest.new
+ @request = ActionController::TestRequest.create
@response = ActionController::TestResponse.new
@request.env.delete('PATH_INFO')
diff --git a/actionview/test/actionpack/controller/view_paths_test.rb b/actionview/test/actionpack/controller/view_paths_test.rb
index 7fba9ff8ff..2dd27358f7 100644
--- a/actionview/test/actionpack/controller/view_paths_test.rb
+++ b/actionview/test/actionpack/controller/view_paths_test.rb
@@ -23,7 +23,7 @@ class ViewLoadPathsTest < ActionController::TestCase
end
def setup
- @request = ActionController::TestRequest.new
+ @request = ActionController::TestRequest.create
@response = ActionController::TestResponse.new
@controller = TestController.new
@paths = TestController.view_paths
diff --git a/actionview/test/template/asset_tag_helper_test.rb b/actionview/test/template/asset_tag_helper_test.rb
index 6e6ce20924..01fc66bed6 100644
--- a/actionview/test/template/asset_tag_helper_test.rb
+++ b/actionview/test/template/asset_tag_helper_test.rb
@@ -310,6 +310,11 @@ class AssetTagHelperTest < ActionView::TestCase
AssetPathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
end
+ def test_asset_path_tag_raises_an_error_for_nil_source
+ e = assert_raise(ArgumentError) { asset_path(nil) }
+ assert_equal("nil is not a valid asset source", e.message)
+ end
+
def test_asset_path_tag_to_not_create_duplicate_slashes
@controller.config.asset_host = "host/"
assert_dom_equal('http://host/foo', asset_path("foo"))
diff --git a/actionview/test/template/render_test.rb b/actionview/test/template/render_test.rb
index 27bbb9b6c1..9c2c9507b7 100644
--- a/actionview/test/template/render_test.rb
+++ b/actionview/test/template/render_test.rb
@@ -7,7 +7,10 @@ end
module RenderTestCases
def setup_view(paths)
@assigns = { :secret => 'in the sauce' }
- @view = ActionView::Base.new(paths, @assigns)
+ @view = Class.new(ActionView::Base) do
+ def view_cache_dependencies; end
+ end.new(paths, @assigns)
+
@controller_view = TestController.new.view_context
# Reload and register danish language for testing
@@ -616,7 +619,7 @@ class CachedCollectionViewRenderTest < CachedViewRenderTest
test "with custom key" do
customer = Customer.new("david")
- key = ActionController::Base.new.fragment_cache_key([customer, 'key'])
+ key = cache_key([customer, 'key'], "test/_customer")
ActionView::PartialRenderer.collection_cache.write(key, 'Hello')
@@ -626,7 +629,7 @@ class CachedCollectionViewRenderTest < CachedViewRenderTest
test "automatic caching with inferred cache name" do
customer = CachedCustomer.new("david")
- key = ActionController::Base.new.fragment_cache_key(customer)
+ key = cache_key(customer, "test/_cached_customer")
ActionView::PartialRenderer.collection_cache.write(key, 'Cached')
@@ -636,11 +639,17 @@ class CachedCollectionViewRenderTest < CachedViewRenderTest
test "automatic caching with as name" do
customer = CachedCustomer.new("david")
- key = ActionController::Base.new.fragment_cache_key(customer)
+ key = cache_key(customer, "test/_cached_customer_as")
ActionView::PartialRenderer.collection_cache.write(key, 'Cached')
assert_equal "Cached",
@view.render(partial: "test/cached_customer_as", collection: [customer], as: :buyer)
end
+
+ private
+ def cache_key(names, virtual_path)
+ digest = ActionView::Digestor.digest name: virtual_path, finder: @view.lookup_context, dependencies: []
+ @view.fragment_cache_key([ *Array(names), digest ])
+ end
end
diff --git a/actionview/test/template/template_test.rb b/actionview/test/template/template_test.rb
index aae6a9aa09..d3b51cd629 100644
--- a/actionview/test/template/template_test.rb
+++ b/actionview/test/template/template_test.rb
@@ -190,6 +190,38 @@ class TestERBTemplate < ActiveSupport::TestCase
assert_match(/\xFC/, e.message)
end
+ def test_not_eligible_for_collection_caching_without_cache_call
+ [
+ "<%= 'Hello' %>",
+ "<% cache_customer = 42 %>",
+ "<% cache customer.name do %><% end %>",
+ "<% my_cache customer do %><% end %>"
+ ].each do |body|
+ template = new_template(body, virtual_path: "test/foo/_customer")
+ assert_not template.eligible_for_collection_caching?, "Template #{body.inspect} should not be eligible for collection caching"
+ end
+ end
+
+ def test_eligible_for_collection_caching_with_cache_call_or_explicit
+ [
+ "<% cache customer do %><% end %>",
+ "<% cache(customer) do %><% end %>",
+ "<% cache( customer) do %><% end %>",
+ "<% cache( customer ) do %><% end %>",
+ "<%cache customer do %><% end %>",
+ "<% cache customer do %><% end %>",
+ " <% cache customer do %>\n<% end %>\n",
+ "<%# comment %><% cache customer do %><% end %>",
+ "<%# comment %>\n<% cache customer do %><% end %>",
+ "<%# comment\n line 2\n line 3 %>\n<% cache customer do %><% end %>",
+ "<%# comment 1 %>\n<%# comment 2 %>\n<% cache customer do %><% end %>",
+ "<%# comment 1 %>\n<%# Template Collection: customer %>\n<% my_cache customer do %><% end %>"
+ ].each do |body|
+ template = new_template(body, virtual_path: "test/foo/_customer")
+ assert template.eligible_for_collection_caching?, "Template #{body.inspect} should be eligible for collection caching"
+ end
+ end
+
def with_external_encoding(encoding)
old = Encoding.default_external
Encoding::Converter.new old, encoding if old != encoding
diff --git a/actionview/test/template/text_helper_test.rb b/actionview/test/template/text_helper_test.rb
index f1b84c4786..5791f33069 100644
--- a/actionview/test/template/text_helper_test.rb
+++ b/actionview/test/template/text_helper_test.rb
@@ -383,6 +383,18 @@ class TextHelperTest < ActionView::TestCase
assert_equal("12 berries", pluralize(12, "berry"))
end
+ def test_pluralization_with_locale
+ ActiveSupport::Inflector.inflections(:de) do |inflect|
+ inflect.plural(/(person)$/i, '\1en')
+ inflect.singular(/(person)en$/i, '\1')
+ end
+
+ assert_equal("2 People", pluralize(2, "Person", locale: :en))
+ assert_equal("2 Personen", pluralize(2, "Person", locale: :de))
+
+ ActiveSupport::Inflector.inflections(:de).clear
+ end
+
def test_cycle_class
value = Cycle.new("one", 2, "3")
assert_equal("one", value.to_s)
diff --git a/activejob/lib/active_job/arguments.rb b/activejob/lib/active_job/arguments.rb
index cdb37879b6..8e462bfe5d 100644
--- a/activejob/lib/active_job/arguments.rb
+++ b/activejob/lib/active_job/arguments.rb
@@ -16,13 +16,13 @@ module ActiveJob
end
end
- # Raised when an unsupported argument type is being set as job argument. We
+ # Raised when an unsupported argument type is set as a job argument. We
# currently support NilClass, Fixnum, Float, String, TrueClass, FalseClass,
- # Bignum and object that can be represented as GlobalIDs (ex: Active Record).
- # Also raised if you set the key for a Hash something else than a string or
- # a symbol.
- class SerializationError < ArgumentError
- end
+ # Bignum and objects that can be represented as GlobalIDs (ex: Active Record).
+ # Raised if you set the key for a Hash something else than a string or
+ # a symbol. Also raised when trying to serialize an object which can't be
+ # identified with a Global ID - such as an unpersisted Active Record model.
+ class SerializationError < ArgumentError; end
module Arguments
extend self
@@ -59,7 +59,7 @@ module ActiveJob
when *TYPE_WHITELIST
argument
when GlobalID::Identification
- { GLOBALID_KEY => argument.to_global_id.to_s }
+ convert_to_global_id_hash(argument)
when Array
argument.map { |arg| serialize_argument(arg) }
when ActiveSupport::HashWithIndifferentAccess
@@ -147,5 +147,12 @@ module ActiveJob
end
end
end
+
+ def convert_to_global_id_hash(argument)
+ { GLOBALID_KEY => argument.to_global_id.to_s }
+ rescue URI::GID::MissingModelIdError
+ raise SerializationError, "Unable to serialize #{argument.class} " \
+ "without an id. (Maybe you forgot to call save?)"
+ end
end
end
diff --git a/activejob/test/cases/argument_serialization_test.rb b/activejob/test/cases/argument_serialization_test.rb
index 8b9b62190f..933972a52b 100644
--- a/activejob/test/cases/argument_serialization_test.rb
+++ b/activejob/test/cases/argument_serialization_test.rb
@@ -88,6 +88,13 @@ class ArgumentSerializationTest < ActiveSupport::TestCase
assert_equal "Job with argument: 2", JobBuffer.last_value
end
+ test 'raises a friendly SerializationError for records without ids' do
+ err = assert_raises ActiveJob::SerializationError do
+ ActiveJob::Arguments.serialize [Person.new(nil)]
+ end
+ assert_match 'Unable to serialize Person without an id.', err.message
+ end
+
private
def assert_arguments_unchanged(*args)
assert_arguments_roundtrip args
diff --git a/activemodel/README.rdoc b/activemodel/README.rdoc
index 5c36b1277e..d954467387 100644
--- a/activemodel/README.rdoc
+++ b/activemodel/README.rdoc
@@ -154,7 +154,7 @@ behavior out of the box:
* Making objects serializable
- ActiveModel::Serialization provides a standard interface for your object
+ <tt>ActiveModel::Serialization</tt> provides a standard interface for your object
to provide +to_json+ or +to_xml+ serialization.
class SerialPerson
diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb
index c1019169e1..72094a26c0 100644
--- a/activemodel/lib/active_model/validations.rb
+++ b/activemodel/lib/active_model/validations.rb
@@ -87,8 +87,7 @@ module ActiveModel
validates_with BlockValidator, _merge_attributes(attr_names), &block
end
- # :nodoc:
- VALID_OPTIONS_FOR_VALIDATE = [:on, :if, :unless, :prepend].freeze
+ VALID_OPTIONS_FOR_VALIDATE = [:on, :if, :unless, :prepend].freeze # :nodoc:
# Adds a validation method or block to the class. This is useful when
# overriding the +validate+ instance method becomes too unwieldy and
@@ -130,6 +129,9 @@ module ActiveModel
# end
# end
#
+ # Note that the return value of validation methods is not relevant.
+ # It's not possible to halt the validate callback chain.
+ #
# Options:
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
# Runs in all validation contexts by default (nil). You can pass a symbol
diff --git a/activemodel/lib/active_model/validations/acceptance.rb b/activemodel/lib/active_model/validations/acceptance.rb
index ee160fb483..1bcfedb35d 100644
--- a/activemodel/lib/active_model/validations/acceptance.rb
+++ b/activemodel/lib/active_model/validations/acceptance.rb
@@ -42,9 +42,10 @@ module ActiveModel
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "must be
# accepted").
- # * <tt>:accept</tt> - Specifies value that is considered accepted.
- # The default value is a string "1", which makes it easy to relate to
- # an HTML checkbox. This should be set to +true+ if you are validating
+ # * <tt>:accept</tt> - Specifies a value that is considered accepted.
+ # Also accepts an array of possible values. The default value is
+ # an array ["1", true], which makes it easy to relate to an HTML
+ # checkbox. This should be set to, or include, +true+ if you are validating
# a database column, since the attribute is typecast from "1" to +true+
# before validation.
#
diff --git a/activemodel/lib/active_model/validations/exclusion.rb b/activemodel/lib/active_model/validations/exclusion.rb
index f342d27275..6f4276cc2a 100644
--- a/activemodel/lib/active_model/validations/exclusion.rb
+++ b/activemodel/lib/active_model/validations/exclusion.rb
@@ -29,7 +29,9 @@ module ActiveModel
# Configuration options:
# * <tt>:in</tt> - An enumerable object of items that the value shouldn't
# be part of. This can be supplied as a proc, lambda or symbol which returns an
- # enumerable. If the enumerable is a range the test is performed with
+ # enumerable. If the enumerable is a numerical, time or datetime range the test
+ # is performed with <tt>Range#cover?</tt>, otherwise with <tt>include?</tt>. When
+ # using a proc or lambda the instance under validation is passed as an argument.
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
# <tt>Range#cover?</tt>, otherwise with <tt>include?</tt>.
# * <tt>:message</tt> - Specifies a custom error message (default is: "is
diff --git a/activemodel/lib/active_model/validations/helper_methods.rb b/activemodel/lib/active_model/validations/helper_methods.rb
new file mode 100644
index 0000000000..2176115334
--- /dev/null
+++ b/activemodel/lib/active_model/validations/helper_methods.rb
@@ -0,0 +1,13 @@
+module ActiveModel
+ module Validations
+ module HelperMethods # :nodoc:
+ private
+ def _merge_attributes(attr_names)
+ options = attr_names.extract_options!.symbolize_keys
+ attr_names.flatten!
+ options[:attributes] = attr_names
+ options
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations/inclusion.rb b/activemodel/lib/active_model/validations/inclusion.rb
index c84025f083..03e0ef56d8 100644
--- a/activemodel/lib/active_model/validations/inclusion.rb
+++ b/activemodel/lib/active_model/validations/inclusion.rb
@@ -28,9 +28,9 @@ module ActiveModel
# Configuration options:
# * <tt>:in</tt> - An enumerable object of available items. This can be
# supplied as a proc, lambda or symbol which returns an enumerable. If the
- # enumerable is a numerical range the test is performed with <tt>Range#cover?</tt>,
- # otherwise with <tt>include?</tt>. When using a proc or lambda the instance
- # under validation is passed as an argument.
+ # enumerable is a numerical, time or datetime range the test is performed
+ # with <tt>Range#cover?</tt>, otherwise with <tt>include?</tt>. When using
+ # a proc or lambda the instance under validation is passed as an argument.
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
# * <tt>:message</tt> - Specifies a custom error message (default is: "is
# not included in the list").
diff --git a/activemodel/lib/active_model/validations/length.rb b/activemodel/lib/active_model/validations/length.rb
index c22a58f9e1..910cca2f49 100644
--- a/activemodel/lib/active_model/validations/length.rb
+++ b/activemodel/lib/active_model/validations/length.rb
@@ -1,8 +1,6 @@
require "active_support/core_ext/string/strip"
module ActiveModel
-
- # == Active \Model Length Validator
module Validations
class LengthValidator < EachValidator # :nodoc:
MESSAGES = { is: :wrong_length, minimum: :too_short, maximum: :too_long }.freeze
@@ -100,8 +98,9 @@ module ActiveModel
module HelperMethods
- # Validates that the specified attribute matches the length restrictions
- # supplied. Only one option can be used at a time:
+ # Validates that the specified attributes match the length restrictions
+ # supplied. Only one constraint option can be used at a time apart from
+ # +:minimum+ and +:maximum+ that can be combined together:
#
# class Person < ActiveRecord::Base
# validates_length_of :first_name, maximum: 30
@@ -120,14 +119,18 @@ module ActiveModel
# end
# end
#
- # Configuration options:
+ # Constraint options:
+ #
# * <tt>:minimum</tt> - The minimum size of the attribute.
# * <tt>:maximum</tt> - The maximum size of the attribute. Allows +nil+ by
- # default if not used with :minimum.
+ # default if not used with +:minimum+.
# * <tt>:is</tt> - The exact size of the attribute.
# * <tt>:within</tt> - A range specifying the minimum and maximum size of
# the attribute.
# * <tt>:in</tt> - A synonym (or alias) for <tt>:within</tt>.
+ #
+ # Other options:
+ #
# * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
# * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
# * <tt>:too_long</tt> - The error message if the attribute goes over the
diff --git a/activemodel/lib/active_model/validations/with.rb b/activemodel/lib/active_model/validations/with.rb
index a2531327bf..6de01b3392 100644
--- a/activemodel/lib/active_model/validations/with.rb
+++ b/activemodel/lib/active_model/validations/with.rb
@@ -1,15 +1,5 @@
module ActiveModel
module Validations
- module HelperMethods
- private
- def _merge_attributes(attr_names)
- options = attr_names.extract_options!.symbolize_keys
- attr_names.flatten!
- options[:attributes] = attr_names
- options
- end
- end
-
class WithValidator < EachValidator # :nodoc:
def validate_each(record, attr, val)
method_name = options[:with]
diff --git a/activemodel/test/cases/errors_test.rb b/activemodel/test/cases/errors_test.rb
index 3fa63917d0..f6d171bec6 100644
--- a/activemodel/test/cases/errors_test.rb
+++ b/activemodel/test/cases/errors_test.rb
@@ -27,14 +27,6 @@ class ErrorsTest < ActiveModel::TestCase
end
end
- def setup
- @mock_generator = MiniTest::Mock.new
- end
-
- def teardown
- @mock_generator.verify
- end
-
def test_delete
errors = ActiveModel::Errors.new(self)
errors[:foo] << 'omg'
@@ -307,8 +299,7 @@ class ErrorsTest < ActiveModel::TestCase
test "add_on_empty generates message" do
person = Person.new
- @mock_generator.expect(:call, nil, [:name, :empty, {}])
- person.errors.stub(:generate_message, @mock_generator) do
+ assert_called_with(person.errors, :generate_message, [:name, :empty, {}]) do
assert_deprecated do
person.errors.add_on_empty :name
end
@@ -317,9 +308,8 @@ class ErrorsTest < ActiveModel::TestCase
test "add_on_empty generates message for multiple attributes" do
person = Person.new
- @mock_generator.expect(:call, nil, [:name, :empty, {}])
- @mock_generator.expect(:call, nil, [:age, :empty, {}])
- person.errors.stub(:generate_message, @mock_generator) do
+ expected_calls = [ [:name, :empty, {}], [:age, :empty, {}] ]
+ assert_called_with(person.errors, :generate_message, expected_calls) do
assert_deprecated do
person.errors.add_on_empty [:name, :age]
end
@@ -328,8 +318,7 @@ class ErrorsTest < ActiveModel::TestCase
test "add_on_empty generates message with custom default message" do
person = Person.new
- @mock_generator.expect(:call, nil, [:name, :empty, { message: 'custom' }])
- person.errors.stub(:generate_message, @mock_generator) do
+ assert_called_with(person.errors, :generate_message, [:name, :empty, { message: 'custom' }]) do
assert_deprecated do
person.errors.add_on_empty :name, message: 'custom'
end
@@ -339,8 +328,7 @@ class ErrorsTest < ActiveModel::TestCase
test "add_on_empty generates message with empty string value" do
person = Person.new
person.name = ''
- @mock_generator.expect(:call, nil, [:name, :empty, {}])
- person.errors.stub(:generate_message, @mock_generator) do
+ assert_called_with(person.errors, :generate_message, [:name, :empty, {}]) do
assert_deprecated do
person.errors.add_on_empty :name
end
@@ -349,8 +337,7 @@ class ErrorsTest < ActiveModel::TestCase
test "add_on_blank generates message" do
person = Person.new
- @mock_generator.expect(:call, nil, [:name, :blank, {}])
- person.errors.stub(:generate_message, @mock_generator) do
+ assert_called_with(person.errors, :generate_message, [:name, :blank, {}]) do
assert_deprecated do
person.errors.add_on_blank :name
end
@@ -359,9 +346,8 @@ class ErrorsTest < ActiveModel::TestCase
test "add_on_blank generates message for multiple attributes" do
person = Person.new
- @mock_generator.expect(:call, nil, [:name, :blank, {}])
- @mock_generator.expect(:call, nil, [:age, :blank, {}])
- person.errors.stub(:generate_message, @mock_generator) do
+ expected_calls = [ [:name, :blank, {}], [:age, :blank, {}] ]
+ assert_called_with(person.errors, :generate_message, expected_calls) do
assert_deprecated do
person.errors.add_on_blank [:name, :age]
end
@@ -370,8 +356,7 @@ class ErrorsTest < ActiveModel::TestCase
test "add_on_blank generates message with custom default message" do
person = Person.new
- @mock_generator.expect(:call, nil, [:name, :blank, { message: 'custom' }])
- person.errors.stub(:generate_message, @mock_generator) do
+ assert_called_with(person.errors, :generate_message, [:name, :blank, { message: 'custom' }]) do
assert_deprecated do
person.errors.add_on_blank :name, message: 'custom'
end
diff --git a/activemodel/test/cases/helper.rb b/activemodel/test/cases/helper.rb
index 0d179ea9ad..c100646837 100644
--- a/activemodel/test/cases/helper.rb
+++ b/activemodel/test/cases/helper.rb
@@ -11,6 +11,7 @@ ActiveSupport::Deprecation.debug = true
I18n.enforce_available_locales = false
require 'active_support/testing/autorun'
+require 'active_support/testing/method_call_assertions'
require 'minitest/mock'
@@ -22,3 +23,7 @@ end
def jruby_skip(message = '')
skip message if defined?(JRUBY_VERSION)
end
+
+class ActiveModel::TestCase
+ include ActiveSupport::Testing::MethodCallAssertions
+end
diff --git a/activemodel/test/cases/validations/acceptance_validation_test.rb b/activemodel/test/cases/validations/acceptance_validation_test.rb
index 9c2114d83d..d3995ad5af 100644
--- a/activemodel/test/cases/validations/acceptance_validation_test.rb
+++ b/activemodel/test/cases/validations/acceptance_validation_test.rb
@@ -50,6 +50,20 @@ class AcceptanceValidationTest < ActiveModel::TestCase
assert t.valid?
end
+ def test_terms_of_service_agreement_with_multiple_accept_values
+ Topic.validates_acceptance_of(:terms_of_service, accept: [1, "I concur."])
+
+ t = Topic.new("title" => "We should be confirmed", "terms_of_service" => "")
+ assert t.invalid?
+ assert_equal ["must be accepted"], t.errors[:terms_of_service]
+
+ t.terms_of_service = 1
+ assert t.valid?
+
+ t.terms_of_service = "I concur."
+ assert t.valid?
+ end
+
def test_validates_acceptance_of_for_ruby_class
Person.validates_acceptance_of :karma
diff --git a/activemodel/test/cases/validations/exclusion_validation_test.rb b/activemodel/test/cases/validations/exclusion_validation_test.rb
index b269c3691a..005bc15df5 100644
--- a/activemodel/test/cases/validations/exclusion_validation_test.rb
+++ b/activemodel/test/cases/validations/exclusion_validation_test.rb
@@ -1,4 +1,5 @@
require 'cases/helper'
+require 'active_support/core_ext/numeric/time'
require 'models/topic'
require 'models/person'
@@ -64,6 +65,22 @@ class ExclusionValidationTest < ActiveModel::TestCase
assert t.valid?
end
+ def test_validates_exclusion_of_with_range
+ Topic.validates_exclusion_of :content, in: ("a".."g")
+
+ assert Topic.new(content: 'g').invalid?
+ assert Topic.new(content: 'h').valid?
+ end
+
+ def test_validates_exclusion_of_with_time_range
+ Topic.validates_exclusion_of :created_at, in: 6.days.ago..2.days.ago
+
+ assert Topic.new(created_at: 5.days.ago).invalid?
+ assert Topic.new(created_at: 3.days.ago).invalid?
+ assert Topic.new(created_at: 7.days.ago).valid?
+ assert Topic.new(created_at: 1.day.ago).valid?
+ end
+
def test_validates_inclusion_of_with_symbol
Person.validates_exclusion_of :karma, in: :reserved_karmas
diff --git a/activemodel/test/cases/validations/i18n_validation_test.rb b/activemodel/test/cases/validations/i18n_validation_test.rb
index 70b93a202b..ce9a782f73 100644
--- a/activemodel/test/cases/validations/i18n_validation_test.rb
+++ b/activemodel/test/cases/validations/i18n_validation_test.rb
@@ -11,7 +11,6 @@ class I18nValidationTest < ActiveModel::TestCase
I18n.load_path.clear
I18n.backend = I18n::Backend::Simple.new
I18n.backend.store_translations('en', errors: { messages: { custom: nil } })
- @mock_generator = MiniTest::Mock.new
end
def teardown
@@ -19,7 +18,6 @@ class I18nValidationTest < ActiveModel::TestCase
I18n.load_path.replace @old_load_path
I18n.backend = @old_backend
I18n.backend.reload!
- @mock_generator.verify
end
def test_full_message_encoding
@@ -32,8 +30,7 @@ class I18nValidationTest < ActiveModel::TestCase
def test_errors_full_messages_translates_human_attribute_name_for_model_attributes
@person.errors.add(:name, 'not found')
- @mock_generator.expect(:call, "Person's name", [:name, default: 'Name'])
- Person.stub(:human_attribute_name, @mock_generator) do
+ assert_called_with(Person, :human_attribute_name, [:name, default: 'Name'], returns: "Person's name") do
assert_equal ["Person's name not found"], @person.errors.full_messages
end
end
@@ -58,206 +55,175 @@ class I18nValidationTest < ActiveModel::TestCase
[ "given option that is not reserved", { format: "jpg" }, { format: "jpg" }]
]
- # validates_confirmation_of w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_confirmation_of on generated message #{name}" do
Person.validates_confirmation_of :title, validation_options
@person.title_confirmation = 'foo'
- @mock_generator.expect(:call, nil, [:title_confirmation, :confirmation, generate_message_options.merge(attribute: 'Title')])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title_confirmation, :confirmation, generate_message_options.merge(attribute: 'Title')]
+ assert_called_with(@person.errors, :generate_message, call) do
@person.valid?
end
end
end
- # validates_acceptance_of w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_acceptance_of on generated message #{name}" do
Person.validates_acceptance_of :title, validation_options.merge(allow_nil: false)
- @mock_generator.expect(:call, nil, [:title, :accepted, generate_message_options])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title, :accepted, generate_message_options]
+ assert_called_with(@person.errors, :generate_message, call) do
@person.valid?
end
end
end
- # validates_presence_of w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_presence_of on generated message #{name}" do
Person.validates_presence_of :title, validation_options
- @mock_generator.expect(:call, nil, [:title, :blank, generate_message_options])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title, :blank, generate_message_options]
+ assert_called_with(@person.errors, :generate_message, call) do
@person.valid?
end
end
end
- # validates_length_of :within too short w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_length_of for :within on generated message when too short #{name}" do
Person.validates_length_of :title, validation_options.merge(within: 3..5)
- @mock_generator.expect(:call, nil, [:title, :too_short, generate_message_options.merge(count: 3)])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title, :too_short, generate_message_options.merge(count: 3)]
+ assert_called_with(@person.errors, :generate_message, call) do
@person.valid?
end
end
end
- # validates_length_of :within too long w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_length_of for :too_long generated message #{name}" do
Person.validates_length_of :title, validation_options.merge(within: 3..5)
@person.title = 'this title is too long'
- @mock_generator.expect(:call, nil, [:title, :too_long, generate_message_options.merge(count: 5)])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title, :too_long, generate_message_options.merge(count: 5)]
+ assert_called_with(@person.errors, :generate_message, ) do
@person.valid?
end
end
end
- # validates_length_of :is w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_length_of for :is on generated message #{name}" do
Person.validates_length_of :title, validation_options.merge(is: 5)
- @mock_generator.expect(:call, nil, [:title, :wrong_length, generate_message_options.merge(count: 5)])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title, :wrong_length, generate_message_options.merge(count: 5)]
+ assert_called_with(@person.errors, :generate_message, call) do
@person.valid?
end
end
end
- # validates_format_of w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_format_of on generated message #{name}" do
Person.validates_format_of :title, validation_options.merge(with: /\A[1-9][0-9]*\z/)
@person.title = '72x'
- @mock_generator.expect(:call, nil, [:title, :invalid, generate_message_options.merge(value: '72x')])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title, :invalid, generate_message_options.merge(value: '72x')]
+ assert_called_with(@person.errors, :generate_message, call) do
@person.valid?
end
end
end
- # validates_inclusion_of w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_inclusion_of on generated message #{name}" do
Person.validates_inclusion_of :title, validation_options.merge(in: %w(a b c))
@person.title = 'z'
- @mock_generator.expect(:call, nil, [:title, :inclusion, generate_message_options.merge(value: 'z')])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title, :inclusion, generate_message_options.merge(value: 'z')]
+ assert_called_with(@person.errors, :generate_message, call) do
@person.valid?
end
end
end
- # validates_inclusion_of using :within w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_inclusion_of using :within on generated message #{name}" do
Person.validates_inclusion_of :title, validation_options.merge(within: %w(a b c))
@person.title = 'z'
- @mock_generator.expect(:call, nil, [:title, :inclusion, generate_message_options.merge(value: 'z')])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title, :inclusion, generate_message_options.merge(value: 'z')]
+ assert_called_with(@person.errors, :generate_message, call) do
@person.valid?
end
end
end
- # validates_exclusion_of w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_exclusion_of generated message #{name}" do
Person.validates_exclusion_of :title, validation_options.merge(in: %w(a b c))
@person.title = 'a'
- @mock_generator.expect(:call, nil, [:title, :exclusion, generate_message_options.merge(value: 'a')])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title, :exclusion, generate_message_options.merge(value: 'a')]
+ assert_called_with(@person.errors, :generate_message, call) do
@person.valid?
end
end
end
- # validates_exclusion_of using :within w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_exclusion_of using :within generated message #{name}" do
Person.validates_exclusion_of :title, validation_options.merge(within: %w(a b c))
@person.title = 'a'
- @mock_generator.expect(:call, nil, [:title, :exclusion, generate_message_options.merge(value: 'a')])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title, :exclusion, generate_message_options.merge(value: 'a')]
+ assert_called_with(@person.errors, :generate_message, call) do
@person.valid?
end
end
end
- # validates_numericality_of without :only_integer w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_numericality_of generated message #{name}" do
Person.validates_numericality_of :title, validation_options
@person.title = 'a'
- @mock_generator.expect(:call, nil, [:title, :not_a_number, generate_message_options.merge(value: 'a')])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title, :not_a_number, generate_message_options.merge(value: 'a')]
+ assert_called_with(@person.errors, :generate_message, call) do
@person.valid?
end
end
end
- # validates_numericality_of with :only_integer w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_numericality_of for :only_integer on generated message #{name}" do
Person.validates_numericality_of :title, validation_options.merge(only_integer: true)
@person.title = '0.0'
- @mock_generator.expect(:call, nil, [:title, :not_an_integer, generate_message_options.merge(value: '0.0')])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title, :not_an_integer, generate_message_options.merge(value: '0.0')]
+ assert_called_with(@person.errors, :generate_message, call) do
@person.valid?
end
end
end
- # validates_numericality_of :odd w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_numericality_of for :odd on generated message #{name}" do
Person.validates_numericality_of :title, validation_options.merge(only_integer: true, odd: true)
@person.title = 0
- @mock_generator.expect(:call, nil, [:title, :odd, generate_message_options.merge(value: 0)])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title, :odd, generate_message_options.merge(value: 0)]
+ assert_called_with(@person.errors, :generate_message, call) do
@person.valid?
end
end
end
- # validates_numericality_of :less_than w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_numericality_of for :less_than on generated message #{name}" do
Person.validates_numericality_of :title, validation_options.merge(only_integer: true, less_than: 0)
@person.title = 1
- @mock_generator.expect(:call, nil, [:title, :less_than, generate_message_options.merge(value: 1, count: 0)])
- @person.errors.stub(:generate_message, @mock_generator) do
+ call = [:title, :less_than, generate_message_options.merge(value: 1, count: 0)]
+ assert_called_with(@person.errors, :generate_message, call) do
@person.valid?
end
end
end
-
- # To make things DRY this macro is defined to define 3 tests for every validation case.
+ # To make things DRY this macro is created to define 3 tests for every validation case.
def self.set_expectations_for_validation(validation, error_type, &block_that_sets_validation)
if error_type == :confirmation
attribute = :title_confirmation
else
attribute = :title
end
- # test "validates_confirmation_of finds custom model key translation when blank"
+
test "#{validation} finds custom model key translation when #{error_type}" do
I18n.backend.store_translations 'en', activemodel: { errors: { models: { person: { attributes: { attribute => { error_type => 'custom message' } } } } } }
I18n.backend.store_translations 'en', errors: { messages: { error_type => 'global message'}}
@@ -267,7 +233,6 @@ class I18nValidationTest < ActiveModel::TestCase
assert_equal ['custom message'], @person.errors[attribute]
end
- # test "validates_confirmation_of finds custom model key translation with interpolation when blank"
test "#{validation} finds custom model key translation with interpolation when #{error_type}" do
I18n.backend.store_translations 'en', activemodel: { errors: { models: { person: { attributes: { attribute => { error_type => 'custom message with %{extra}' } } } } } }
I18n.backend.store_translations 'en', errors: { messages: {error_type => 'global message'} }
@@ -277,7 +242,6 @@ class I18nValidationTest < ActiveModel::TestCase
assert_equal ['custom message with extra information'], @person.errors[attribute]
end
- # test "validates_confirmation_of finds global default key translation when blank"
test "#{validation} finds global default key translation when #{error_type}" do
I18n.backend.store_translations 'en', errors: { messages: {error_type => 'global message'} }
@@ -287,27 +251,19 @@ class I18nValidationTest < ActiveModel::TestCase
end
end
- # validates_confirmation_of w/o mocha
-
set_expectations_for_validation "validates_confirmation_of", :confirmation do |person, options_to_merge|
Person.validates_confirmation_of :title, options_to_merge
person.title_confirmation = 'foo'
end
- # validates_acceptance_of w/o mocha
-
set_expectations_for_validation "validates_acceptance_of", :accepted do |person, options_to_merge|
Person.validates_acceptance_of :title, options_to_merge.merge(allow_nil: false)
end
- # validates_presence_of w/o mocha
-
set_expectations_for_validation "validates_presence_of", :blank do |person, options_to_merge|
Person.validates_presence_of :title, options_to_merge
end
- # validates_length_of :within w/o mocha
-
set_expectations_for_validation "validates_length_of", :too_short do |person, options_to_merge|
Person.validates_length_of :title, options_to_merge.merge(within: 3..5)
end
@@ -317,61 +273,43 @@ class I18nValidationTest < ActiveModel::TestCase
person.title = "too long"
end
- # validates_length_of :is w/o mocha
-
set_expectations_for_validation "validates_length_of", :wrong_length do |person, options_to_merge|
Person.validates_length_of :title, options_to_merge.merge(is: 5)
end
- # validates_format_of w/o mocha
-
set_expectations_for_validation "validates_format_of", :invalid do |person, options_to_merge|
Person.validates_format_of :title, options_to_merge.merge(with: /\A[1-9][0-9]*\z/)
end
- # validates_inclusion_of w/o mocha
-
set_expectations_for_validation "validates_inclusion_of", :inclusion do |person, options_to_merge|
Person.validates_inclusion_of :title, options_to_merge.merge(in: %w(a b c))
end
- # validates_exclusion_of w/o mocha
-
set_expectations_for_validation "validates_exclusion_of", :exclusion do |person, options_to_merge|
Person.validates_exclusion_of :title, options_to_merge.merge(in: %w(a b c))
person.title = 'a'
end
- # validates_numericality_of without :only_integer w/o mocha
-
set_expectations_for_validation "validates_numericality_of", :not_a_number do |person, options_to_merge|
Person.validates_numericality_of :title, options_to_merge
person.title = 'a'
end
- # validates_numericality_of with :only_integer w/o mocha
-
set_expectations_for_validation "validates_numericality_of", :not_an_integer do |person, options_to_merge|
Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true)
person.title = '1.0'
end
- # validates_numericality_of :odd w/o mocha
-
set_expectations_for_validation "validates_numericality_of", :odd do |person, options_to_merge|
Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true, odd: true)
person.title = 0
end
- # validates_numericality_of :less_than w/o mocha
-
set_expectations_for_validation "validates_numericality_of", :less_than do |person, options_to_merge|
Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true, less_than: 0)
person.title = 1
end
- # test with validates_with
-
def test_validations_with_message_symbol_must_translate
I18n.backend.store_translations 'en', errors: { messages: { custom_error: "I am a custom error" } }
Person.validates_presence_of :title, message: :custom_error
diff --git a/activemodel/test/cases/validations/with_validation_test.rb b/activemodel/test/cases/validations/with_validation_test.rb
index 9ee8b79da9..03c7943308 100644
--- a/activemodel/test/cases/validations/with_validation_test.rb
+++ b/activemodel/test/cases/validations/with_validation_test.rb
@@ -97,7 +97,7 @@ class ValidatesWithTest < ActiveModel::TestCase
test "passes all configuration options to the validator class" do
topic = Topic.new
- validator = MiniTest::Mock.new
+ validator = Minitest::Mock.new
validator.expect(:new, validator, [{foo: :bar, if: "1 == 1", class: Topic}])
validator.expect(:validate, nil, [topic])
validator.expect(:is_a?, false, [Symbol])
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index 9b5310b6d5..e4a6734009 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,3 +1,50 @@
+* Fix through associations using scopes having the scope merged multiple
+ times.
+
+ Fixes #20721.
+ Fixes #20727.
+
+ *Sean Griffin*
+
+* `ActiveRecord::Base.dump_schema_after_migration` applies migration tasks
+ other than `db:migrate`. (eg. `db:rollback`, `db:migrate:dup`, ...)
+
+ Fixes #20743.
+
+ *Yves Senn*
+
+* Add alternate syntax to make `change_column_default` reversible.
+
+ User can pass in `:from` and `:to` to make `change_column_default` command
+ become reversible.
+
+ Example:
+
+ change_column_default :posts, :status, from: nil, to: "draft"
+ change_column_default :users, :authorized, from: true, to: false
+
+ *Prem Sichanugrist*
+
+* Prevent error when using `force_reload: true` on an unassigned polymorphic
+ belongs_to association.
+
+ Fixes #20426.
+
+ *James Dabbs*
+
+* Correctly raise `ActiveRecord::AssociationTypeMismatch` when assigning
+ a wrong type to a namespaced association.
+
+ Fixes #20545.
+
+ *Diego Carrion*
+
+* `validates_absence_of` respects `marked_for_destruction?`.
+
+ Fixes #20449.
+
+ *Yves Senn*
+
* Include the `Enumerable` module in `ActiveRecord::Relation`
*Sean Griffin & bogdan*
diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb
index 930f678ae8..7c729676a7 100644
--- a/activerecord/lib/active_record/associations/association.rb
+++ b/activerecord/lib/active_record/associations/association.rb
@@ -211,9 +211,12 @@ module ActiveRecord
# the kind of the class of the associated objects. Meant to be used as
# a sanity check when you are about to assign an associated record.
def raise_on_type_mismatch!(record)
- unless record.is_a?(reflection.klass) || record.is_a?(reflection.class_name.constantize)
- message = "#{reflection.class_name}(##{reflection.klass.object_id}) expected, got #{record.class}(##{record.class.object_id})"
- raise ActiveRecord::AssociationTypeMismatch, message
+ unless record.is_a?(reflection.klass)
+ fresh_class = reflection.class_name.safe_constantize
+ unless fresh_class && record.is_a?(fresh_class)
+ message = "#{reflection.class_name}(##{reflection.klass.object_id}) expected, got #{record.class}(##{record.class.object_id})"
+ raise ActiveRecord::AssociationTypeMismatch, message
+ end
end
end
diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb
index 2416167834..a140dc239c 100644
--- a/activerecord/lib/active_record/associations/association_scope.rb
+++ b/activerecord/lib/active_record/associations/association_scope.rb
@@ -149,6 +149,7 @@ module ActiveRecord
scope.where_clause += item.where_clause
scope.order_values |= item.order_values
+ scope.unscope!(*item.unscope_values)
end
reflection = reflection.next
diff --git a/activerecord/lib/active_record/associations/preloader.rb b/activerecord/lib/active_record/associations/preloader.rb
index 97f4bd3811..6ecc741195 100644
--- a/activerecord/lib/active_record/associations/preloader.rb
+++ b/activerecord/lib/active_record/associations/preloader.rb
@@ -10,13 +10,13 @@ module ActiveRecord
# end
#
# class Book < ActiveRecord::Base
- # # columns: title, sales
+ # # columns: title, sales, author_id
# end
#
# When you load an author with all associated books Active Record will make
# multiple queries like this:
#
- # Author.includes(:books).where(:name => ['bell hooks', 'Homer').to_a
+ # Author.includes(:books).where(name: ['bell hooks', 'Homer']).to_a
#
# => SELECT `authors`.* FROM `authors` WHERE `name` IN ('bell hooks', 'Homer')
# => SELECT `books`.* FROM `books` WHERE `author_id` IN (2, 5)
@@ -160,7 +160,7 @@ module ActiveRecord
h
end
- class AlreadyLoaded
+ class AlreadyLoaded # :nodoc:
attr_reader :owners, :reflection
def initialize(klass, owners, reflection, preload_scope)
@@ -175,7 +175,7 @@ module ActiveRecord
end
end
- class NullPreloader
+ class NullPreloader # :nodoc:
def self.new(klass, owners, reflection, preload_scope); self; end
def self.run(preloader); end
def self.preloaded_records; []; end
diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb
index 58d0f7d65d..bec9505bd2 100644
--- a/activerecord/lib/active_record/associations/singular_association.rb
+++ b/activerecord/lib/active_record/associations/singular_association.rb
@@ -3,7 +3,7 @@ module ActiveRecord
class SingularAssociation < Association #:nodoc:
# Implements the reader method, e.g. foo.bar for Foo.has_one :bar
def reader(force_reload = false)
- if force_reload
+ if force_reload && klass
klass.uncached { reload }
elsif !loaded? || stale_target?
reload
diff --git a/activerecord/lib/active_record/associations/through_association.rb b/activerecord/lib/active_record/associations/through_association.rb
index af1bce523c..55ee9f04e0 100644
--- a/activerecord/lib/active_record/associations/through_association.rb
+++ b/activerecord/lib/active_record/associations/through_association.rb
@@ -15,12 +15,6 @@ module ActiveRecord
scope = super
reflection.chain.drop(1).each do |reflection|
relation = reflection.klass.all
-
- reflection_scope = reflection.scope
- if reflection_scope && reflection_scope.arity.zero?
- relation = relation.merge(reflection_scope)
- end
-
scope.merge!(
relation.except(:select, :create_with, :includes, :preload, :joins, :eager_load)
)
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
index 158b773e11..d17e272ed1 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -592,10 +592,11 @@ module ActiveRecord
#
# t.change_default(:qualification, 'new')
# t.change_default(:authorized, 1)
+ # t.change_default(:status, from: nil, to: "draft")
#
# See SchemaStatements#change_column_default
- def change_default(column_name, default)
- @base.change_column_default(name, column_name, default)
+ def change_default(column_name, default_or_changes)
+ @base.change_column_default(name, column_name, default_or_changes)
end
# Removes the column(s) from the table definition.
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 49ffd7ccf0..e3115abe66 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -460,7 +460,12 @@ module ActiveRecord
#
# change_column_default(:users, :email, nil)
#
- def change_column_default(table_name, column_name, default)
+ # Passing a hash containing +:from+ and +:to+ will make this change
+ # reversible in migration:
+ #
+ # change_column_default(:posts, :state, from: nil, to: "draft")
+ #
+ def change_column_default(table_name, column_name, default_or_changes)
raise NotImplementedError, "change_column_default is not implemented"
end
@@ -832,7 +837,10 @@ module ActiveRecord
end
def foreign_key_column_for(table_name) # :nodoc:
- "#{table_name.to_s.singularize}_id"
+ prefix = Base.table_name_prefix
+ suffix = Base.table_name_suffix
+ name = table_name.to_s =~ /#{prefix}(.+)#{suffix}/ ? $1 : table_name.to_s
+ "#{name.singularize}_id"
end
def dump_schema_information #:nodoc:
@@ -1068,6 +1076,14 @@ module ActiveRecord
raise ArgumentError, "Index name '#{new_name}' on table '#{table_name}' is too long; the limit is #{allowed_index_name_length} characters"
end
end
+
+ def extract_new_default_value(default_or_changes)
+ if default_or_changes.is_a?(Hash) && default_or_changes.has_key?(:from) && default_or_changes.has_key?(:to)
+ default_or_changes[:to]
+ else
+ default_or_changes
+ end
+ end
end
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
index 00e3d2965b..2027492f29 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
@@ -629,7 +629,8 @@ module ActiveRecord
end
end
- def change_column_default(table_name, column_name, default) #:nodoc:
+ def change_column_default(table_name, column_name, default_or_changes) #:nodoc:
+ default = extract_new_default_value(default_or_changes)
column = column_for(table_name, column_name)
change_column table_name, column_name, column.sql_type, :default => default
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
index 595c635fc0..d114cad16b 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
@@ -410,11 +410,12 @@ module ActiveRecord
end
# Changes the default value of a table column.
- def change_column_default(table_name, column_name, default) # :nodoc:
+ def change_column_default(table_name, column_name, default_or_changes) # :nodoc:
clear_cache!
column = column_for(table_name, column_name)
return unless column
+ default = extract_new_default_value(default_or_changes)
alter_column_query = "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} %s"
if default.nil?
# <tt>DEFAULT NULL</tt> results in the same behavior as <tt>DROP DEFAULT</tt>. However, PostgreSQL will
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
index 87129c42cf..7c809b088c 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
@@ -422,7 +422,9 @@ module ActiveRecord
end
end
- def change_column_default(table_name, column_name, default) #:nodoc:
+ def change_column_default(table_name, column_name, default_or_changes) #:nodoc:
+ default = extract_new_default_value(default_or_changes)
+
alter_table(table_name) do |definition|
definition[column_name].default = default
end
diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb
index b01444a090..d062dd9e34 100644
--- a/activerecord/lib/active_record/fixtures.rb
+++ b/activerecord/lib/active_record/fixtures.rb
@@ -645,7 +645,9 @@ module ActiveRecord
# Resolve enums
model_class.defined_enums.each do |name, values|
- row[name] = values.fetch(row[name], row[name])
+ if row.include?(name)
+ row[name] = values.fetch(row[name], row[name])
+ end
end
# If STI is used, find the correct subclass for association reflection
diff --git a/activerecord/lib/active_record/log_subscriber.rb b/activerecord/lib/active_record/log_subscriber.rb
index af816a278e..4d597a0ab1 100644
--- a/activerecord/lib/active_record/log_subscriber.rb
+++ b/activerecord/lib/active_record/log_subscriber.rb
@@ -47,18 +47,21 @@ module ActiveRecord
binds = " " + payload[:binds].map { |attr| render_bind(attr) }.inspect
end
- if odd?
- name = color(name, CYAN, true)
- sql = color(sql, nil, true)
- else
- name = color(name, MAGENTA, true)
- end
+ name = color(name, nil, true)
+ sql = color(sql, sql_color(sql), true)
debug " #{name} #{sql}#{binds}"
end
- def odd?
- @odd = !@odd
+ def sql_color(sql)
+ case sql
+ when /\s*\Ainsert/i then GREEN
+ when /\s*\Aselect/i then BLUE
+ when /\s*\Aupdate/i then YELLOW
+ when /\s*\Adelete/i then RED
+ when /transaction\s*\Z/i then CYAN
+ else MAGENTA
+ end
end
def logger
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index d41b7e88d5..4cfda302ea 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -640,7 +640,8 @@ module ActiveRecord
unless @connection.respond_to? :revert
unless arguments.empty? || [:execute, :enable_extension, :disable_extension].include?(method)
arguments[0] = proper_table_name(arguments.first, table_name_options)
- if [:rename_table, :add_foreign_key].include?(method)
+ if [:rename_table, :add_foreign_key].include?(method) ||
+ (method == :remove_foreign_key && !arguments.second.is_a?(Hash))
arguments[1] = proper_table_name(arguments.second, table_name_options)
end
end
diff --git a/activerecord/lib/active_record/migration/command_recorder.rb b/activerecord/lib/active_record/migration/command_recorder.rb
index b592c004aa..dcc2362397 100644
--- a/activerecord/lib/active_record/migration/command_recorder.rb
+++ b/activerecord/lib/active_record/migration/command_recorder.rb
@@ -72,7 +72,7 @@ module ActiveRecord
[:create_table, :create_join_table, :rename_table, :add_column, :remove_column,
:rename_index, :rename_column, :add_index, :remove_index, :add_timestamps, :remove_timestamps,
- :change_column_default, :add_reference, :remove_reference, :transaction,
+ :add_reference, :remove_reference, :transaction,
:drop_join_table, :drop_table, :execute_block, :enable_extension,
:change_column, :execute, :remove_columns, :change_column_null,
:add_foreign_key, :remove_foreign_key
@@ -166,6 +166,16 @@ module ActiveRecord
alias :invert_add_belongs_to :invert_add_reference
alias :invert_remove_belongs_to :invert_remove_reference
+ def invert_change_column_default(args)
+ table, column, options = *args
+
+ unless options && options.is_a?(Hash) && options.has_key?(:from) && options.has_key?(:to)
+ raise ActiveRecord::IrreversibleMigration, "change_column_default is only reversible if given a :from and :to option."
+ end
+
+ [:change_column_default, [table, column, from: options[:to], to: options[:from]]]
+ end
+
def invert_change_column_null(args)
args[2] = !args[2]
[:change_column_null, args]
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index 66fb3ae44b..6a72d528b4 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -42,15 +42,18 @@ db_namespace = namespace :db do
desc "Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)."
task :migrate => [:environment, :load_config] do
ActiveRecord::Tasks::DatabaseTasks.migrate
- db_namespace['_dump'].invoke if ActiveRecord::Base.dump_schema_after_migration
+ db_namespace['_dump'].invoke
end
+ # IMPORTANT: This task won't dump the schema if ActiveRecord::Base.dump_schema_after_migration is set to false
task :_dump do
- case ActiveRecord::Base.schema_format
- when :ruby then db_namespace["schema:dump"].invoke
- when :sql then db_namespace["structure:dump"].invoke
- else
- raise "unknown schema format #{ActiveRecord::Base.schema_format}"
+ if ActiveRecord::Base.dump_schema_after_migration
+ case ActiveRecord::Base.schema_format
+ when :ruby then db_namespace["schema:dump"].invoke
+ when :sql then db_namespace["structure:dump"].invoke
+ else
+ raise "unknown schema format #{ActiveRecord::Base.schema_format}"
+ end
end
# Allow this task to be called as many times as required. An example is the
# migrate:redo task, which calls other two internally that depend on this one.
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index 7108b087f1..0f6015fa93 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -139,7 +139,7 @@ module ActiveRecord
# # SELECT people.id, people.name FROM people
# # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
#
- # Person.pluck('DISTINCT role')
+ # Person.distinct.pluck(:role)
# # SELECT DISTINCT role FROM people
# # => ['admin', 'member', 'guest']
#
@@ -195,7 +195,8 @@ module ActiveRecord
def perform_calculation(operation, column_name)
operation = operation.to_s.downcase
- # If #count is used with #distinct / #uniq it is considered distinct. (eg. relation.distinct.count)
+ # If #count is used with #distinct (i.e. `relation.distinct.count`) it is
+ # considered distinct.
distinct = self.distinct_value
if operation == "count"
diff --git a/activerecord/lib/active_record/relation/merger.rb b/activerecord/lib/active_record/relation/merger.rb
index dd8f0aa298..0b38666ce9 100644
--- a/activerecord/lib/active_record/relation/merger.rb
+++ b/activerecord/lib/active_record/relation/merger.rb
@@ -87,8 +87,8 @@ module ActiveRecord
return if other.preload_values.empty? && other.includes_values.empty?
if other.klass == relation.klass
- relation.preload! other.preload_values unless other.preload_values.empty?
- relation.includes! other.includes_values unless other.includes_values.empty?
+ relation.preload!(*other.preload_values) unless other.preload_values.empty?
+ relation.includes!(other.includes_values) unless other.includes_values.empty?
else
reflection = relation.klass.reflect_on_all_associations.find do |r|
r.class_name == other.klass.name
diff --git a/activerecord/lib/active_record/table_metadata.rb b/activerecord/lib/active_record/table_metadata.rb
index 3dd6321a97..41f1c55c3c 100644
--- a/activerecord/lib/active_record/table_metadata.rb
+++ b/activerecord/lib/active_record/table_metadata.rb
@@ -41,7 +41,7 @@ module ActiveRecord
association = klass._reflect_on_association(table_name)
if association && !association.polymorphic?
association_klass = association.klass
- arel_table = association_klass.arel_table
+ arel_table = association_klass.arel_table.alias(table_name)
else
type_caster = TypeCaster::Connection.new(klass, table_name)
association_klass = nil
diff --git a/activerecord/lib/active_record/type/decimal.rb b/activerecord/lib/active_record/type/decimal.rb
index 867b5f75c7..f200a92d10 100644
--- a/activerecord/lib/active_record/type/decimal.rb
+++ b/activerecord/lib/active_record/type/decimal.rb
@@ -8,7 +8,7 @@ module ActiveRecord
end
def type_cast_for_schema(value)
- value.to_s
+ value.to_s.inspect
end
private
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index e227212827..34d96b19fe 100644
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -76,4 +76,5 @@ end
require "active_record/validations/associated"
require "active_record/validations/uniqueness"
require "active_record/validations/presence"
+require "active_record/validations/absence"
require "active_record/validations/length"
diff --git a/activerecord/lib/active_record/validations/absence.rb b/activerecord/lib/active_record/validations/absence.rb
new file mode 100644
index 0000000000..2e19e6dc5c
--- /dev/null
+++ b/activerecord/lib/active_record/validations/absence.rb
@@ -0,0 +1,24 @@
+module ActiveRecord
+ module Validations
+ class AbsenceValidator < ActiveModel::Validations::AbsenceValidator # :nodoc:
+ def validate_each(record, attribute, association_or_value)
+ return unless should_validate?(record)
+ if record.class._reflect_on_association(attribute)
+ association_or_value = Array.wrap(association_or_value).reject(&:marked_for_destruction?)
+ end
+ super
+ end
+ end
+
+ module ClassMethods
+ # Validates that the specified attributes are not present (as defined by
+ # Object#present?). If the attribute is an association, the associated object
+ # is considered absent if it was marked for destruction.
+ #
+ # See ActiveModel::Validations::HelperMethods.validates_absence_of for more information.
+ def validates_absence_of(*attr_names)
+ validates_with AbsenceValidator, _merge_attributes(attr_names)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/validations/length.rb b/activerecord/lib/active_record/validations/length.rb
index 5991fbad8e..69e048eef1 100644
--- a/activerecord/lib/active_record/validations/length.rb
+++ b/activerecord/lib/active_record/validations/length.rb
@@ -22,7 +22,10 @@ module ActiveRecord
end
module ClassMethods
- # See <tt>ActiveModel::Validation::LengthValidator</tt> for more information.
+ # Validates that the specified attributes match the length restrictions supplied.
+ # If the attribute is an association, records that are marked for destruction are not counted.
+ #
+ # See ActiveModel::Validations::HelperMethods.validates_length_of for more information.
def validates_length_of(*attr_names)
validates_with LengthValidator, _merge_attributes(attr_names)
end
diff --git a/activerecord/lib/active_record/validations/presence.rb b/activerecord/lib/active_record/validations/presence.rb
index a9b791397b..23a3985d35 100644
--- a/activerecord/lib/active_record/validations/presence.rb
+++ b/activerecord/lib/active_record/validations/presence.rb
@@ -1,18 +1,12 @@
module ActiveRecord
module Validations
class PresenceValidator < ActiveModel::Validations::PresenceValidator # :nodoc:
- def validate(record)
+ def validate_each(record, attribute, association_or_value)
return unless should_validate?(record)
- super
- attributes.each do |attribute|
- next unless record.class._reflect_on_association(attribute)
- associated_records = Array.wrap(record.send(attribute))
-
- # Superclass validates presence. Ensure present records aren't about to be destroyed.
- if associated_records.present? && associated_records.all?(&:marked_for_destruction?)
- record.errors.add(attribute, :blank, options)
- end
+ if record.class._reflect_on_association(attribute)
+ association_or_value = Array.wrap(association_or_value).reject(&:marked_for_destruction?)
end
+ super
end
end
diff --git a/activerecord/test/cases/adapters/postgresql/money_test.rb b/activerecord/test/cases/adapters/postgresql/money_test.rb
index e3670c203d..c031178479 100644
--- a/activerecord/test/cases/adapters/postgresql/money_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/money_test.rb
@@ -56,7 +56,7 @@ class PostgresqlMoneyTest < ActiveRecord::PostgreSQLTestCase
def test_schema_dumping
output = dump_table_schema("postgresql_moneys")
assert_match %r{t\.money\s+"wealth",\s+scale: 2$}, output
- assert_match %r{t\.money\s+"depth",\s+scale: 2,\s+default: 150\.55$}, output
+ assert_match %r{t\.money\s+"depth",\s+scale: 2,\s+default: "150\.55"$}, output
end
def test_create_and_update_money
diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb
index 9aba2b5976..35d5581aa7 100644
--- a/activerecord/test/cases/adapters/postgresql/schema_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb
@@ -480,6 +480,7 @@ class DefaultsUsingMultipleSchemasAndDomainTest < ActiveRecord::PostgreSQLTestCa
@connection.create_table "defaults" do |t|
t.text "text_col", default: "some value"
t.string "string_col", default: "some value"
+ t.decimal "decimal_col", default: "3.14159265358979323846"
end
Default.reset_column_information
end
@@ -498,6 +499,10 @@ class DefaultsUsingMultipleSchemasAndDomainTest < ActiveRecord::PostgreSQLTestCa
assert_equal "some value", Default.new.string_col, "Default of string column was not correctly parsed"
end
+ def test_decimal_defaults_in_new_schema_when_overriding_domain
+ assert_equal BigDecimal.new("3.14159265358979323846"), Default.new.decimal_col, "Default of decimal column was not correctly parsed"
+ end
+
def test_bpchar_defaults_in_new_schema_when_overriding_domain
@connection.execute "ALTER TABLE defaults ADD bpchar_col bpchar DEFAULT 'some value'"
Default.reset_column_information
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index 039cc46b0b..ebe08c618f 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -19,6 +19,8 @@ require 'models/invoice'
require 'models/line_item'
require 'models/column'
require 'models/record'
+require 'models/admin'
+require 'models/admin/user'
class BelongsToAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :developers, :projects, :topics,
@@ -151,6 +153,30 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = Project.find(1) }
end
+ def test_raises_type_mismatch_with_namespaced_class
+ assert_nil defined?(Region), "This test requires that there is no top-level Region class"
+
+ ActiveRecord::Base.connection.instance_eval do
+ create_table(:admin_regions) { |t| t.string :name }
+ add_column :admin_users, :region_id, :integer
+ end
+ Admin.const_set "RegionalUser", Class.new(Admin::User) { belongs_to(:region) }
+ Admin.const_set "Region", Class.new(ActiveRecord::Base)
+
+ e = assert_raise(ActiveRecord::AssociationTypeMismatch) {
+ Admin::RegionalUser.new(region: 'wrong value')
+ }
+ assert_match(/^Region\([^)]+\) expected, got String\([^)]+\)$/, e.message)
+ ensure
+ Admin.send :remove_const, "Region" if Admin.const_defined?("Region")
+ Admin.send :remove_const, "RegionalUser" if Admin.const_defined?("RegionalUser")
+
+ ActiveRecord::Base.connection.instance_eval do
+ remove_column :admin_users, :region_id if column_exists?(:admin_users, :region_id)
+ drop_table :admin_regions, if_exists: true
+ end
+ end
+
def test_natural_assignment
apple = Firm.create("name" => "Apple")
citibank = Account.create("credit_limit" => 10)
@@ -292,9 +318,11 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
def test_polymorphic_association_class
sponsor = Sponsor.new
assert_nil sponsor.association(:sponsorable).send(:klass)
+ assert_nil sponsor.sponsorable(force_reload: true)
sponsor.sponsorable_type = '' # the column doesn't have to be declared NOT NULL
assert_nil sponsor.association(:sponsorable).send(:klass)
+ assert_nil sponsor.sponsorable(force_reload: true)
sponsor.sponsorable = Member.new :name => "Bert"
assert_equal Member, sponsor.association(:sponsorable).send(:klass)
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 1d545af5a5..c34387f06d 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -1158,4 +1158,11 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
post_through = organization.posts.build
assert_equal post_direct.author_id, post_through.author_id
end
+
+ def test_has_many_through_with_scope_that_should_not_be_fully_merged
+ Club.has_many :distinct_memberships, -> { distinct }, class_name: "Membership"
+ Club.has_many :special_favourites, through: :distinct_memberships, source: :member
+
+ assert_nil Club.new.special_favourites.distinct_value
+ end
end
diff --git a/activerecord/test/cases/enum_test.rb b/activerecord/test/cases/enum_test.rb
index 769b171717..ba23049a92 100644
--- a/activerecord/test/cases/enum_test.rb
+++ b/activerecord/test/cases/enum_test.rb
@@ -405,4 +405,10 @@ class EnumTest < ActiveRecord::TestCase
assert_not @book.in_spanish?
assert_not @book.in_french?
end
+
+ test "uses default status when no status is provided in fixtures" do
+ book = books(:tlg)
+ assert book.proposed?, "expected fixture to default to proposed status"
+ assert book.in_english?, "expected fixture to default to english language"
+ end
end
diff --git a/activerecord/test/cases/migration/columns_test.rb b/activerecord/test/cases/migration/columns_test.rb
index 5fc7702dfa..ab3f584350 100644
--- a/activerecord/test/cases/migration/columns_test.rb
+++ b/activerecord/test/cases/migration/columns_test.rb
@@ -267,6 +267,13 @@ module ActiveRecord
assert_nil TestModel.new.first_name
end
+ def test_change_column_default_with_from_and_to
+ add_column "test_models", "first_name", :string
+ connection.change_column_default "test_models", "first_name", from: nil, to: "Tester"
+
+ assert_equal "Tester", TestModel.new.first_name
+ end
+
def test_remove_column_no_second_parameter_raises_exception
assert_raise(ArgumentError) { connection.remove_column("funny") }
end
diff --git a/activerecord/test/cases/migration/command_recorder_test.rb b/activerecord/test/cases/migration/command_recorder_test.rb
index 90b7c6b38a..99f1dc65b0 100644
--- a/activerecord/test/cases/migration/command_recorder_test.rb
+++ b/activerecord/test/cases/migration/command_recorder_test.rb
@@ -169,6 +169,16 @@ module ActiveRecord
end
end
+ def test_invert_change_column_default_with_from_and_to
+ change = @recorder.inverse_of :change_column_default, [:table, :column, from: "old_value", to: "new_value"]
+ assert_equal [:change_column_default, [:table, :column, from: "new_value", to: "old_value"]], change
+ end
+
+ def test_invert_change_column_default_with_from_and_to_with_boolean
+ change = @recorder.inverse_of :change_column_default, [:table, :column, from: true, to: false]
+ assert_equal [:change_column_default, [:table, :column, from: false, to: true]], change
+ end
+
def test_invert_change_column_null
add = @recorder.inverse_of :change_column_null, [:table, :column, true]
assert_equal [:change_column_null, [:table, :column, false]], add
diff --git a/activerecord/test/cases/migration/foreign_key_test.rb b/activerecord/test/cases/migration/foreign_key_test.rb
index 7f4790bf3e..72f2fa95f1 100644
--- a/activerecord/test/cases/migration/foreign_key_test.rb
+++ b/activerecord/test/cases/migration/foreign_key_test.rb
@@ -243,6 +243,37 @@ module ActiveRecord
silence_stream($stdout) { migration.migrate(:down) }
end
+ class CreateSchoolsAndClassesMigration < ActiveRecord::Migration
+ def change
+ create_table(:schools)
+
+ create_table(:classes) do |t|
+ t.column :school_id, :integer
+ end
+ add_foreign_key :classes, :schools
+ end
+ end
+
+ def test_add_foreign_key_with_prefix
+ ActiveRecord::Base.table_name_prefix = 'p_'
+ migration = CreateSchoolsAndClassesMigration.new
+ silence_stream($stdout) { migration.migrate(:up) }
+ assert_equal 1, @connection.foreign_keys("p_classes").size
+ ensure
+ silence_stream($stdout) { migration.migrate(:down) }
+ ActiveRecord::Base.table_name_prefix = nil
+ end
+
+ def test_add_foreign_key_with_suffix
+ ActiveRecord::Base.table_name_suffix = '_s'
+ migration = CreateSchoolsAndClassesMigration.new
+ silence_stream($stdout) { migration.migrate(:up) }
+ assert_equal 1, @connection.foreign_keys("classes_s").size
+ ensure
+ silence_stream($stdout) { migration.migrate(:down) }
+ ActiveRecord::Base.table_name_suffix = nil
+ end
+
end
end
end
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index 6b4addd52f..d72225f3d3 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -658,6 +658,16 @@ module NestedAttributesOnACollectionAssociationTests
assert_equal "Couldn't find #{@child_1.class.name} with ID=1234567890 for Pirate with ID=#{@pirate.id}", exception.message
end
+ def test_should_raise_RecordNotFound_if_an_id_belonging_to_a_different_record_is_given
+ other_pirate = Pirate.create! catchphrase: 'Ahoy!'
+ other_child = other_pirate.send(@association_name).create! name: 'Buccaneers Servant'
+
+ exception = assert_raise ActiveRecord::RecordNotFound do
+ @pirate.attributes = { association_getter => [{ id: other_child.id }] }
+ end
+ assert_equal "Couldn't find #{@child_1.class.name} with ID=#{other_child.id} for Pirate with ID=#{@pirate.id}", exception.message
+ end
+
def test_should_automatically_build_new_associated_models_for_each_entry_in_a_hash_where_the_id_is_missing
@pirate.send(@association_name).destroy_all
@pirate.reload.attributes = {
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index acbf85d398..5f48c2b40f 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -647,6 +647,25 @@ class RelationTest < ActiveRecord::TestCase
end
end
+ def test_preloading_with_associations_default_scopes_and_merges
+ post = Post.create! title: 'Uhuu', body: 'body'
+ reader = Reader.create! post_id: post.id, person_id: 1
+
+ post_rel = PostWithPreloadDefaultScope.preload(:readers).joins(:readers).where(title: 'Uhuu')
+ result_post = PostWithPreloadDefaultScope.all.merge(post_rel).to_a.first
+
+ assert_no_queries do
+ assert_equal [reader], result_post.readers.to_a
+ end
+
+ post_rel = PostWithIncludesDefaultScope.includes(:readers).where(title: 'Uhuu')
+ result_post = PostWithIncludesDefaultScope.all.merge(post_rel).to_a.first
+
+ assert_no_queries do
+ assert_equal [reader], result_post.readers.to_a
+ end
+ end
+
def test_loading_with_one_association
posts = Post.preload(:comments)
post = posts.find { |p| p.id == 1 }
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index 51170c533b..feb1c29656 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -239,7 +239,7 @@ class SchemaDumperTest < ActiveRecord::TestCase
def test_schema_dump_includes_decimal_options
output = dump_all_table_schema([/^[^n]/])
- assert_match %r{precision: 3,[[:space:]]+scale: 2,[[:space:]]+default: 2\.78}, output
+ assert_match %r{precision: 3,[[:space:]]+scale: 2,[[:space:]]+default: "2\.78"}, output
end
if current_adapter?(:PostgreSQLAdapter)
@@ -255,7 +255,7 @@ class SchemaDumperTest < ActiveRecord::TestCase
def test_schema_dump_allows_array_of_decimal_defaults
output = standard_dump
- assert_match %r{t\.decimal\s+"decimal_array_default",\s+default: \[1.23, 3.45\],\s+array: true}, output
+ assert_match %r{t\.decimal\s+"decimal_array_default",\s+default: \["1.23", "3.45"\],\s+array: true}, output
end
if ActiveRecord::Base.connection.supports_extensions?
diff --git a/activerecord/test/cases/touch_later_test.rb b/activerecord/test/cases/touch_later_test.rb
index 11804ff90b..49ada22529 100644
--- a/activerecord/test/cases/touch_later_test.rb
+++ b/activerecord/test/cases/touch_later_test.rb
@@ -2,8 +2,11 @@ require 'cases/helper'
require 'models/invoice'
require 'models/line_item'
require 'models/topic'
+require 'models/node'
+require 'models/tree'
class TouchLaterTest < ActiveRecord::TestCase
+ fixtures :nodes, :trees
def test_touch_laster_raise_if_non_persisted
invoice = Invoice.new
@@ -90,4 +93,22 @@ class TouchLaterTest < ActiveRecord::TestCase
invoice.touch_later
end
end
+
+ def test_touching_three_deep
+ skip "Pending from #19324"
+
+ previous_tree_updated_at = trees(:root).updated_at
+ previous_grandparent_updated_at = nodes(:grandparent).updated_at
+ previous_parent_updated_at = nodes(:parent_a).updated_at
+ previous_child_updated_at = nodes(:child_one_of_a).updated_at
+
+ travel 5.seconds
+
+ Node.create! parent: nodes(:child_one_of_a), tree: trees(:root)
+
+ assert_not_equal nodes(:child_one_of_a).reload.updated_at, previous_child_updated_at
+ assert_not_equal nodes(:parent_a).reload.updated_at, previous_parent_updated_at
+ assert_not_equal nodes(:grandparent).reload.updated_at, previous_grandparent_updated_at
+ assert_not_equal trees(:root).reload.updated_at, previous_tree_updated_at
+ end
end
diff --git a/activerecord/test/cases/validations/absence_validation_test.rb b/activerecord/test/cases/validations/absence_validation_test.rb
new file mode 100644
index 0000000000..dd43ee358c
--- /dev/null
+++ b/activerecord/test/cases/validations/absence_validation_test.rb
@@ -0,0 +1,75 @@
+require "cases/helper"
+require 'models/face'
+require 'models/interest'
+require 'models/man'
+require 'models/topic'
+
+class AbsenceValidationTest < ActiveRecord::TestCase
+ def test_non_association
+ boy_klass = Class.new(Man) do
+ def self.name; "Boy" end
+ validates_absence_of :name
+ end
+
+ assert boy_klass.new.valid?
+ assert_not boy_klass.new(name: "Alex").valid?
+ end
+
+ def test_has_one_marked_for_destruction
+ boy_klass = Class.new(Man) do
+ def self.name; "Boy" end
+ validates_absence_of :face
+ end
+
+ boy = boy_klass.new(face: Face.new)
+ assert_not boy.valid?, "should not be valid if has_one association is present"
+ assert_equal 1, boy.errors[:face].size, "should only add one error"
+
+ boy.face.mark_for_destruction
+ assert boy.valid?, "should be valid if association is marked for destruction"
+ end
+
+ def test_has_many_marked_for_destruction
+ boy_klass = Class.new(Man) do
+ def self.name; "Boy" end
+ validates_absence_of :interests
+ end
+ boy = boy_klass.new
+ boy.interests << [i1 = Interest.new, i2 = Interest.new]
+ assert_not boy.valid?, "should not be valid if has_many association is present"
+
+ i1.mark_for_destruction
+ assert_not boy.valid?, "should not be valid if has_many association is present"
+
+ i2.mark_for_destruction
+ assert boy.valid?
+ end
+
+ def test_does_not_call_to_a_on_associations
+ boy_klass = Class.new(Man) do
+ def self.name; "Boy" end
+ validates_absence_of :face
+ end
+
+ face_with_to_a = Face.new
+ def face_with_to_a.to_a; ['(/)', '(\)']; end
+
+ assert_nothing_raised { boy_klass.new(face: face_with_to_a).valid? }
+ end
+
+ def test_does_not_validate_if_parent_record_is_validate_false
+ repair_validations(Interest) do
+ Interest.validates_absence_of(:topic)
+ interest = Interest.new(topic: Topic.new(title: "Math"))
+ interest.save!(validate: false)
+ assert interest.persisted?
+
+ man = Man.new(interest_ids: [interest.id])
+ man.save!
+
+ assert_equal man.interests.size, 1
+ assert interest.valid?
+ assert man.valid?
+ end
+ end
+end
diff --git a/activerecord/test/fixtures/books.yml b/activerecord/test/fixtures/books.yml
index 93cfabd61c..a304fba399 100644
--- a/activerecord/test/fixtures/books.yml
+++ b/activerecord/test/fixtures/books.yml
@@ -24,3 +24,8 @@ ddd:
name: "Domain-Driven Design"
format: "hardcover"
status: 2
+
+tlg:
+ author_id: 1
+ id: 4
+ name: "Thoughtleadering"
diff --git a/activerecord/test/fixtures/nodes.yml b/activerecord/test/fixtures/nodes.yml
new file mode 100644
index 0000000000..b8bb8216ee
--- /dev/null
+++ b/activerecord/test/fixtures/nodes.yml
@@ -0,0 +1,29 @@
+grandparent:
+ id: 1
+ tree_id: 1
+ name: Grand Parent
+
+parent_a:
+ id: 2
+ tree_id: 1
+ parent_id: 1
+ name: Parent A
+
+parent_b:
+ id: 3
+ tree_id: 1
+ parent_id: 1
+ name: Parent B
+
+child_one_of_a:
+ id: 4
+ tree_id: 1
+ parent_id: 2
+ name: Child one
+
+child_two_of_b:
+ id: 5
+ tree_id: 1
+ parent_id: 2
+ name: Child two
+
diff --git a/activerecord/test/fixtures/trees.yml b/activerecord/test/fixtures/trees.yml
new file mode 100644
index 0000000000..9e030b7632
--- /dev/null
+++ b/activerecord/test/fixtures/trees.yml
@@ -0,0 +1,3 @@
+root:
+ id: 1
+ name: The Root
diff --git a/activerecord/test/models/node.rb b/activerecord/test/models/node.rb
new file mode 100644
index 0000000000..07dd2dbccb
--- /dev/null
+++ b/activerecord/test/models/node.rb
@@ -0,0 +1,5 @@
+class Node < ActiveRecord::Base
+ belongs_to :tree, touch: true
+ belongs_to :parent, class_name: 'Node', touch: true, optional: true
+ has_many :children, class_name: 'Node', foreign_key: :parent_id, dependent: :destroy
+end
diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb
index 052b1c9690..10f13b67da 100644
--- a/activerecord/test/models/post.rb
+++ b/activerecord/test/models/post.rb
@@ -208,6 +208,22 @@ class PostWithDefaultScope < ActiveRecord::Base
default_scope { order(:title) }
end
+class PostWithPreloadDefaultScope < ActiveRecord::Base
+ self.table_name = 'posts'
+
+ has_many :readers, foreign_key: 'post_id'
+
+ default_scope { preload(:readers) }
+end
+
+class PostWithIncludesDefaultScope < ActiveRecord::Base
+ self.table_name = 'posts'
+
+ has_many :readers, foreign_key: 'post_id'
+
+ default_scope { includes(:readers) }
+end
+
class SpecialPostWithDefaultScope < ActiveRecord::Base
self.table_name = 'posts'
default_scope { where(:id => [1, 5,6]) }
diff --git a/activerecord/test/models/tree.rb b/activerecord/test/models/tree.rb
new file mode 100644
index 0000000000..dc29cccc9c
--- /dev/null
+++ b/activerecord/test/models/tree.rb
@@ -0,0 +1,3 @@
+class Tree < ActiveRecord::Base
+ has_many :nodes, dependent: :destroy
+end
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index dffccc9326..6872b49ad9 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -867,6 +867,17 @@ ActiveRecord::Schema.define do
t.string 'from'
end
+ create_table :nodes, force: true do |t|
+ t.integer :tree_id
+ t.integer :parent_id
+ t.string :name
+ t.datetime :updated_at
+ end
+ create_table :trees, force: true do |t|
+ t.string :name
+ t.datetime :updated_at
+ end
+
create_table :hotels, force: true do |t|
end
create_table :departments, force: true do |t|
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index 6ebbdbc3db..334eebc268 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,3 +1,12 @@
+* Fix not calling `#default` on `HashWithIndifferentAccess#to_hash` when only
+ `default_proc` is set, which could raise.
+
+ *Simon Eskildsen*
+
+* Fix setting `default_proc` on `HashWithIndifferentAccess#dup`
+
+ *Simon Eskildsen*
+
* Fix a range of values for parameters of the Time#change
*Nikolay Kondratyev*
diff --git a/activesupport/lib/active_support/concurrency/share_lock.rb b/activesupport/lib/active_support/concurrency/share_lock.rb
new file mode 100644
index 0000000000..f1c6230084
--- /dev/null
+++ b/activesupport/lib/active_support/concurrency/share_lock.rb
@@ -0,0 +1,138 @@
+require 'thread'
+require 'monitor'
+
+module ActiveSupport
+ module Concurrency
+ # A share/exclusive lock, otherwise known as a read/write lock.
+ #
+ # https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock
+ #--
+ # Note that a pending Exclusive lock attempt does not block incoming
+ # Share requests (i.e., we are "read-preferring"). That seems
+ # consistent with the behavior of +loose_upgrades+, but may be the
+ # wrong choice otherwise: it nominally reduces the possibility of
+ # deadlock by risking starvation instead.
+ class ShareLock
+ include MonitorMixin
+
+ # We track Thread objects, instead of just using counters, because
+ # we need exclusive locks to be reentrant, and we need to be able
+ # to upgrade share locks to exclusive.
+
+
+ # If +loose_upgrades+ is false (the default), then a thread that
+ # is waiting on an Exclusive lock will continue to hold any Share
+ # lock that it has already established. This is safer, but can
+ # lead to deadlock.
+ #
+ # If +loose_upgrades+ is true, a thread waiting on an Exclusive
+ # lock will temporarily relinquish its Share lock. Being less
+ # strict, this behavior prevents some classes of deadlocks. For
+ # many resources, loose upgrades are sufficient: if a thread is
+ # awaiting a lock, it is not running any other code.
+ attr_reader :loose_upgrades
+
+ def initialize(loose_upgrades = false)
+ @loose_upgrades = loose_upgrades
+
+ super()
+
+ @cv = new_cond
+
+ @sharing = Hash.new(0)
+ @exclusive_thread = nil
+ @exclusive_depth = 0
+ end
+
+ # Returns false if +no_wait+ is specified and the lock is not
+ # immediately available. Otherwise, returns true after the lock
+ # has been acquired.
+ def start_exclusive(no_wait=false)
+ synchronize do
+ unless @exclusive_thread == Thread.current
+ return false if no_wait && busy?
+
+ loose_shares = nil
+ if @loose_upgrades
+ loose_shares = @sharing.delete(Thread.current)
+ end
+
+ @cv.wait_while { busy? } if busy?
+
+ @exclusive_thread = Thread.current
+ @sharing[Thread.current] = loose_shares if loose_shares
+ end
+ @exclusive_depth += 1
+
+ true
+ end
+ end
+
+ # Relinquish the exclusive lock. Must only be called by the thread
+ # that called start_exclusive (and currently holds the lock).
+ def stop_exclusive
+ synchronize do
+ raise "invalid unlock" if @exclusive_thread != Thread.current
+
+ @exclusive_depth -= 1
+ if @exclusive_depth == 0
+ @exclusive_thread = nil
+ @cv.broadcast
+ end
+ end
+ end
+
+ def start_sharing
+ synchronize do
+ if @exclusive_thread && @exclusive_thread != Thread.current
+ @cv.wait_while { @exclusive_thread }
+ end
+ @sharing[Thread.current] += 1
+ end
+ end
+
+ def stop_sharing
+ synchronize do
+ if @sharing[Thread.current] > 1
+ @sharing[Thread.current] -= 1
+ else
+ @sharing.delete Thread.current
+ @cv.broadcast
+ end
+ end
+ end
+
+ # Execute the supplied block while holding the Exclusive lock. If
+ # +no_wait+ is set and the lock is not immediately available,
+ # returns +nil+ without yielding. Otherwise, returns the result of
+ # the block.
+ def exclusive(no_wait=false)
+ if start_exclusive(no_wait)
+ begin
+ yield
+ ensure
+ stop_exclusive
+ end
+ end
+ end
+
+ # Execute the supplied block while holding the Share lock.
+ def sharing
+ start_sharing
+ begin
+ yield
+ ensure
+ stop_sharing
+ end
+ end
+
+ private
+
+ # Must be called within synchronize
+ def busy?
+ (@exclusive_thread && @exclusive_thread != Thread.current) ||
+ @sharing.size > (@sharing[Thread.current] > 0 ? 1 : 0)
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/module/concerning.rb b/activesupport/lib/active_support/core_ext/module/concerning.rb
index e26b594fc4..65b88b9bbd 100644
--- a/activesupport/lib/active_support/core_ext/module/concerning.rb
+++ b/activesupport/lib/active_support/core_ext/module/concerning.rb
@@ -99,7 +99,7 @@ class Module
# end
#
# Todo.ancestors
- # # => Todo, Todo::EventTracking, Object
+ # # => [Todo, Todo::EventTracking, Object]
#
# This small step has some wonderful ripple effects. We can
# * grok the behavior of our class in one glance,
diff --git a/activesupport/lib/active_support/core_ext/object/duplicable.rb b/activesupport/lib/active_support/core_ext/object/duplicable.rb
index 620f7b6561..6fc0cb53f0 100644
--- a/activesupport/lib/active_support/core_ext/object/duplicable.rb
+++ b/activesupport/lib/active_support/core_ext/object/duplicable.rb
@@ -19,7 +19,7 @@
class Object
# Can you safely dup this object?
#
- # False for +nil+, +false+, +true+, symbol, number objects;
+ # False for +nil+, +false+, +true+, symbol, number, method objects;
# true otherwise.
def duplicable?
true
@@ -78,6 +78,10 @@ end
require 'bigdecimal'
class BigDecimal
+ # BigDecimals are duplicable:
+ #
+ # BigDecimal.new("1.2").duplicable? # => true
+ # BigDecimal.new("1.2").dup # => #<BigDecimal:7f9d698eee10,'0.12E1',18(18)>
def duplicable?
true
end
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index 664cc15a29..770c845435 100644
--- a/activesupport/lib/active_support/dependencies.rb
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -12,12 +12,33 @@ require 'active_support/core_ext/kernel/reporting'
require 'active_support/core_ext/load_error'
require 'active_support/core_ext/name_error'
require 'active_support/core_ext/string/starts_ends_with'
+require "active_support/dependencies/interlock"
require 'active_support/inflector'
module ActiveSupport #:nodoc:
module Dependencies #:nodoc:
extend self
+ mattr_accessor :interlock
+ self.interlock = Interlock.new
+
+ # :doc:
+
+ # Execute the supplied block without interference from any
+ # concurrent loads
+ def self.run_interlock
+ Dependencies.interlock.running { yield }
+ end
+
+ # Execute the supplied block while holding an exclusive lock,
+ # preventing any other thread from being inside a #run_interlock
+ # block at the same time
+ def self.load_interlock
+ Dependencies.interlock.loading { yield }
+ end
+
+ # :nodoc:
+
# Should we turn on Ruby warnings on the first load of dependent files?
mattr_accessor :warnings_on_first_load
self.warnings_on_first_load = false
@@ -234,10 +255,12 @@ module ActiveSupport #:nodoc:
end
def load_dependency(file)
- if Dependencies.load? && ActiveSupport::Dependencies.constant_watch_stack.watching?
- Dependencies.new_constants_in(Object) { yield }
- else
- yield
+ Dependencies.load_interlock do
+ if Dependencies.load? && ActiveSupport::Dependencies.constant_watch_stack.watching?
+ Dependencies.new_constants_in(Object) { yield }
+ else
+ yield
+ end
end
rescue Exception => exception # errors from loading file
exception.blame_file! file if exception.respond_to? :blame_file!
@@ -325,9 +348,11 @@ module ActiveSupport #:nodoc:
def clear
log_call
- loaded.clear
- loading.clear
- remove_unloadable_constants!
+ Dependencies.load_interlock do
+ loaded.clear
+ loading.clear
+ remove_unloadable_constants!
+ end
end
def require_or_load(file_name, const_path = nil)
@@ -336,39 +361,44 @@ module ActiveSupport #:nodoc:
expanded = File.expand_path(file_name)
return if loaded.include?(expanded)
- # Record that we've seen this file *before* loading it to avoid an
- # infinite loop with mutual dependencies.
- loaded << expanded
- loading << expanded
+ Dependencies.load_interlock do
+ # Maybe it got loaded while we were waiting for our lock:
+ return if loaded.include?(expanded)
- begin
- if load?
- log "loading #{file_name}"
-
- # Enable warnings if this file has not been loaded before and
- # warnings_on_first_load is set.
- load_args = ["#{file_name}.rb"]
- load_args << const_path unless const_path.nil?
+ # Record that we've seen this file *before* loading it to avoid an
+ # infinite loop with mutual dependencies.
+ loaded << expanded
+ loading << expanded
- if !warnings_on_first_load or history.include?(expanded)
- result = load_file(*load_args)
+ begin
+ if load?
+ log "loading #{file_name}"
+
+ # Enable warnings if this file has not been loaded before and
+ # warnings_on_first_load is set.
+ load_args = ["#{file_name}.rb"]
+ load_args << const_path unless const_path.nil?
+
+ if !warnings_on_first_load or history.include?(expanded)
+ result = load_file(*load_args)
+ else
+ enable_warnings { result = load_file(*load_args) }
+ end
else
- enable_warnings { result = load_file(*load_args) }
+ log "requiring #{file_name}"
+ result = require file_name
end
- else
- log "requiring #{file_name}"
- result = require file_name
+ rescue Exception
+ loaded.delete expanded
+ raise
+ ensure
+ loading.pop
end
- rescue Exception
- loaded.delete expanded
- raise
- ensure
- loading.pop
- end
- # Record history *after* loading so first load gets warnings.
- history << expanded
- result
+ # Record history *after* loading so first load gets warnings.
+ history << expanded
+ result
+ end
end
# Is the provided constant path defined?
diff --git a/activesupport/lib/active_support/dependencies/interlock.rb b/activesupport/lib/active_support/dependencies/interlock.rb
new file mode 100644
index 0000000000..148212c951
--- /dev/null
+++ b/activesupport/lib/active_support/dependencies/interlock.rb
@@ -0,0 +1,41 @@
+require 'active_support/concurrency/share_lock'
+
+module ActiveSupport #:nodoc:
+ module Dependencies #:nodoc:
+ class Interlock
+ def initialize # :nodoc:
+ @lock = ActiveSupport::Concurrency::ShareLock.new(true)
+ end
+
+ def loading
+ @lock.exclusive do
+ yield
+ end
+ end
+
+ # Attempt to obtain a "loading" (exclusive) lock. If possible,
+ # execute the supplied block while holding the lock. If there is
+ # concurrent activity, return immediately (without executing the
+ # block) instead of waiting.
+ def attempt_loading
+ @lock.exclusive(true) do
+ yield
+ end
+ end
+
+ def start_running
+ @lock.start_sharing
+ end
+
+ def done_running
+ @lock.stop_sharing
+ end
+
+ def running
+ @lock.sharing do
+ yield
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb
index 4f71f13971..63690a1342 100644
--- a/activesupport/lib/active_support/hash_with_indifferent_access.rb
+++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb
@@ -188,7 +188,7 @@ module ActiveSupport
# dup[:a][:c] # => "c"
def dup
self.class.new(self).tap do |new_hash|
- new_hash.default = default
+ set_defaults(new_hash)
end
end
@@ -247,7 +247,9 @@ module ActiveSupport
# Convert to a regular hash with string keys.
def to_hash
- _new_hash = Hash.new(default)
+ _new_hash = Hash.new
+ set_defaults(_new_hash)
+
each do |key, value|
_new_hash[key] = convert_value(value, for: :to_hash)
end
@@ -275,6 +277,14 @@ module ActiveSupport
value
end
end
+
+ def set_defaults(target)
+ if default_proc
+ target.default_proc = default_proc.dup
+ else
+ target.default = default
+ end
+ end
end
end
diff --git a/activesupport/lib/active_support/ordered_options.rb b/activesupport/lib/active_support/ordered_options.rb
index bc0326473d..45864990ce 100644
--- a/activesupport/lib/active_support/ordered_options.rb
+++ b/activesupport/lib/active_support/ordered_options.rb
@@ -6,6 +6,7 @@ module ActiveSupport
# h[:girl] = 'Mary'
# h[:boy] # => 'John'
# h[:girl] # => 'Mary'
+ # h[:dog] # => nil
#
# Using +OrderedOptions+, the above code could be reduced to:
#
@@ -14,6 +15,13 @@ module ActiveSupport
# h.girl = 'Mary'
# h.boy # => 'John'
# h.girl # => 'Mary'
+ # h.dog # => nil
+ #
+ # To raise an exception when the value is blank, append a
+ # bang to the key name, like:
+ #
+ # h.dog! # => raises KeyError
+ #
class OrderedOptions < Hash
alias_method :_get, :[] # preserve the original #[] method
protected :_get # make it protected
diff --git a/activesupport/lib/active_support/testing/method_call_assertions.rb b/activesupport/lib/active_support/testing/method_call_assertions.rb
new file mode 100644
index 0000000000..e3cbe40308
--- /dev/null
+++ b/activesupport/lib/active_support/testing/method_call_assertions.rb
@@ -0,0 +1,35 @@
+module ActiveSupport
+ module Testing
+ module MethodCallAssertions # :nodoc:
+ private
+ def assert_called(object, method_name, message = nil, times: 1)
+ times_called = 0
+
+ object.stub(method_name, -> { times_called += 1 }) { yield }
+
+ error = "Expected #{method_name} to be called #{times} times, " \
+ "but was called #{times_called} times"
+ error = "#{message}.\n#{error}" if message
+ assert_equal times, times_called, error
+ end
+
+ def assert_called_with(object, method_name, args = [], returns: nil)
+ mock = Minitest::Mock.new
+
+ if args.all? { |arg| arg.is_a?(Array) }
+ args.each { |arg| mock.expect(:call, returns, arg) }
+ else
+ mock.expect(:call, returns, args)
+ end
+
+ object.stub(method_name, mock) { yield }
+
+ mock.verify
+ end
+
+ def assert_not_called(object, method_name, message = nil, &block)
+ assert_called(object, method_name, message, times: 0, &block)
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/activesupport/test/abstract_unit.rb b/activesupport/test/abstract_unit.rb
index 9b88a2dcc1..65a8edbabb 100644
--- a/activesupport/test/abstract_unit.rb
+++ b/activesupport/test/abstract_unit.rb
@@ -15,6 +15,7 @@ silence_warnings do
end
require 'active_support/testing/autorun'
+require 'active_support/testing/method_call_assertions'
ENV['NO_RELOAD'] = '1'
require 'active_support'
@@ -38,4 +39,7 @@ def jruby_skip(message = '')
end
require 'minitest/mock'
-require 'mocha/setup' # FIXME: stop using mocha
+
+class ActiveSupport::TestCase
+ include ActiveSupport::Testing::MethodCallAssertions
+end
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index 8e22d4ed2f..74ceff44f9 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -133,37 +133,42 @@ class CacheStoreSettingTest < ActiveSupport::TestCase
end
def test_mem_cache_fragment_cache_store
- Dalli::Client.expects(:new).with(%w[localhost], {})
- store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost"
- assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ assert_called_with(Dalli::Client, :new, [%w[localhost], {}]) do
+ store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost"
+ assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ end
end
def test_mem_cache_fragment_cache_store_with_given_mem_cache
mem_cache = Dalli::Client.new
- Dalli::Client.expects(:new).never
- store = ActiveSupport::Cache.lookup_store :mem_cache_store, mem_cache
- assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ assert_not_called(Dalli::Client, :new) do
+ store = ActiveSupport::Cache.lookup_store :mem_cache_store, mem_cache
+ assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ end
end
def test_mem_cache_fragment_cache_store_with_not_dalli_client
- Dalli::Client.expects(:new).never
- memcache = Object.new
- assert_raises(ArgumentError) do
- ActiveSupport::Cache.lookup_store :mem_cache_store, memcache
+ assert_not_called(Dalli::Client, :new) do
+ memcache = Object.new
+ assert_raises(ArgumentError) do
+ ActiveSupport::Cache.lookup_store :mem_cache_store, memcache
+ end
end
end
def test_mem_cache_fragment_cache_store_with_multiple_servers
- Dalli::Client.expects(:new).with(%w[localhost 192.168.1.1], {})
- store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", '192.168.1.1'
- assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ assert_called_with(Dalli::Client, :new, [%w[localhost 192.168.1.1], {}]) do
+ store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", '192.168.1.1'
+ assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ end
end
def test_mem_cache_fragment_cache_store_with_options
- Dalli::Client.expects(:new).with(%w[localhost 192.168.1.1], { :timeout => 10 })
- store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", '192.168.1.1', :namespace => 'foo', :timeout => 10
- assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
- assert_equal 'foo', store.options[:namespace]
+ assert_called_with(Dalli::Client, :new, [%w[localhost 192.168.1.1], { :timeout => 10 }]) do
+ store = ActiveSupport::Cache.lookup_store :mem_cache_store, "localhost", '192.168.1.1', :namespace => 'foo', :timeout => 10
+ assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
+ assert_equal 'foo', store.options[:namespace]
+ end
end
def test_object_assigned_fragment_cache_store
@@ -224,13 +229,15 @@ module CacheStoreBehavior
def test_fetch_without_cache_miss
@cache.write('foo', 'bar')
- @cache.expects(:write).never
- assert_equal 'bar', @cache.fetch('foo') { 'baz' }
+ assert_not_called(@cache, :write) do
+ assert_equal 'bar', @cache.fetch('foo') { 'baz' }
+ end
end
def test_fetch_with_cache_miss
- @cache.expects(:write).with('foo', 'baz', @cache.options)
- assert_equal 'baz', @cache.fetch('foo') { 'baz' }
+ assert_called_with(@cache, :write, ['foo', 'baz', @cache.options]) do
+ assert_equal 'baz', @cache.fetch('foo') { 'baz' }
+ end
end
def test_fetch_with_cache_miss_passes_key_to_block
@@ -245,15 +252,18 @@ module CacheStoreBehavior
def test_fetch_with_forced_cache_miss
@cache.write('foo', 'bar')
- @cache.expects(:read).never
- @cache.expects(:write).with('foo', 'bar', @cache.options.merge(:force => true))
- @cache.fetch('foo', :force => true) { 'bar' }
+ assert_not_called(@cache, :read) do
+ assert_called_with(@cache, :write, ['foo', 'bar', @cache.options.merge(:force => true)]) do
+ @cache.fetch('foo', :force => true) { 'bar' }
+ end
+ end
end
def test_fetch_with_cached_nil
@cache.write('foo', nil)
- @cache.expects(:write).never
- assert_nil @cache.fetch('foo') { 'baz' }
+ assert_not_called(@cache, :write) do
+ assert_nil @cache.fetch('foo') { 'baz' }
+ end
end
def test_should_read_and_write_hash
@@ -304,8 +314,9 @@ module CacheStoreBehavior
end
def test_multi_with_objects
- foo = stub(:title => 'FOO!', :cache_key => 'foo')
- bar = stub(:cache_key => 'bar')
+ cache_struct = Struct.new(:cache_key, :title)
+ foo = cache_struct.new('foo', 'FOO!')
+ bar = cache_struct.new('bar')
@cache.write('bar', 'BAM!')
@@ -774,9 +785,10 @@ class FileStoreTest < ActiveSupport::TestCase
end
def test_log_exception_when_cache_read_fails
- File.expects(:exist?).raises(StandardError, "failed")
- @cache.send(:read_entry, "winston", {})
- assert @buffer.string.present?
+ File.stub(:exist?, -> { raise StandardError.new("failed") }) do
+ @cache.send(:read_entry, "winston", {})
+ assert @buffer.string.present?
+ end
end
def test_cleanup_removes_all_expired_entries
@@ -1026,10 +1038,6 @@ class NullStoreTest < ActiveSupport::TestCase
end
assert_nil @cache.read("name")
end
-
- def test_setting_nil_cache_store
- assert ActiveSupport::Cache.lookup_store.class.name, ActiveSupport::Cache::NullStore.name
- end
end
class CacheStoreLoggerTest < ActiveSupport::TestCase
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index e10bee5e00..663f782611 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -524,6 +524,10 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_indifferent_reverse_merging
+ hash = HashWithIndifferentAccess.new key: :old_value
+ hash.reverse_merge! key: :new_value
+ assert_equal :old_value, hash[:key]
+
hash = HashWithIndifferentAccess.new('some' => 'value', 'other' => 'value')
hash.reverse_merge!(:some => 'noclobber', :another => 'clobber')
assert_equal 'value', hash[:some]
@@ -961,10 +965,11 @@ class HashExtTest < ActiveSupport::TestCase
assert_raise(RuntimeError) { original.except!(:a) }
end
- def test_except_with_mocha_expectation_on_original
+ def test_except_does_not_delete_values_in_original
original = { :a => 'x', :b => 'y' }
- original.expects(:delete).never
- original.except(:a)
+ assert_not_called(original, :delete) do
+ original.except(:a)
+ end
end
def test_compact
@@ -998,6 +1003,37 @@ class HashExtTest < ActiveSupport::TestCase
assert hash.key?('a')
assert_equal 1, hash[:a]
end
+
+ def test_dup_with_default_proc
+ hash = HashWithIndifferentAccess.new
+ hash.default_proc = proc { |h, v| raise "walrus" }
+ assert_nothing_raised { hash.dup }
+ end
+
+ def test_dup_with_default_proc_sets_proc
+ hash = HashWithIndifferentAccess.new
+ hash.default_proc = proc { |h, k| k + 1 }
+ new_hash = hash.dup
+
+ assert_equal 3, new_hash[2]
+
+ new_hash.default = 2
+ assert_equal 2, new_hash[:non_existant]
+ end
+
+ def test_to_hash_with_raising_default_proc
+ hash = HashWithIndifferentAccess.new
+ hash.default_proc = proc { |h, k| raise "walrus" }
+
+ assert_nothing_raised { hash.to_hash }
+ end
+
+ def test_new_from_hash_copying_default_should_not_raise_when_default_proc_does
+ hash = Hash.new
+ hash.default_proc = proc { |h, k| raise "walrus" }
+
+ assert_nothing_raised { HashWithIndifferentAccess.new_from_hash_copying_default(hash) }
+ end
end
class IWriteMyOwnXML
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
index 5b48bf328c..477a42114b 100644
--- a/activesupport/test/core_ext/time_with_zone_test.rb
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -2,6 +2,7 @@ require 'abstract_unit'
require 'active_support/time'
require 'time_zone_test_helpers'
require 'active_support/core_ext/string/strip'
+require 'yaml'
class TimeWithZoneTest < ActiveSupport::TestCase
include TimeZoneTestHelpers
@@ -482,22 +483,24 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_method_missing_with_non_time_return_value
- @twz.time.expects(:foo).returns('bar')
+ time = @twz.time
+ def time.foo; 'bar'; end
assert_equal 'bar', @twz.foo
end
def test_date_part_value_methods
twz = ActiveSupport::TimeWithZone.new(Time.utc(1999,12,31,19,18,17,500), @time_zone)
- twz.expects(:method_missing).never
- assert_equal 1999, twz.year
- assert_equal 12, twz.month
- assert_equal 31, twz.day
- assert_equal 14, twz.hour
- assert_equal 18, twz.min
- assert_equal 17, twz.sec
- assert_equal 500, twz.usec
- assert_equal 5, twz.wday
- assert_equal 365, twz.yday
+ assert_not_called(twz, :method_missing) do
+ assert_equal 1999, twz.year
+ assert_equal 12, twz.month
+ assert_equal 31, twz.day
+ assert_equal 14, twz.hour
+ assert_equal 18, twz.min
+ assert_equal 17, twz.sec
+ assert_equal 500, twz.usec
+ assert_equal 5, twz.wday
+ assert_equal 365, twz.yday
+ end
end
def test_usec_returns_0_when_datetime_is_wrapped
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
index 6dce7560dd..757e600646 100644
--- a/activesupport/test/dependencies_test.rb
+++ b/activesupport/test/dependencies_test.rb
@@ -721,12 +721,13 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_unloadable_constants_should_receive_callback
- Object.const_set :C, Class.new
+ Object.const_set :C, Class.new { def self.before_remove_const; end }
C.unloadable
- C.expects(:before_remove_const).once
- assert C.respond_to?(:before_remove_const)
- ActiveSupport::Dependencies.clear
- assert !defined?(C)
+ assert_called(C, :before_remove_const, times: 1) do
+ assert C.respond_to?(:before_remove_const)
+ ActiveSupport::Dependencies.clear
+ assert !defined?(C)
+ end
ensure
remove_constants(:C)
end
diff --git a/activesupport/test/deprecation_test.rb b/activesupport/test/deprecation_test.rb
index 20bd8ee5dd..7e8844b301 100644
--- a/activesupport/test/deprecation_test.rb
+++ b/activesupport/test/deprecation_test.rb
@@ -256,17 +256,17 @@ class DeprecationTest < ActiveSupport::TestCase
end
def test_deprecate_with_custom_deprecator
- custom_deprecator = mock('Deprecator') do
- expects(:deprecation_warning)
- end
+ custom_deprecator = Struct.new(:deprecation_warning).new
- klass = Class.new do
- def method
+ assert_called_with(custom_deprecator, :deprecation_warning, [:method, nil]) do
+ klass = Class.new do
+ def method
+ end
+ deprecate :method, deprecator: custom_deprecator
end
- deprecate :method, deprecator: custom_deprecator
- end
- klass.new.method
+ klass.new.method
+ end
end
def test_deprecated_constant_with_deprecator_given
diff --git a/activesupport/test/hash_with_indifferent_access_test.rb b/activesupport/test/hash_with_indifferent_access_test.rb
deleted file mode 100644
index 1facd691fa..0000000000
--- a/activesupport/test/hash_with_indifferent_access_test.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-require 'abstract_unit'
-require 'active_support/hash_with_indifferent_access'
-
-class HashWithIndifferentAccessTest < ActiveSupport::TestCase
- def test_reverse_merge
- hash = HashWithIndifferentAccess.new key: :old_value
- hash.reverse_merge! key: :new_value
- assert_equal :old_value, hash[:key]
- end
-
-end
diff --git a/activesupport/test/log_subscriber_test.rb b/activesupport/test/log_subscriber_test.rb
index 2a0e8d20ed..998a6887c5 100644
--- a/activesupport/test/log_subscriber_test.rb
+++ b/activesupport/test/log_subscriber_test.rb
@@ -82,10 +82,11 @@ class SyncLogSubscriberTest < ActiveSupport::TestCase
def test_does_not_send_the_event_if_logger_is_nil
ActiveSupport::LogSubscriber.logger = nil
- @log_subscriber.expects(:some_event).never
- ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber
- instrument "some_event.my_log_subscriber"
- wait
+ assert_not_called(@log_subscriber, :some_event) do
+ ActiveSupport::LogSubscriber.attach_to :my_log_subscriber, @log_subscriber
+ instrument "some_event.my_log_subscriber"
+ wait
+ end
end
def test_does_not_fail_with_non_namespaced_events
diff --git a/activesupport/test/multibyte_unicode_database_test.rb b/activesupport/test/multibyte_unicode_database_test.rb
index 52ae266f01..dd33641ec2 100644
--- a/activesupport/test/multibyte_unicode_database_test.rb
+++ b/activesupport/test/multibyte_unicode_database_test.rb
@@ -11,8 +11,9 @@ class MultibyteUnicodeDatabaseTest < ActiveSupport::TestCase
UnicodeDatabase::ATTRIBUTES.each do |attribute|
define_method "test_lazy_loading_on_attribute_access_of_#{attribute}" do
- @ucd.expects(:load)
- @ucd.send(attribute)
+ assert_called(@ucd, :load) do
+ @ucd.send(attribute)
+ end
end
end
diff --git a/activesupport/test/testing/method_call_assertions_test.rb b/activesupport/test/testing/method_call_assertions_test.rb
new file mode 100644
index 0000000000..a9908aea0d
--- /dev/null
+++ b/activesupport/test/testing/method_call_assertions_test.rb
@@ -0,0 +1,98 @@
+require 'abstract_unit'
+require 'active_support/testing/method_call_assertions'
+
+class MethodCallAssertionsTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::MethodCallAssertions
+
+ class Level
+ def increment; 1; end
+ def decrement; end
+ def <<(arg); end
+ end
+
+ setup do
+ @object = Level.new
+ end
+
+ def test_assert_called_with_defaults_to_expect_once
+ assert_called @object, :increment do
+ @object.increment
+ end
+ end
+
+ def test_assert_called_more_than_once
+ assert_called(@object, :increment, times: 2) do
+ @object.increment
+ @object.increment
+ end
+ end
+
+ def test_assert_called_failure
+ error = assert_raises(Minitest::Assertion) do
+ assert_called(@object, :increment) do
+ # Call nothing...
+ end
+ end
+
+ assert_equal "Expected increment to be called 1 times, but was called 0 times.\nExpected: 1\n Actual: 0", error.message
+ end
+
+ def test_assert_called_with_message
+ error = assert_raises(Minitest::Assertion) do
+ assert_called(@object, :increment, 'dang it') do
+ # Call nothing...
+ end
+ end
+
+ assert_match(/dang it.\nExpected increment/, error.message)
+ end
+
+ def test_assert_called_with
+ assert_called_with(@object, :increment) do
+ @object.increment
+ end
+ end
+
+ def test_assert_called_with_arguments
+ assert_called_with(@object, :<<, [ 2 ]) do
+ @object << 2
+ end
+ end
+
+ def test_assert_called_with_failure
+ assert_raises(MockExpectationError) do
+ assert_called_with(@object, :<<, [ 4567 ]) do
+ @object << 2
+ end
+ end
+ end
+
+ def test_assert_called_with_returns
+ assert_called_with(@object, :increment, returns: 1) do
+ @object.increment
+ end
+ end
+
+ def test_assert_called_with_multiple_expected_arguments
+ assert_called_with(@object, :<<, [ [ 1 ], [ 2 ] ]) do
+ @object << 1
+ @object << 2
+ end
+ end
+
+ def test_assert_not_called
+ assert_not_called(@object, :decrement) do
+ @object.increment
+ end
+ end
+
+ def test_assert_not_called_failure
+ error = assert_raises(Minitest::Assertion) do
+ assert_not_called(@object, :increment) do
+ @object.increment
+ end
+ end
+
+ assert_equal "Expected increment to be called 0 times, but was called 1 times.\nExpected: 0\n Actual: 1", error.message
+ end
+end
diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb
index 34bb0e2995..00d40c4497 100644
--- a/activesupport/test/time_zone_test.rb
+++ b/activesupport/test/time_zone_test.rb
@@ -1,6 +1,7 @@
require 'abstract_unit'
require 'active_support/time'
require 'time_zone_test_helpers'
+require 'yaml'
class TimeZoneTest < ActiveSupport::TestCase
include TimeZoneTestHelpers
diff --git a/activesupport/test/xml_mini_test.rb b/activesupport/test/xml_mini_test.rb
index 0e4e7427d2..55e8181b54 100644
--- a/activesupport/test/xml_mini_test.rb
+++ b/activesupport/test/xml_mini_test.rb
@@ -3,6 +3,7 @@ require 'active_support/xml_mini'
require 'active_support/builder'
require 'active_support/core_ext/hash'
require 'active_support/core_ext/big_decimal'
+require 'yaml'
module XmlMiniTest
class RenameKeyTest < ActiveSupport::TestCase
diff --git a/guides/assets/images/getting_started/rails_welcome.png b/guides/assets/images/getting_started/rails_welcome.png
index 3e07c948a0..4d0cb417b7 100644
--- a/guides/assets/images/getting_started/rails_welcome.png
+++ b/guides/assets/images/getting_started/rails_welcome.png
Binary files differ
diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md
index d506722f75..09fbdc0d32 100644
--- a/guides/source/action_controller_overview.md
+++ b/guides/source/action_controller_overview.md
@@ -738,7 +738,7 @@ You can choose not to yield and build the response yourself, in which case the a
While the most common way to use filters is by creating private methods and using *_action to add them, there are two other ways to do the same thing.
-The first is to use a block directly with the *\_action methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritten to use a block:
+The first is to use a block directly with the *\_action methods. The block receives the controller as an argument. The `require_login` filter from above could be rewritten to use a block:
```ruby
class ApplicationController < ActionController::Base
diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md
index 6f159b2fc4..c31b50fcfc 100644
--- a/guides/source/action_mailer_basics.md
+++ b/guides/source/action_mailer_basics.md
@@ -533,6 +533,24 @@ url helper.
NOTE: non-`GET` links require [jQuery UJS](https://github.com/rails/jquery-ujs)
and won't work in mailer templates. They will result in normal `GET` requests.
+### Adding images in Action Mailer Views
+
+Unlike controllers, the mailer instance doesn't have any context about the
+incoming request so you'll need to provide the `:asset_host` parameter yourself.
+
+As the `:asset_host` usually is consistent across the application you can
+configure it globally in config/application.rb:
+
+```ruby
+config.action_mailer.asset_host = 'http://example.com'
+```
+
+Now you can display an image inside your email.
+
+```ruby
+<%= image_tag 'image.jpg' %>
+```
+
### Sending Multipart Emails
Action Mailer will automatically send multipart emails if you have different
diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md
index 3c1c3c7873..98c6cbd540 100644
--- a/guides/source/action_view_overview.md
+++ b/guides/source/action_view_overview.md
@@ -1059,14 +1059,6 @@ If `@article.author_ids` is [1], this would return:
<input name="article[author_ids][]" type="hidden" value="" />
```
-#### country_options_for_select
-
-Returns a string of option tags for pretty much any country in the world.
-
-#### country_select
-
-Returns select and option tags for the given object and method, using country_options_for_select to generate the list of option tags.
-
#### option_groups_from_collection_for_select
Returns a string of `option` tags, like `options_from_collection_for_select`, but groups them by `optgroup` tags based on the object relationships of the arguments.
@@ -1153,8 +1145,8 @@ If `@article.person_id` is 1, this would become:
<select name="article[person_id]">
<option value=""></option>
<option value="1" selected="selected">David</option>
- <option value="2">Sam</option>
- <option value="3">Tobias</option>
+ <option value="2">Eileen</option>
+ <option value="3">Rafael</option>
</select>
```
diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md
index 22f3c0146a..dd545b56f5 100644
--- a/guides/source/active_job_basics.md
+++ b/guides/source/active_job_basics.md
@@ -330,6 +330,13 @@ class GuestsCleanupJob < ActiveJob::Base
end
```
+### Deserialization
+
+GlobalID allows serializing full Active Record objects passed to `#perform`.
+
+If a passed record is deleted after the job is enqueued but before the `#perform`
+method is called Active Job will raise an `ActiveJob::DeserializationError`
+exception.
Job Testing
--------------
diff --git a/guides/source/active_record_migrations.md b/guides/source/active_record_migrations.md
index ad069a112e..ce605c912e 100644
--- a/guides/source/active_record_migrations.md
+++ b/guides/source/active_record_migrations.md
@@ -423,21 +423,23 @@ change_column :products, :part_number, :text
```
This changes the column `part_number` on products table to be a `:text` field.
+Note that `change_column` command is irreversible.
Besides `change_column`, the `change_column_null` and `change_column_default`
-methods are used specifically to change a not null constraint and default values of a
-column.
+methods are used specifically to change a not null constraint and default
+values of a column.
```ruby
change_column_null :products, :name, false
-change_column_default :products, :approved, false
+change_column_default :products, :approved, from: true, to: false
```
This sets `:name` field on products to a `NOT NULL` column and the default
-value of the `:approved` field to false.
+value of the `:approved` field from true to false.
-TIP: Unlike `change_column` (and `change_column_default`), `change_column_null`
-is reversible.
+Note: You could also write the above `change_column_default` migration as
+`change_column_default :products, :approved, false`, but unlike the previous
+example, this would make your migration irreversible.
### Column Modifiers
@@ -475,7 +477,7 @@ column names can not be derived from the table names, you can use the
`:column` and `:primary_key` options.
Rails will generate a name for every foreign key starting with
-`fk_rails_` followed by 10 character which is deterministically
+`fk_rails_` followed by 10 characters which are deterministically
generated from the `from_table` and `column`.
There is a `:name` option to specify a different name if needed.
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md
index 7932853c11..71ca7a0f66 100644
--- a/guides/source/active_record_validations.md
+++ b/guides/source/active_record_validations.md
@@ -965,8 +965,9 @@ own custom validators.
You can also create methods that verify the state of your models and add
messages to the `errors` collection when they are invalid. You must then
-register these methods by using the `validate` class method, passing in the
-symbols for the validation methods' names.
+register these methods by using the `validate`
+([API](http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validate))
+class method, passing in the symbols for the validation methods' names.
You can pass more than one symbol for each class method and the respective
validations will be run in the same order as they were registered.
diff --git a/guides/source/active_support_instrumentation.md b/guides/source/active_support_instrumentation.md
index 373dbbb9aa..e49abc41f4 100644
--- a/guides/source/active_support_instrumentation.md
+++ b/guides/source/active_support_instrumentation.md
@@ -321,17 +321,6 @@ Action Mailer
}
```
-Active Resource
---------------
-
-### request.active_resource
-
-| Key | Value |
-| -------------- | -------------------- |
-| `:method` | HTTP method |
-| `:request_uri` | Complete URI |
-| `:result` | HTTP response object |
-
Active Support
--------------
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md
index 05dd0d2a04..c0fa3cfd04 100644
--- a/guides/source/association_basics.md
+++ b/guides/source/association_basics.md
@@ -1519,20 +1519,30 @@ conditions exists in the collection. It uses the same syntax and options as
##### `collection.build(attributes = {}, ...)`
-The `collection.build` method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
+The `collection.build` method returns a single or array of new objects of the associated type. The object(s) will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
```ruby
@order = @customer.orders.build(order_date: Time.now,
order_number: "A12345")
+
+@orders = @customer.orders.build([
+ { order_date: Time.now, order_number: "A12346" },
+ { order_date: Time.now, order_number: "A12347" }
+])
```
##### `collection.create(attributes = {})`
-The `collection.create` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
+The `collection.create` method returns a single or array of new objects of the associated type. The object(s) will be instantiated from the passed attributes, the link through its foreign key will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
```ruby
@order = @customer.orders.create(order_date: Time.now,
order_number: "A12345")
+
+@orders = @customer.orders.create([
+ { order_date: Time.now, order_number: "A12346" },
+ { order_date: Time.now, order_number: "A12347" }
+])
```
##### `collection.create!(attributes = {})`
@@ -2344,13 +2354,13 @@ associations, public methods, etc.
Creating a car will save it in the `vehicles` table with "Car" as the `type` field:
```ruby
-Car.create color: 'Red', price: 10000
+Car.create(color: 'Red', price: 10000)
```
will generate the following SQL:
```sql
-INSERT INTO "vehicles" ("type", "color", "price") VALUES ("Car", "Red", 10000)
+INSERT INTO "vehicles" ("type", "color", "price") VALUES ('Car', 'Red', 10000)
```
Querying car records will just search for vehicles that are cars:
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
index bb6c395c96..79a80de3cc 100644
--- a/guides/source/configuring.md
+++ b/guides/source/configuring.md
@@ -181,7 +181,7 @@ The full set of methods that can be used in this block are as follows:
* `assets` allows to create assets on generating a scaffold. Defaults to `true`.
* `force_plural` allows pluralized model names. Defaults to `false`.
* `helper` defines whether or not to generate helpers. Defaults to `true`.
-* `integration_tool` defines which integration tool to use. Defaults to `nil`.
+* `integration_tool` defines which integration tool to use to generate integration tests. Defaults to `:test_unit`.
* `javascripts` turns on the hook for JavaScript files in generators. Used in Rails for when the `scaffold` generator is run. Defaults to `true`.
* `javascript_engine` configures the engine to be used (for eg. coffee) when generating assets. Defaults to `:js`.
* `orm` defines which orm to use. Defaults to `false` and will use Active Record by default.
diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md
index 3279c99c42..2e86eee587 100644
--- a/guides/source/contributing_to_ruby_on_rails.md
+++ b/guides/source/contributing_to_ruby_on_rails.md
@@ -28,7 +28,7 @@ NOTE: Bugs in the most recent released version of Ruby on Rails are likely to ge
If you've found a problem in Ruby on Rails which is not a security risk, do a search on GitHub under [Issues](https://github.com/rails/rails/issues) in case it has already been reported. If you are unable to find any open GitHub issues addressing the problem you found, your next step will be to [open a new one](https://github.com/rails/rails/issues/new). (See the next section for reporting security issues.)
-Your issue report should contain a title and a clear description of the issue at the bare minimum. You should include as much relevant information as possible and should at least post a code sample that demonstrates the issue. It would be even better if you could include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix.
+Your issue report should contain a title and a clear description of the issue at the bare minimum. You should include as much relevant information as possible and should at least post a code sample that demonstrates the issue. It would be even better if you could include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to reproduce the bug and figure out a fix.
Then, don't get your hopes up! Unless you have a "Code Red, Mission Critical, the World is Coming to an End" kind of bug, you're creating this issue report in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the issue report will automatically see any activity or that others will jump to fix it. Creating an issue like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with an "I'm having this problem too" comment.
@@ -61,7 +61,7 @@ can expect it to be marked "invalid" as soon as it's reviewed.
Sometimes, the line between 'bug' and 'feature' is a hard one to draw.
Generally, a feature is anything that adds new behavior, while a bug is
-anything that fixes already existing behavior that is misbehaving. Sometimes,
+anything that causes incorrect behavior. Sometimes,
the core team will have to make a judgement call. That said, the distinction
generally just affects which release your patch will get in to; we love feature
submissions! They just won't get backported to maintenance branches.
@@ -295,7 +295,7 @@ You can run a single test through ruby. For instance:
```bash
$ cd actionmailer
-$ ruby -w -Itest test/mail_layout_test.rb -n test_explicit_class_layout
+$ bundle exec ruby -w -Itest test/mail_layout_test.rb -n test_explicit_class_layout
```
The `-n` option allows you to run a single method instead of the whole
diff --git a/guides/source/generators.md b/guides/source/generators.md
index 14f451cbc9..32bbdc554a 100644
--- a/guides/source/generators.md
+++ b/guides/source/generators.md
@@ -503,6 +503,14 @@ Adds a specified source to `Gemfile`:
add_source "http://gems.github.com"
```
+This method also takes a block:
+
+```ruby
+add_source "http://gems.github.com" do
+ gem "rspec-rails"
+end
+```
+
### `inject_into_file`
Injects a block of code into a defined position in your file.
diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md
index 193246cbca..400383cfb5 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -23,7 +23,8 @@ application from scratch. It does not assume that you have any prior experience
with Rails. However, to get the most out of it, you need to have some
prerequisites installed:
-* The [Ruby](https://www.ruby-lang.org/en/downloads) language version 2.2.2 or newer.
+* The [Ruby](https://www.ruby-lang.org/en/downloads) language version 2.2.2 or newer.
+* Right version of [Development Kit](http://rubyinstaller.org/downloads/), if you are using Windows
* The [RubyGems](https://rubygems.org) packaging system, which is installed with Ruby
versions 1.9 and later. To learn more about RubyGems, please read the [RubyGems Guides](http://guides.rubygems.org).
* A working installation of the [SQLite3 Database](https://www.sqlite.org).
@@ -298,6 +299,7 @@ Rails.application.routes.draw do
# The priority is based upon order of creation:
# first created -> highest priority.
+ # See how all your routes lay out with "rake routes".
#
# You can have the root of your site routed with "root"
# root 'welcome#index'
@@ -1545,8 +1547,6 @@ class CreateComments < ActiveRecord::Migration
create_table :comments do |t|
t.string :commenter
t.text :body
-
- # this line adds an integer column called `article_id`.
t.references :article, index: true, foreign_key: true
t.timestamps null: false
@@ -1555,9 +1555,9 @@ class CreateComments < ActiveRecord::Migration
end
```
-The `t.references` line sets up a foreign key column for the association between
-the two models. An index for this association is also created on this column.
-Go ahead and run the migration:
+The `t.references` line creates an integer column called `article_id`, an index
+for it, and a foreign key constraint that points to the `id` column of the `articles`
+table. Go ahead and run the migration:
```bash
$ bin/rake db:migrate
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index 31682464ee..272a0e3623 100644
--- a/guides/source/i18n.md
+++ b/guides/source/i18n.md
@@ -210,7 +210,7 @@ This approach has almost the same set of advantages as setting the locale from t
Getting the locale from `params` and setting it accordingly is not hard; including it in every URL and thus **passing it through the requests** is. To include an explicit option in every URL, e.g. `link_to(books_url(locale: I18n.locale))`, would be tedious and probably impossible, of course.
-Rails contains infrastructure for "centralizing dynamic decisions about the URLs" in its [`ApplicationController#default_url_options`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Base.html#method-i-default_url_options), which is useful precisely in this scenario: it enables us to set "defaults" for [`url_for`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for) and helper methods dependent on it (by implementing/overriding this method).
+Rails contains infrastructure for "centralizing dynamic decisions about the URLs" in its [`ApplicationController#default_url_options`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Base.html#method-i-default_url_options), which is useful precisely in this scenario: it enables us to set "defaults" for [`url_for`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for) and helper methods dependent on it (by implementing/overriding `default_url_options`).
We can include something like this in our `ApplicationController` then:
diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md
index 99ab47d1db..1e2fe94010 100644
--- a/guides/source/rails_on_rack.md
+++ b/guides/source/rails_on_rack.md
@@ -58,22 +58,6 @@ class Server < ::Rack::Server
end
```
-Here's how it loads the middlewares:
-
-```ruby
-def middleware
- middlewares = []
- middlewares << [::Rack::ContentLength]
- Hash.new(middlewares)
-end
-```
-
-The following table explains the usage of the loaded middlewares:
-
-| Middleware | Purpose |
-| ----------------------- | --------------------------------------------------------------------------------- |
-| `Rack::ContentLength` | Counts the number of bytes in the response and set the HTTP Content-Length header |
-
### `rackup`
To use `rackup` instead of Rails' `rails server`, you can put the following inside `config.ru` of your Rails application's root directory:
@@ -81,8 +65,6 @@ To use `rackup` instead of Rails' `rails server`, you can put the following insi
```ruby
# Rails.root/config.ru
require ::File.expand_path('../config/environment', __FILE__)
-
-use Rack::ContentLength
run Rails.application
```
diff --git a/guides/source/security.md b/guides/source/security.md
index 93580d4d4e..485b108d12 100644
--- a/guides/source/security.md
+++ b/guides/source/security.md
@@ -1026,6 +1026,29 @@ Environmental Security
It is beyond the scope of this guide to inform you on how to secure your application code and environments. However, please secure your database configuration, e.g. `config/database.yml`, and your server-side secret, e.g. stored in `config/secrets.yml`. You may want to further restrict access, using environment-specific versions of these files and any others that may contain sensitive information.
+### Custom secrets
+
+Rails generates a `config/secrets.yml`. By default, this file contains the
+application's `secret_key_base`, but it could also be used to store other
+secrets such as access keys for external APIs.
+
+The secrets added to this file are accessible via `Rails.application.secrets`.
+For example, with the following `config/secrets.yml`:
+
+ development:
+ secret_key_base: 3b7cd727ee24e8444053437c36cc66c3
+ some_api_key: SOMEKEY
+
+`Rails.application.secrets.some_api_key` returns `SOMEKEY` in the development
+environment.
+
+If you want an exception to be raised when some key is blank, use the bang
+version:
+
+```ruby
+Rails.application.secrets.some_api_key! # => raises KeyError
+```
+
Additional Resources
--------------------
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index 7367f0a813..573b1f8f69 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,3 +1,11 @@
+* Fix `NoMethodError` when generating a scaffold inside a full engine.
+
+ *Yuji Yaginuma*
+
+* Adding support for passing a block to the `add_source` action of a custom generator
+
+ *Mike Dalton*, *Hirofumi Wakasugi*
+
* `assert_file` understands paths with special characters
(eg. `v0.1.4~alpha+nightly`).
diff --git a/railties/lib/rails/application/default_middleware_stack.rb b/railties/lib/rails/application/default_middleware_stack.rb
index 6f9ccec137..88eade5c5a 100644
--- a/railties/lib/rails/application/default_middleware_stack.rb
+++ b/railties/lib/rails/application/default_middleware_stack.rb
@@ -26,7 +26,27 @@ module Rails
middleware.use ::Rack::Cache, rack_cache
end
- middleware.use ::Rack::Lock unless allow_concurrency?
+ if config.allow_concurrency == false
+ # User has explicitly opted out of concurrent request
+ # handling: presumably their code is not threadsafe
+
+ middleware.use ::Rack::Lock
+
+ elsif config.allow_concurrency == :unsafe
+ # Do nothing, even if we know this is dangerous. This is the
+ # historical behaviour for true.
+
+ else
+ # Default concurrency setting: enabled, but safe
+
+ unless config.cache_classes && config.eager_load
+ # Without cache_classes + eager_load, the load interlock
+ # is required for proper operation
+
+ middleware.use ::ActionDispatch::LoadInterlock
+ end
+ end
+
middleware.use ::Rack::Runtime
middleware.use ::Rack::MethodOverride unless config.api_only
middleware.use ::ActionDispatch::RequestId
@@ -65,14 +85,6 @@ module Rails
config.reload_classes_only_on_change != true || app.reloaders.map(&:updated?).any?
end
- def allow_concurrency?
- if config.allow_concurrency.nil?
- config.cache_classes && config.eager_load
- else
- config.allow_concurrency
- end
- end
-
def load_rack_cache
rack_cache = config.action_dispatch.rack_cache
return unless rack_cache
diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb
index 0599e988d9..f8f92792a7 100644
--- a/railties/lib/rails/application/finisher.rb
+++ b/railties/lib/rails/application/finisher.rb
@@ -86,8 +86,10 @@ module Rails
# added in the hook are taken into account.
initializer :set_clear_dependencies_hook, group: :all do
callback = lambda do
- ActiveSupport::DescendantsTracker.clear
- ActiveSupport::Dependencies.clear
+ ActiveSupport::Dependencies.interlock.attempt_loading do
+ ActiveSupport::DescendantsTracker.clear
+ ActiveSupport::Dependencies.clear
+ end
end
if config.reload_classes_only_on_change
diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb
index c1bd4072ac..d1e445ac70 100644
--- a/railties/lib/rails/commands/server.rb
+++ b/railties/lib/rails/commands/server.rb
@@ -77,17 +77,7 @@ module Rails
end
def middleware
- middlewares = []
-
- # FIXME: add Rack::Lock in the case people are using webrick.
- # This is to remain backwards compatible for those who are
- # running webrick in production. We should consider removing this
- # in development.
- if server.name == 'Rack::Handler::WEBrick'
- middlewares << [::Rack::Lock]
- end
-
- Hash.new(middlewares)
+ Hash.new([])
end
def default_options
@@ -96,8 +86,7 @@ module Rails
DoNotReverseLookup: true,
environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup,
daemonize: false,
- pid: File.expand_path("tmp/pids/server.pid"),
- config: File.expand_path("config.ru")
+ pid: File.expand_path("tmp/pids/server.pid")
})
end
diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb
index 70a20801a0..560a553789 100644
--- a/railties/lib/rails/generators/actions.rb
+++ b/railties/lib/rails/generators/actions.rb
@@ -63,12 +63,26 @@ module Rails
# Add the given source to +Gemfile+
#
+ # If block is given, gem entries in block are wrapped into the source group.
+ #
# add_source "http://gems.github.com/"
- def add_source(source, options={})
+ #
+ # add_source "http://gems.github.com/" do
+ # gem "rspec-rails"
+ # end
+ def add_source(source, options={}, &block)
log :source, source
in_root do
- prepend_file "Gemfile", "source #{quote(source)}\n", verbose: false
+ if block
+ append_file "Gemfile", "source #{quote(source)} do", force: true
+ @in_group = true
+ instance_eval(&block)
+ @in_group = false
+ append_file "Gemfile", "\nend\n", force: true
+ else
+ prepend_file "Gemfile", "source #{quote(source)}\n", verbose: false
+ end
end
end
diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb
index 7b527831b0..243694f38e 100644
--- a/railties/lib/rails/generators/named_base.rb
+++ b/railties/lib/rails/generators/named_base.rb
@@ -183,6 +183,10 @@ module Rails
!defined?(ActiveRecord::Base) || ActiveRecord::Base.pluralize_table_names
end
+ def mountable_engine?
+ defined?(ENGINE_ROOT) && namespaced?
+ end
+
# Add a class collisions name to be checked on class initialization. You
# can supply a hash with a :prefix or :suffix to be tested.
#
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index 4b73313388..b813b083f4 100644
--- a/railties/lib/rails/generators/rails/app/app_generator.rb
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -356,7 +356,9 @@ module Rails
if app_const =~ /^\d/
raise Error, "Invalid application name #{app_name}. Please give a name which does not start with numbers."
elsif RESERVED_NAMES.include?(app_name)
- raise Error, "Invalid application name #{app_name}. Please give a name which does not match one of the reserved rails words: #{RESERVED_NAMES}"
+ raise Error, "Invalid application name #{app_name}. Please give a " \
+ "name which does not match one of the reserved rails " \
+ "words: #{RESERVED_NAMES.join(", ")}"
elsif Object.const_defined?(app_const_base)
raise Error, "Invalid application name #{app_name}, constant #{app_const_base} is already in use. Please choose another application name."
end
diff --git a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
index 7f5bf0c8b8..66111004aa 100644
--- a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
+++ b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
@@ -364,7 +364,9 @@ task default: :test
elsif camelized =~ /^\d/
raise Error, "Invalid plugin name #{original_name}. Please give a name which does not start with numbers."
elsif RESERVED_NAMES.include?(name)
- raise Error, "Invalid plugin name #{original_name}. Please give a name which does not match one of the reserved rails words: #{RESERVED_NAMES}"
+ raise Error, "Invalid plugin name #{original_name}. Please give a " \
+ "name which does not match one of the reserved rails " \
+ "words: #{RESERVED_NAMES.join(", ")}"
elsif Object.const_defined?(camelized)
raise Error, "Invalid plugin name #{original_name}, constant #{camelized} is already in use. Please choose another plugin name."
end
diff --git a/railties/lib/rails/generators/rails/plugin/templates/test/integration/navigation_test.rb b/railties/lib/rails/generators/rails/plugin/templates/test/integration/navigation_test.rb
index 824caecb24..f5d1ec2046 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/test/integration/navigation_test.rb
+++ b/railties/lib/rails/generators/rails/plugin/templates/test/integration/navigation_test.rb
@@ -1,10 +1,6 @@
require 'test_helper'
class NavigationTest < ActionDispatch::IntegrationTest
-<% unless options[:skip_active_record] -%>
- fixtures :all
-<% end -%>
-
# test "the truth" do
# assert true
# end
diff --git a/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb b/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb
index 0852ffce9a..95adcc06ff 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb
+++ b/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb
@@ -20,6 +20,6 @@ Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
# Load fixtures from the engine
if ActiveSupport::TestCase.respond_to?(:fixture_path=)
ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__)
- ActiveSupport::TestCase.file_fixture_path = ActiveSupport::TestCase.fixture_path + "files"
+ ActiveSupport::TestCase.file_fixture_path = ActiveSupport::TestCase.fixture_path + "/files"
ActiveSupport::TestCase.fixtures :all
end
diff --git a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
index 7106096b60..5a8a3ca5e0 100644
--- a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
+++ b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
@@ -2,7 +2,7 @@ require 'test_helper'
<% module_namespacing do -%>
class <%= class_name %>ControllerTest < ActionController::TestCase
-<% if defined?(ENGINE_ROOT) -%>
+<% if mountable_engine? -%>
setup do
@routes = Engine.routes
end
diff --git a/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb
index d634584beb..0171da7cc7 100644
--- a/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb
+++ b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb
@@ -21,7 +21,7 @@ module TestUnit # :nodoc:
def fixture_name
@fixture_name ||=
- if defined?(ENGINE_ROOT)
+ if mountable_engine?
"%s_%s" % [namespaced_path, table_name]
else
table_name
diff --git a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
index d12a5ba733..50b98b2631 100644
--- a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
+++ b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
@@ -4,7 +4,7 @@ require 'test_helper'
class <%= controller_class_name %>ControllerTest < ActionController::TestCase
setup do
@<%= singular_table_name %> = <%= fixture_name %>(:one)
-<% if defined?(ENGINE_ROOT) -%>
+<% if mountable_engine? -%>
@routes = Engine.routes
<% end -%>
end
diff --git a/railties/lib/rails/test_unit/minitest_plugin.rb b/railties/lib/rails/test_unit/minitest_plugin.rb
index 421f032d81..ab71298509 100644
--- a/railties/lib/rails/test_unit/minitest_plugin.rb
+++ b/railties/lib/rails/test_unit/minitest_plugin.rb
@@ -34,14 +34,14 @@ module Minitest
ENV["RAILS_ENV"] = options[:environment] || "test"
- Rails::TestRequirer.require_files options[:patterns] unless run_with_autorun
+ ::Rails::TestRequirer.require_files options[:patterns] unless run_with_autorun
unless options[:full_backtrace] || ENV["BACKTRACE"]
# Plugin can run without Rails loaded, check before filtering.
- Minitest.backtrace_filter = Rails.backtrace_cleaner if Rails.respond_to?(:backtrace_cleaner)
+ Minitest.backtrace_filter = ::Rails.backtrace_cleaner if ::Rails.respond_to?(:backtrace_cleaner)
end
- self.reporter << Rails::TestUnitReporter.new(options[:io], options)
+ self.reporter << ::Rails::TestUnitReporter.new(options[:io], options)
end
mattr_accessor(:run_with_autorun) { false }
diff --git a/railties/lib/rails/test_unit/reporter.rb b/railties/lib/rails/test_unit/reporter.rb
index faf551f381..09b8675cf8 100644
--- a/railties/lib/rails/test_unit/reporter.rb
+++ b/railties/lib/rails/test_unit/reporter.rb
@@ -7,7 +7,7 @@ module Rails
self.executable = "bin/rails test"
def report
- return if results.empty?
+ return if filtered_results.empty?
io.puts
io.puts "Failed tests:"
io.puts
@@ -15,14 +15,20 @@ module Rails
end
def aggregated_results # :nodoc:
- filtered_results = results.dup
- filtered_results.reject!(&:skipped?) unless options[:verbose]
filtered_results.map do |result|
location, line = result.method(result.name).source_location
"#{self.executable} #{relative_path_for(location)}:#{line}"
end.join "\n"
end
+ def filtered_results
+ if options[:verbose]
+ results
+ else
+ results.reject(&:skipped?)
+ end
+ end
+
def relative_path_for(file)
file.sub(/^#{Rails.root}\/?/, '')
end
diff --git a/railties/test/application/asset_debugging_test.rb b/railties/test/application/asset_debugging_test.rb
index acd387256c..36ab8109a7 100644
--- a/railties/test/application/asset_debugging_test.rb
+++ b/railties/test/application/asset_debugging_test.rb
@@ -36,7 +36,7 @@ module ApplicationTests
test "assets are concatenated when debug is off and compile is off either if debug_assets param is provided" do
# config.assets.debug and config.assets.compile are false for production environment
ENV["RAILS_ENV"] = "production"
- output = Dir.chdir(app_path){ `bundle exec rake assets:precompile --trace 2>&1` }
+ output = Dir.chdir(app_path){ `bin/rake assets:precompile --trace 2>&1` }
assert $?.success?, output
require "#{app_path}/config/environment"
diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb
index 1e2a9ba040..6952472ff5 100644
--- a/railties/test/application/assets_test.rb
+++ b/railties/test/application/assets_test.rb
@@ -18,7 +18,7 @@ module ApplicationTests
def precompile!(env = nil)
quietly do
- precompile_task = "bundle exec rake assets:precompile #{env} --trace 2>&1"
+ precompile_task = "bin/rake assets:precompile #{env} --trace 2>&1"
output = Dir.chdir(app_path) { %x[ #{precompile_task} ] }
assert $?.success?, output
output
@@ -27,7 +27,7 @@ module ApplicationTests
def clean_assets!
quietly do
- assert Dir.chdir(app_path) { system('bundle exec rake assets:clobber') }
+ assert Dir.chdir(app_path) { system('bin/rake assets:clobber') }
end
end
diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb
index af98e08d0e..7bba910b9e 100644
--- a/railties/test/application/initializers/frameworks_test.rb
+++ b/railties/test/application/initializers/frameworks_test.rb
@@ -206,7 +206,7 @@ module ApplicationTests
test "use schema cache dump" do
Dir.chdir(app_path) do
`rails generate model post title:string;
- bundle exec rake db:migrate db:schema:cache:dump`
+ bin/rake db:migrate db:schema:cache:dump`
end
require "#{app_path}/config/environment"
ActiveRecord::Base.connection.drop_table("posts") # force drop posts table for test.
@@ -216,7 +216,7 @@ module ApplicationTests
test "expire schema cache dump" do
Dir.chdir(app_path) do
`rails generate model post title:string;
- bundle exec rake db:migrate db:schema:cache:dump db:rollback`
+ bin/rake db:migrate db:schema:cache:dump db:rollback`
end
silence_warnings {
require "#{app_path}/config/environment"
diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb
index ce92ebbf66..d298e8d632 100644
--- a/railties/test/application/middleware_test.rb
+++ b/railties/test/application/middleware_test.rb
@@ -26,7 +26,7 @@ module ApplicationTests
assert_equal [
"Rack::Sendfile",
"ActionDispatch::Static",
- "Rack::Lock",
+ "ActionDispatch::LoadInterlock",
"ActiveSupport::Cache::Strategy::LocalCache",
"Rack::Runtime",
"Rack::MethodOverride",
@@ -58,7 +58,7 @@ module ApplicationTests
assert_equal [
"Rack::Sendfile",
"ActionDispatch::Static",
- "Rack::Lock",
+ "ActionDispatch::LoadInterlock",
"ActiveSupport::Cache::Strategy::LocalCache",
"Rack::Runtime",
"ActionDispatch::RequestId",
@@ -121,23 +121,40 @@ module ApplicationTests
assert !middleware.include?("ActiveRecord::Migration::CheckPending")
end
- test "includes lock if cache_classes is set but eager_load is not" do
+ test "includes interlock if cache_classes is set but eager_load is not" do
add_to_config "config.cache_classes = true"
boot!
- assert middleware.include?("Rack::Lock")
+ assert_not_includes middleware, "Rack::Lock"
+ assert_includes middleware, "ActionDispatch::LoadInterlock"
+ end
+
+ test "includes interlock if cache_classes is off" do
+ add_to_config "config.cache_classes = false"
+ boot!
+ assert_not_includes middleware, "Rack::Lock"
+ assert_includes middleware, "ActionDispatch::LoadInterlock"
end
test "does not include lock if cache_classes is set and so is eager_load" do
add_to_config "config.cache_classes = true"
add_to_config "config.eager_load = true"
boot!
- assert !middleware.include?("Rack::Lock")
+ assert_not_includes middleware, "Rack::Lock"
+ assert_not_includes middleware, "ActionDispatch::LoadInterlock"
+ end
+
+ test "does not include lock if allow_concurrency is set to :unsafe" do
+ add_to_config "config.allow_concurrency = :unsafe"
+ boot!
+ assert_not_includes middleware, "Rack::Lock"
+ assert_not_includes middleware, "ActionDispatch::LoadInterlock"
end
- test "does not include lock if allow_concurrency is set" do
- add_to_config "config.allow_concurrency = true"
+ test "includes lock if allow_concurrency is disabled" do
+ add_to_config "config.allow_concurrency = false"
boot!
- assert !middleware.include?("Rack::Lock")
+ assert_includes middleware, "Rack::Lock"
+ assert_not_includes middleware, "ActionDispatch::LoadInterlock"
end
test "removes static asset server if serve_static_files is disabled" do
diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb
index 5cc9790b28..e7beab8b5e 100644
--- a/railties/test/application/rake/dbs_test.rb
+++ b/railties/test/application/rake/dbs_test.rb
@@ -28,11 +28,11 @@ module ApplicationTests
def db_create_and_drop(expected_database)
Dir.chdir(app_path) do
- output = `bundle exec rake db:create`
+ output = `bin/rake db:create`
assert_empty output
assert File.exist?(expected_database)
assert_equal expected_database, ActiveRecord::Base.connection_config[:database]
- output = `bundle exec rake db:drop`
+ output = `bin/rake db:drop`
assert_empty output
assert !File.exist?(expected_database)
end
@@ -51,9 +51,9 @@ module ApplicationTests
def db_migrate_and_status(expected_database)
Dir.chdir(app_path) do
- `rails generate model book title:string;
- bundle exec rake db:migrate`
- output = `bundle exec rake db:migrate:status`
+ `bin/rails generate model book title:string;
+ bin/rake db:migrate`
+ output = `bin/rake db:migrate:status`
assert_match(%r{database:\s+\S*#{Regexp.escape(expected_database)}}, output)
assert_match(/up\s+\d{14}\s+Create books/, output)
end
@@ -72,8 +72,8 @@ module ApplicationTests
def db_schema_dump
Dir.chdir(app_path) do
- `rails generate model book title:string;
- rake db:migrate db:schema:dump`
+ `bin/rails generate model book title:string;
+ bin/rake db:migrate db:schema:dump`
schema_dump = File.read("db/schema.rb")
assert_match(/create_table \"books\"/, schema_dump)
end
@@ -90,8 +90,8 @@ module ApplicationTests
def db_fixtures_load(expected_database)
Dir.chdir(app_path) do
- `rails generate model book title:string;
- bundle exec rake db:migrate db:fixtures:load`
+ `bin/rails generate model book title:string;
+ bin/rake db:migrate db:fixtures:load`
assert_match expected_database, ActiveRecord::Base.connection_config[:database]
require "#{app_path}/app/models/book"
assert_equal 2, Book.count
@@ -112,8 +112,8 @@ module ApplicationTests
test 'db:fixtures:load with namespaced fixture' do
require "#{app_path}/config/environment"
Dir.chdir(app_path) do
- `rails generate model admin::book title:string;
- bundle exec rake db:migrate db:fixtures:load`
+ `bin/rails generate model admin::book title:string;
+ bin/rake db:migrate db:fixtures:load`
require "#{app_path}/app/models/admin/book"
assert_equal 2, Admin::Book.count
end
@@ -121,11 +121,11 @@ module ApplicationTests
def db_structure_dump_and_load(expected_database)
Dir.chdir(app_path) do
- `rails generate model book title:string;
- bundle exec rake db:migrate db:structure:dump`
+ `bin/rails generate model book title:string;
+ bin/rake db:migrate db:structure:dump`
structure_dump = File.read("db/structure.sql")
assert_match(/CREATE TABLE \"books\"/, structure_dump)
- `bundle exec rake environment db:drop db:structure:load`
+ `bin/rake environment db:drop db:structure:load`
assert_match expected_database, ActiveRecord::Base.connection_config[:database]
require "#{app_path}/app/models/book"
#if structure is not loaded correctly, exception would be raised
@@ -147,9 +147,9 @@ module ApplicationTests
test 'db:structure:dump does not dump schema information when no migrations are used' do
Dir.chdir(app_path) do
# create table without migrations
- `bundle exec rails runner 'ActiveRecord::Base.connection.create_table(:posts) {|t| t.string :title }'`
+ `bin/rails runner 'ActiveRecord::Base.connection.create_table(:posts) {|t| t.string :title }'`
- stderr_output = capture(:stderr) { `bundle exec rake db:structure:dump` }
+ stderr_output = capture(:stderr) { `bin/rake db:structure:dump` }
assert_empty stderr_output
structure_dump = File.read("db/structure.sql")
assert_match(/CREATE TABLE \"posts\"/, structure_dump)
@@ -211,8 +211,8 @@ module ApplicationTests
def db_test_load_structure
Dir.chdir(app_path) do
- `rails generate model book title:string;
- bundle exec rake db:migrate db:structure:dump db:test:load_structure`
+ `bin/rails generate model book title:string;
+ bin/rake db:migrate db:structure:dump db:test:load_structure`
ActiveRecord::Base.configurations = Rails.application.config.database_configuration
ActiveRecord::Base.establish_connection :test
require "#{app_path}/app/models/book"
@@ -248,7 +248,7 @@ module ApplicationTests
RUBY
Dir.chdir(app_path) do
- database_path = `bundle exec rake db:setup`
+ database_path = `bin/rake db:setup`
assert_equal "development.sqlite3", File.basename(database_path.strip)
end
ensure
diff --git a/railties/test/application/rake/migrations_test.rb b/railties/test/application/rake/migrations_test.rb
index a3819b93b2..2d8bd7c571 100644
--- a/railties/test/application/rake/migrations_test.rb
+++ b/railties/test/application/rake/migrations_test.rb
@@ -15,21 +15,21 @@ module ApplicationTests
test 'running migrations with given scope' do
Dir.chdir(app_path) do
- `rails generate model user username:string password:string`
+ `bin/rails generate model user username:string password:string`
app_file "db/migrate/01_a_migration.bukkits.rb", <<-MIGRATION
class AMigration < ActiveRecord::Migration
end
MIGRATION
- output = `rake db:migrate SCOPE=bukkits`
+ output = `bin/rake db:migrate SCOPE=bukkits`
assert_no_match(/create_table\(:users\)/, output)
assert_no_match(/CreateUsers/, output)
assert_no_match(/add_column\(:users, :email, :string\)/, output)
assert_match(/AMigration: migrated/, output)
- output = `rake db:migrate SCOPE=bukkits VERSION=0`
+ output = `bin/rake db:migrate SCOPE=bukkits VERSION=0`
assert_no_match(/drop_table\(:users\)/, output)
assert_no_match(/CreateUsers/, output)
assert_no_match(/remove_column\(:users, :email\)/, output)
@@ -40,16 +40,16 @@ module ApplicationTests
test 'model and migration generator with change syntax' do
Dir.chdir(app_path) do
- `rails generate model user username:string password:string;
- rails generate migration add_email_to_users email:string`
+ `bin/rails generate model user username:string password:string;
+ bin/rails generate migration add_email_to_users email:string`
- output = `rake db:migrate`
+ output = `bin/rake db:migrate`
assert_match(/create_table\(:users\)/, output)
assert_match(/CreateUsers: migrated/, output)
assert_match(/add_column\(:users, :email, :string\)/, output)
assert_match(/AddEmailToUsers: migrated/, output)
- output = `rake db:rollback STEP=2`
+ output = `bin/rake db:rollback STEP=2`
assert_match(/drop_table\(:users\)/, output)
assert_match(/CreateUsers: reverted/, output)
assert_match(/remove_column\(:users, :email, :string\)/, output)
@@ -58,23 +58,23 @@ module ApplicationTests
end
test 'migration status when schema migrations table is not present' do
- output = Dir.chdir(app_path){ `rake db:migrate:status 2>&1` }
+ output = Dir.chdir(app_path){ `bin/rake db:migrate:status 2>&1` }
assert_equal "Schema migrations table does not exist yet.\n", output
end
test 'test migration status' do
Dir.chdir(app_path) do
- `rails generate model user username:string password:string;
- rails generate migration add_email_to_users email:string;
- rake db:migrate`
+ `bin/rails generate model user username:string password:string;
+ bin/rails generate migration add_email_to_users email:string;
+ bin/rake db:migrate`
- output = `rake db:migrate:status`
+ output = `bin/rake db:migrate:status`
assert_match(/up\s+\d{14}\s+Create users/, output)
assert_match(/up\s+\d{14}\s+Add email to users/, output)
- `rake db:rollback STEP=1`
- output = `rake db:migrate:status`
+ `bin/rake db:rollback STEP=1`
+ output = `bin/rake db:migrate:status`
assert_match(/up\s+\d{14}\s+Create users/, output)
assert_match(/down\s+\d{14}\s+Add email to users/, output)
@@ -85,17 +85,17 @@ module ApplicationTests
add_to_config('config.active_record.timestamped_migrations = false')
Dir.chdir(app_path) do
- `rails generate model user username:string password:string;
- rails generate migration add_email_to_users email:string;
- rake db:migrate`
+ `bin/rails generate model user username:string password:string;
+ bin/rails generate migration add_email_to_users email:string;
+ bin/rake db:migrate`
- output = `rake db:migrate:status`
+ output = `bin/rake db:migrate:status`
assert_match(/up\s+\d{3,}\s+Create users/, output)
assert_match(/up\s+\d{3,}\s+Add email to users/, output)
- `rake db:rollback STEP=1`
- output = `rake db:migrate:status`
+ `bin/rake db:rollback STEP=1`
+ output = `bin/rake db:migrate:status`
assert_match(/up\s+\d{3,}\s+Create users/, output)
assert_match(/down\s+\d{3,}\s+Add email to users/, output)
@@ -104,23 +104,23 @@ module ApplicationTests
test 'test migration status after rollback and redo' do
Dir.chdir(app_path) do
- `rails generate model user username:string password:string;
- rails generate migration add_email_to_users email:string;
- rake db:migrate`
+ `bin/rails generate model user username:string password:string;
+ bin/rails generate migration add_email_to_users email:string;
+ bin/rake db:migrate`
- output = `rake db:migrate:status`
+ output = `bin/rake db:migrate:status`
assert_match(/up\s+\d{14}\s+Create users/, output)
assert_match(/up\s+\d{14}\s+Add email to users/, output)
- `rake db:rollback STEP=2`
- output = `rake db:migrate:status`
+ `bin/rake db:rollback STEP=2`
+ output = `bin/rake db:migrate:status`
assert_match(/down\s+\d{14}\s+Create users/, output)
assert_match(/down\s+\d{14}\s+Add email to users/, output)
- `rake db:migrate:redo`
- output = `rake db:migrate:status`
+ `bin/rake db:migrate:redo`
+ output = `bin/rake db:migrate:status`
assert_match(/up\s+\d{14}\s+Create users/, output)
assert_match(/up\s+\d{14}\s+Add email to users/, output)
@@ -131,23 +131,23 @@ module ApplicationTests
add_to_config('config.active_record.timestamped_migrations = false')
Dir.chdir(app_path) do
- `rails generate model user username:string password:string;
- rails generate migration add_email_to_users email:string;
- rake db:migrate`
+ `bin/rails generate model user username:string password:string;
+ bin/rails generate migration add_email_to_users email:string;
+ bin/rake db:migrate`
- output = `rake db:migrate:status`
+ output = `bin/rake db:migrate:status`
assert_match(/up\s+\d{3,}\s+Create users/, output)
assert_match(/up\s+\d{3,}\s+Add email to users/, output)
- `rake db:rollback STEP=2`
- output = `rake db:migrate:status`
+ `bin/rake db:rollback STEP=2`
+ output = `bin/rake db:migrate:status`
assert_match(/down\s+\d{3,}\s+Create users/, output)
assert_match(/down\s+\d{3,}\s+Add email to users/, output)
- `rake db:migrate:redo`
- output = `rake db:migrate:status`
+ `bin/rake db:migrate:redo`
+ output = `bin/rake db:migrate:status`
assert_match(/up\s+\d{3,}\s+Create users/, output)
assert_match(/up\s+\d{3,}\s+Add email to users/, output)
@@ -158,27 +158,29 @@ module ApplicationTests
add_to_config('config.active_record.dump_schema_after_migration = false')
Dir.chdir(app_path) do
- `rails generate model book title:string;
- bundle exec rake db:migrate`
+ `bin/rails generate model book title:string`
+ output = `bin/rails generate model author name:string`
+ version = output =~ %r{[^/]+db/migrate/(\d+)_create_authors\.rb} && $1
- assert !File.exist?("db/schema.rb")
+ `bin/rake db:migrate db:rollback db:forward db:migrate:up db:migrate:down VERSION=#{version}`
+ assert !File.exist?("db/schema.rb"), "should not dump schema when configured not to"
end
add_to_config('config.active_record.dump_schema_after_migration = true')
Dir.chdir(app_path) do
- `rails generate model author name:string;
- bundle exec rake db:migrate`
+ `bin/rails generate model reviews book_id:integer`
+ `bin/rake db:migrate`
structure_dump = File.read("db/schema.rb")
- assert_match(/create_table "authors"/, structure_dump)
+ assert_match(/create_table "reviews"/, structure_dump)
end
end
test 'default schema generation after migration' do
Dir.chdir(app_path) do
- `rails generate model book title:string;
- bundle exec rake db:migrate`
+ `bin/rails generate model book title:string;
+ bin/rake db:migrate`
structure_dump = File.read("db/schema.rb")
assert_match(/create_table "books"/, structure_dump)
@@ -187,12 +189,12 @@ module ApplicationTests
test 'test migration status migrated file is deleted' do
Dir.chdir(app_path) do
- `rails generate model user username:string password:string;
- rails generate migration add_email_to_users email:string;
- rake db:migrate
+ `bin/rails generate model user username:string password:string;
+ bin/rails generate migration add_email_to_users email:string;
+ bin/rake db:migrate
rm db/migrate/*email*.rb`
- output = `rake db:migrate:status`
+ output = `bin/rake db:migrate:status`
File.write('test.txt', output)
assert_match(/up\s+\d{14}\s+Create users/, output)
diff --git a/railties/test/application/rake/notes_test.rb b/railties/test/application/rake/notes_test.rb
index 95087bf29f..d6f5fee5c3 100644
--- a/railties/test/application/rake/notes_test.rb
+++ b/railties/test/application/rake/notes_test.rb
@@ -74,7 +74,7 @@ module ApplicationTests
app_file "some_other_dir/blah.rb", "# TODO: note in some_other directory"
- run_rake_notes "SOURCE_ANNOTATION_DIRECTORIES='some_other_dir' bundle exec rake notes" do |output, lines|
+ run_rake_notes "SOURCE_ANNOTATION_DIRECTORIES='some_other_dir' bin/rake notes" do |output, lines|
assert_match(/note in app directory/, output)
assert_match(/note in config directory/, output)
assert_match(/note in db directory/, output)
@@ -102,7 +102,7 @@ module ApplicationTests
end
EOS
- run_rake_notes "bundle exec rake notes_custom" do |output, lines|
+ run_rake_notes "bin/rake notes_custom" do |output, lines|
assert_match(/\[FIXME\] note in lib directory/, output)
assert_match(/\[TODO\] note in test directory/, output)
assert_no_match(/OPTIMIZE/, output)
@@ -127,7 +127,7 @@ module ApplicationTests
private
- def run_rake_notes(command = 'bundle exec rake notes')
+ def run_rake_notes(command = 'bin/rake notes')
boot_rails
load_tasks
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index 4c1913f0cc..a040dd4cf6 100644
--- a/railties/test/application/rake_test.rb
+++ b/railties/test/application/rake_test.rb
@@ -36,7 +36,7 @@ module ApplicationTests
Rails.application.initialize!
RUBY
- assert_match("SuperMiddleware", Dir.chdir(app_path){ `rake middleware` })
+ assert_match("SuperMiddleware", Dir.chdir(app_path){ `bin/rake middleware` })
end
def test_initializers_are_executed_in_rake_tasks
@@ -51,7 +51,7 @@ module ApplicationTests
end
RUBY
- output = Dir.chdir(app_path){ `rake do_nothing` }
+ output = Dir.chdir(app_path){ `bin/rake do_nothing` }
assert_match "Doing something...", output
end
@@ -72,7 +72,7 @@ module ApplicationTests
end
RUBY
- output = Dir.chdir(app_path) { `rake do_nothing` }
+ output = Dir.chdir(app_path) { `bin/rake do_nothing` }
assert_match 'Hello world', output
end
@@ -93,14 +93,14 @@ module ApplicationTests
RUBY
Dir.chdir(app_path) do
- assert system('rake do_nothing RAILS_ENV=production'),
+ assert system('bin/rake do_nothing RAILS_ENV=production'),
'should not be pre-required for rake even eager_load=true'
end
end
def test_code_statistics_sanity
assert_match "Code LOC: 7 Test LOC: 0 Code to Test Ratio: 1:0.0",
- Dir.chdir(app_path){ `rake stats` }
+ Dir.chdir(app_path){ `bin/rake stats` }
end
def test_rake_routes_calls_the_route_inspector
@@ -110,7 +110,7 @@ module ApplicationTests
end
RUBY
- output = Dir.chdir(app_path){ `rake routes` }
+ output = Dir.chdir(app_path){ `bin/rake routes` }
assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output
end
@@ -123,7 +123,7 @@ module ApplicationTests
RUBY
ENV['CONTROLLER'] = 'cart'
- output = Dir.chdir(app_path){ `rake routes` }
+ output = Dir.chdir(app_path){ `bin/rake routes` }
assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output
end
@@ -133,7 +133,7 @@ module ApplicationTests
end
RUBY
- assert_equal <<-MESSAGE.strip_heredoc, Dir.chdir(app_path){ `rake routes` }
+ assert_equal <<-MESSAGE.strip_heredoc, Dir.chdir(app_path){ `bin/rake routes` }
You don't have any routes defined!
Please add some routes in config/routes.rb.
@@ -151,21 +151,21 @@ module ApplicationTests
end
RUBY
- output = Dir.chdir(app_path){ `rake log_something RAILS_ENV=production && cat log/production.log` }
+ output = Dir.chdir(app_path){ `bin/rake log_something RAILS_ENV=production && cat log/production.log` }
assert_match "Sample log message", output
end
def test_loading_specific_fixtures
Dir.chdir(app_path) do
- `rails generate model user username:string password:string;
- rails generate model product name:string;
- rake db:migrate`
+ `bin/rails generate model user username:string password:string;
+ bin/rails generate model product name:string;
+ bin/rake db:migrate`
end
require "#{rails_root}/config/environment"
# loading a specific fixture
- errormsg = Dir.chdir(app_path) { `rake db:fixtures:load FIXTURES=products` }
+ errormsg = Dir.chdir(app_path) { `bin/rake db:fixtures:load FIXTURES=products` }
assert $?.success?, errormsg
assert_equal 2, ::AppTemplate::Application::Product.count
@@ -174,20 +174,20 @@ module ApplicationTests
def test_loading_only_yml_fixtures
Dir.chdir(app_path) do
- `rake db:migrate`
+ `bin/rake db:migrate`
end
app_file "test/fixtures/products.csv", ""
require "#{rails_root}/config/environment"
- errormsg = Dir.chdir(app_path) { `rake db:fixtures:load` }
+ errormsg = Dir.chdir(app_path) { `bin/rake db:fixtures:load` }
assert $?.success?, errormsg
end
def test_scaffold_tests_pass_by_default
output = Dir.chdir(app_path) do
- `rails generate scaffold user username:string password:string;
- bundle exec rake db:migrate test`
+ `bin/rails generate scaffold user username:string password:string;
+ bin/rake db:migrate test`
end
assert_match(/7 runs, 12 assertions, 0 failures, 0 errors/, output)
@@ -205,8 +205,8 @@ module ApplicationTests
RUBY
output = Dir.chdir(app_path) do
- `rails generate scaffold user username:string password:string;
- bundle exec rake db:migrate test`
+ `bin/rails generate scaffold user username:string password:string;
+ bin/rake db:migrate test`
end
assert_match(/5 runs, 7 assertions, 0 failures, 0 errors/, output)
@@ -218,8 +218,8 @@ module ApplicationTests
"Rails.application.config.active_record.belongs_to_required_by_default = false"
output = Dir.chdir(app_path) do
- `rails generate scaffold LineItems product:references cart:belongs_to;
- bundle exec rake db:migrate test`
+ `bin/rails generate scaffold LineItems product:references cart:belongs_to;
+ bin/rake db:migrate test`
end
assert_match(/7 runs, 12 assertions, 0 failures, 0 errors/, output)
@@ -229,9 +229,9 @@ module ApplicationTests
def test_db_test_clone_when_using_sql_format
add_to_config "config.active_record.schema_format = :sql"
output = Dir.chdir(app_path) do
- `rails generate scaffold user username:string;
- bundle exec rake db:migrate;
- bundle exec rake db:test:clone 2>&1 --trace`
+ `bin/rails generate scaffold user username:string;
+ bin/rake db:migrate;
+ bin/rake db:test:clone 2>&1 --trace`
end
assert_match(/Execute db:test:clone_structure/, output)
end
@@ -239,9 +239,9 @@ module ApplicationTests
def test_db_test_prepare_when_using_sql_format
add_to_config "config.active_record.schema_format = :sql"
output = Dir.chdir(app_path) do
- `rails generate scaffold user username:string;
- bundle exec rake db:migrate;
- bundle exec rake db:test:prepare 2>&1 --trace`
+ `bin/rails generate scaffold user username:string;
+ bin/rake db:migrate;
+ bin/rake db:test:prepare 2>&1 --trace`
end
assert_match(/Execute db:test:load_structure/, output)
end
@@ -249,7 +249,7 @@ module ApplicationTests
def test_rake_dump_structure_should_respect_db_structure_env_variable
Dir.chdir(app_path) do
# ensure we have a schema_migrations table to dump
- `bundle exec rake db:migrate db:structure:dump SCHEMA=db/my_structure.sql`
+ `bin/rake db:migrate db:structure:dump SCHEMA=db/my_structure.sql`
end
assert File.exist?(File.join(app_path, 'db', 'my_structure.sql'))
end
@@ -258,8 +258,8 @@ module ApplicationTests
add_to_config "config.active_record.schema_format = :sql"
output = Dir.chdir(app_path) do
- `rails g model post title:string;
- bundle exec rake db:migrate:redo 2>&1 --trace;`
+ `bin/rails g model post title:string;
+ bin/rake db:migrate:redo 2>&1 --trace;`
end
# expect only Invoke db:structure:dump (first_time)
@@ -268,23 +268,23 @@ module ApplicationTests
def test_rake_dump_schema_cache
Dir.chdir(app_path) do
- `rails generate model post title:string;
- rails generate model product name:string;
- bundle exec rake db:migrate db:schema:cache:dump`
+ `bin/rails generate model post title:string;
+ bin/rails generate model product name:string;
+ bin/rake db:migrate db:schema:cache:dump`
end
assert File.exist?(File.join(app_path, 'db', 'schema_cache.dump'))
end
def test_rake_clear_schema_cache
Dir.chdir(app_path) do
- `bundle exec rake db:schema:cache:dump db:schema:cache:clear`
+ `bin/rake db:schema:cache:dump db:schema:cache:clear`
end
assert !File.exist?(File.join(app_path, 'db', 'schema_cache.dump'))
end
def test_copy_templates
Dir.chdir(app_path) do
- `bundle exec rake rails:templates:copy`
+ `bin/rake rails:templates:copy`
%w(controller mailer scaffold).each do |dir|
assert File.exist?(File.join(app_path, 'lib', 'templates', 'erb', dir))
end
@@ -299,7 +299,7 @@ module ApplicationTests
app_file "template.rb", ""
output = Dir.chdir(app_path) do
- `bundle exec rake rails:template LOCATION=template.rb`
+ `bin/rake rails:template LOCATION=template.rb`
end
assert_match(/Hello, World!/, output)
@@ -307,7 +307,7 @@ module ApplicationTests
def test_tmp_clear_should_work_if_folder_missing
FileUtils.remove_dir("#{app_path}/tmp")
- errormsg = Dir.chdir(app_path) { `bundle exec rake tmp:clear` }
+ errormsg = Dir.chdir(app_path) { `bin/rake tmp:clear` }
assert_predicate $?, :success?
assert_empty errormsg
end
diff --git a/railties/test/application/runner_test.rb b/railties/test/application/runner_test.rb
index 6595c40f8b..0c180339b4 100644
--- a/railties/test/application/runner_test.rb
+++ b/railties/test/application/runner_test.rb
@@ -25,15 +25,15 @@ module ApplicationTests
end
def test_should_include_runner_in_shebang_line_in_help_without_option
- assert_match "/rails runner", Dir.chdir(app_path) { `bundle exec rails runner` }
+ assert_match "/rails runner", Dir.chdir(app_path) { `bin/rails runner` }
end
def test_should_include_runner_in_shebang_line_in_help
- assert_match "/rails runner", Dir.chdir(app_path) { `bundle exec rails runner --help` }
+ assert_match "/rails runner", Dir.chdir(app_path) { `bin/rails runner --help` }
end
def test_should_run_ruby_statement
- assert_match "42", Dir.chdir(app_path) { `bundle exec rails runner "puts User.count"` }
+ assert_match "42", Dir.chdir(app_path) { `bin/rails runner "puts User.count"` }
end
def test_should_run_file
@@ -41,7 +41,7 @@ module ApplicationTests
puts User.count
SCRIPT
- assert_match "42", Dir.chdir(app_path) { `bundle exec rails runner "bin/count_users.rb"` }
+ assert_match "42", Dir.chdir(app_path) { `bin/rails runner "bin/count_users.rb"` }
end
def test_should_set_dollar_0_to_file
@@ -49,7 +49,7 @@ module ApplicationTests
puts $0
SCRIPT
- assert_match "bin/dollar0.rb", Dir.chdir(app_path) { `bundle exec rails runner "bin/dollar0.rb"` }
+ assert_match "bin/dollar0.rb", Dir.chdir(app_path) { `bin/rails runner "bin/dollar0.rb"` }
end
def test_should_set_dollar_program_name_to_file
@@ -57,7 +57,7 @@ module ApplicationTests
puts $PROGRAM_NAME
SCRIPT
- assert_match "bin/program_name.rb", Dir.chdir(app_path) { `bundle exec rails runner "bin/program_name.rb"` }
+ assert_match "bin/program_name.rb", Dir.chdir(app_path) { `bin/rails runner "bin/program_name.rb"` }
end
def test_with_hook
@@ -67,22 +67,22 @@ module ApplicationTests
end
RUBY
- assert_match "true", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.application.config.ran"` }
+ assert_match "true", Dir.chdir(app_path) { `bin/rails runner "puts Rails.application.config.ran"` }
end
def test_default_environment
- assert_match "development", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.env"` }
+ assert_match "development", Dir.chdir(app_path) { `bin/rails runner "puts Rails.env"` }
end
def test_environment_with_rails_env
with_rails_env "production" do
- assert_match "production", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.env"` }
+ assert_match "production", Dir.chdir(app_path) { `bin/rails runner "puts Rails.env"` }
end
end
def test_environment_with_rack_env
with_rack_env "production" do
- assert_match "production", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.env"` }
+ assert_match "production", Dir.chdir(app_path) { `bin/rails runner "puts Rails.env"` }
end
end
end
diff --git a/railties/test/application/test_runner_test.rb b/railties/test/application/test_runner_test.rb
index bbaab42a7f..494e6dd7bd 100644
--- a/railties/test/application/test_runner_test.rb
+++ b/railties/test/application/test_runner_test.rb
@@ -423,7 +423,7 @@ module ApplicationTests
end
def run_migration
- Dir.chdir(app_path) { `bundle exec rake db:migrate` }
+ Dir.chdir(app_path) { `bin/rake db:migrate` }
end
end
end
diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb
index 4a4317c4f4..2857dae07e 100644
--- a/railties/test/generators/actions_test.rb
+++ b/railties/test/generators/actions_test.rb
@@ -47,6 +47,14 @@ class ActionsTest < Rails::Generators::TestCase
assert_file 'Gemfile', /source 'http:\/\/gems\.github\.com'/
end
+ def test_add_source_with_block_adds_source_to_gemfile_with_gem
+ run_generator
+ action :add_source, 'http://gems.github.com' do
+ gem 'rspec-rails'
+ end
+ assert_file 'Gemfile', /source 'http:\/\/gems\.github\.com' do\n gem 'rspec-rails'\nend/
+ end
+
def test_gem_should_put_gem_dependency_in_gemfile
run_generator
action :gem, 'will-paginate'
diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb
index d6e5f4bd89..73e68863f4 100644
--- a/railties/test/generators/plugin_generator_test.rb
+++ b/railties/test/generators/plugin_generator_test.rb
@@ -38,7 +38,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase
assert_equal "Invalid plugin name 43things. Please give a name which does not start with numbers.\n", content
content = capture(:stderr){ run_generator [File.join(destination_root, "plugin")] }
- assert_equal "Invalid plugin name plugin. Please give a name which does not match one of the reserved rails words: [\"application\", \"destroy\", \"plugin\", \"runner\", \"test\"]\n", content
+ assert_equal "Invalid plugin name plugin. Please give a name which does not match one of the reserved rails words: application, destroy, plugin, runner, test\n", content
content = capture(:stderr){ run_generator [File.join(destination_root, "Digest")] }
assert_equal "Invalid plugin name Digest, constant Digest is already in use. Please choose another plugin name.\n", content
diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb
index 5dae36b65e..648b8d9325 100644
--- a/railties/test/generators/scaffold_controller_generator_test.rb
+++ b/railties/test/generators/scaffold_controller_generator_test.rb
@@ -186,6 +186,17 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_controller_tests_pass_by_default_inside_full_engine
+ Dir.chdir(destination_root) { `bundle exec rails plugin new bukkits --full` }
+
+ engine_path = File.join(destination_root, "bukkits")
+
+ Dir.chdir(engine_path) do
+ quietly { `bin/rails g controller dashboard foo` }
+ assert_match(/2 runs, 2 assertions, 0 failures, 0 errors/, `bundle exec rake test 2>&1`)
+ end
+ end
+
def test_api_only_generates_a_proper_api_controller
run_generator ["User", "--api"]
diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb
index 3401b96d7d..debf1140ab 100644
--- a/railties/test/generators/scaffold_generator_test.rb
+++ b/railties/test/generators/scaffold_generator_test.rb
@@ -491,4 +491,18 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
assert_match(/8 runs, 13 assertions, 0 failures, 0 errors/, `bundle exec rake test 2>&1`)
end
end
+
+ def test_scaffold_tests_pass_by_default_inside_full_engine
+ Dir.chdir(destination_root) { `bundle exec rails plugin new bukkits --full` }
+
+ engine_path = File.join(destination_root, "bukkits")
+
+ Dir.chdir(engine_path) do
+ quietly do
+ `bin/rails g scaffold User name:string age:integer;
+ bundle exec rake db:migrate`
+ end
+ assert_match(/8 runs, 13 assertions, 0 failures, 0 errors/, `bundle exec rake test 2>&1`)
+ end
+ end
end
diff --git a/railties/test/generators/shared_generator_tests.rb b/railties/test/generators/shared_generator_tests.rb
index f983b45d2b..77372fb514 100644
--- a/railties/test/generators/shared_generator_tests.rb
+++ b/railties/test/generators/shared_generator_tests.rb
@@ -56,7 +56,7 @@ module SharedGeneratorTests
reserved_words = %w[application destroy plugin runner test]
reserved_words.each do |reserved|
content = capture(:stderr){ run_generator [File.join(destination_root, reserved)] }
- assert_match(/Invalid \w+ name #{reserved}. Please give a name which does not match one of the reserved rails words: \["application", "destroy", "plugin", "runner", "test"\]\n/, content)
+ assert_match(/Invalid \w+ name #{reserved}. Please give a name which does not match one of the reserved rails words: application, destroy, plugin, runner, test\n/, content)
end
end
diff --git a/railties/test/test_unit/reporter_test.rb b/railties/test/test_unit/reporter_test.rb
index d619a3e515..3066ba82d6 100644
--- a/railties/test/test_unit/reporter_test.rb
+++ b/railties/test/test_unit/reporter_test.rb
@@ -32,6 +32,7 @@ class TestUnitReporterTest < ActiveSupport::TestCase
@reporter.record(passing_test)
@reporter.record(skipped_test)
@reporter.report
+ assert_no_match 'Failed tests:', @output.string
assert_rerun_snippet_count 0
end
@@ -47,7 +48,6 @@ class TestUnitReporterTest < ActiveSupport::TestCase
original_executable = Rails::TestUnitReporter.executable
begin
Rails::TestUnitReporter.executable = "bin/test"
- verbose = Rails::TestUnitReporter.new @output, verbose: true
@reporter.record(failed_test)
@reporter.report