aboutsummaryrefslogtreecommitdiffstats
path: root/railties
diff options
context:
space:
mode:
Diffstat (limited to 'railties')
-rw-r--r--railties/CHANGELOG.md121
-rw-r--r--railties/MIT-LICENSE2
-rw-r--r--railties/Rakefile1
-rw-r--r--railties/lib/rails.rb16
-rw-r--r--railties/lib/rails/all.rb1
-rw-r--r--railties/lib/rails/api/task.rb7
-rw-r--r--railties/lib/rails/application.rb99
-rw-r--r--railties/lib/rails/application/bootstrap.rb16
-rw-r--r--railties/lib/rails/application/configuration.rb65
-rw-r--r--railties/lib/rails/application/default_middleware_stack.rb8
-rw-r--r--railties/lib/rails/application/routes_reloader.rb4
-rw-r--r--railties/lib/rails/backtrace_cleaner.rb13
-rw-r--r--railties/lib/rails/code_statistics.rb1
-rw-r--r--railties/lib/rails/commands/commands_tasks.rb2
-rw-r--r--railties/lib/rails/commands/console.rb6
-rw-r--r--railties/lib/rails/commands/dbconsole.rb19
-rw-r--r--railties/lib/rails/commands/destroy.rb2
-rw-r--r--railties/lib/rails/commands/generate.rb2
-rw-r--r--railties/lib/rails/commands/plugin.rb2
-rw-r--r--railties/lib/rails/commands/server.rb24
-rw-r--r--railties/lib/rails/commands/update.rb9
-rw-r--r--railties/lib/rails/configuration.rb4
-rw-r--r--railties/lib/rails/engine.rb25
-rw-r--r--railties/lib/rails/engine/configuration.rb5
-rw-r--r--railties/lib/rails/gem_version.rb4
-rw-r--r--railties/lib/rails/generators.rb4
-rw-r--r--railties/lib/rails/generators/actions.rb27
-rw-r--r--railties/lib/rails/generators/actions/create_migration.rb4
-rw-r--r--railties/lib/rails/generators/app_base.rb79
-rw-r--r--railties/lib/rails/generators/base.rb2
-rw-r--r--railties/lib/rails/generators/erb/mailer/mailer_generator.rb27
-rw-r--r--railties/lib/rails/generators/erb/mailer/templates/layout.html.erb5
-rw-r--r--railties/lib/rails/generators/erb/mailer/templates/layout.text.erb1
-rw-r--r--railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb2
-rw-r--r--railties/lib/rails/generators/generated_attribute.rb28
-rw-r--r--railties/lib/rails/generators/named_base.rb6
-rw-r--r--railties/lib/rails/generators/rails/app/app_generator.rb11
-rw-r--r--railties/lib/rails/generators/rails/app/templates/Gemfile29
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/bin/rails2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/bin/setup26
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config.ru2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/application.rb10
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt5
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt25
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt9
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/assets.rb.tt3
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb4
-rw-r--r--railties/lib/rails/generators/rails/app/templates/gitignore3
-rw-r--r--railties/lib/rails/generators/rails/controller/USAGE1
-rw-r--r--railties/lib/rails/generators/rails/controller/controller_generator.rb4
-rw-r--r--railties/lib/rails/generators/rails/helper/USAGE4
-rw-r--r--railties/lib/rails/generators/rails/model/USAGE13
-rw-r--r--railties/lib/rails/generators/rails/plugin/plugin_generator.rb3
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/Gemfile8
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/rails/application.rb4
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js2
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css2
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb14
-rw-r--r--railties/lib/rails/generators/rails/scaffold/USAGE8
-rw-r--r--railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb1
-rw-r--r--railties/lib/rails/generators/resource_helpers.rb4
-rw-r--r--railties/lib/rails/generators/test_unit/helper/helper_generator.rb6
-rw-r--r--railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb6
-rw-r--r--railties/lib/rails/generators/test_unit/job/job_generator.rb13
-rw-r--r--railties/lib/rails/generators/test_unit/job/templates/unit_test.rb.erb9
-rw-r--r--railties/lib/rails/generators/test_unit/model/templates/fixtures.yml2
-rw-r--r--railties/lib/rails/generators/testing/behaviour.rb2
-rw-r--r--railties/lib/rails/info.rb36
-rw-r--r--railties/lib/rails/paths.rb14
-rw-r--r--railties/lib/rails/rack/log_tailer.rb2
-rw-r--r--railties/lib/rails/ruby_version_check.rb6
-rw-r--r--railties/lib/rails/rubyprof_ext.rb35
-rw-r--r--railties/lib/rails/source_annotation_extractor.rb5
-rw-r--r--railties/lib/rails/tasks.rb2
-rw-r--r--railties/lib/rails/tasks/statistics.rake12
-rw-r--r--railties/lib/rails/tasks/tmp.rake14
-rw-r--r--railties/lib/rails/templates/rails/mailers/email.html.erb11
-rw-r--r--railties/lib/rails/templates/rails/welcome/index.html.erb30
-rw-r--r--railties/lib/rails/test_unit/testing.rake28
-rw-r--r--railties/railties.gemspec2
-rw-r--r--railties/test/abstract_unit.rb36
-rw-r--r--railties/test/application/assets_test.rb2
-rw-r--r--railties/test/application/configuration/base_test.rb37
-rw-r--r--railties/test/application/configuration/custom_test.rb22
-rw-r--r--railties/test/application/configuration_test.rb361
-rw-r--r--railties/test/application/initializers/frameworks_test.rb8
-rw-r--r--railties/test/application/loading_test.rb29
-rw-r--r--railties/test/application/mailer_previews_test.rb63
-rw-r--r--railties/test/application/middleware/cache_test.rb12
-rw-r--r--railties/test/application/middleware/exceptions_test.rb15
-rw-r--r--railties/test/application/middleware/remote_ip_test.rb16
-rw-r--r--railties/test/application/middleware/sendfile_test.rb2
-rw-r--r--railties/test/application/middleware/session_test.rb8
-rw-r--r--railties/test/application/middleware_test.rb19
-rw-r--r--railties/test/application/multiple_applications_test.rb76
-rw-r--r--railties/test/application/rake/dbs_test.rb67
-rw-r--r--railties/test/application/routing_test.rb20
-rw-r--r--railties/test/application/test_runner_test.rb17
-rw-r--r--railties/test/application/test_test.rb185
-rw-r--r--railties/test/application/url_generation_test.rb2
-rw-r--r--railties/test/commands/dbconsole_test.rb11
-rw-r--r--railties/test/configuration/middleware_stack_proxy_test.rb1
-rw-r--r--railties/test/engine_test.rb11
-rw-r--r--railties/test/generators/actions_test.rb12
-rw-r--r--railties/test/generators/app_generator_test.rb149
-rw-r--r--railties/test/generators/argv_scrubber_test.rb2
-rw-r--r--railties/test/generators/controller_generator_test.rb2
-rw-r--r--railties/test/generators/generated_attribute_test.rb8
-rw-r--r--railties/test/generators/generator_test.rb2
-rw-r--r--railties/test/generators/generators_test_helper.rb2
-rw-r--r--railties/test/generators/helper_generator_test.rb15
-rw-r--r--railties/test/generators/job_generator_test.rb29
-rw-r--r--railties/test/generators/mailer_generator_test.rb39
-rw-r--r--railties/test/generators/migration_generator_test.rb40
-rw-r--r--railties/test/generators/model_generator_test.rb87
-rw-r--r--railties/test/generators/namespaced_generators_test.rb11
-rw-r--r--railties/test/generators/plugin_generator_test.rb75
-rw-r--r--railties/test/generators/resource_generator_test.rb1
-rw-r--r--railties/test/generators/scaffold_controller_generator_test.rb2
-rw-r--r--railties/test/generators/scaffold_generator_test.rb20
-rw-r--r--railties/test/generators_test.rb10
-rw-r--r--railties/test/isolation/abstract_unit.rb24
-rw-r--r--railties/test/path_generation_test.rb88
-rw-r--r--railties/test/rails_info_controller_test.rb9
-rw-r--r--railties/test/rails_info_test.rb13
-rw-r--r--railties/test/railties/engine_test.rb57
129 files changed, 2076 insertions, 722 deletions
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index 36b26b9bd9..f67c87d74d 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -2,118 +2,31 @@
*Andrew Kozlov*
-* Add `Rails::Application.config_for` to load a configuration for the current
- environment.
+* Add `config/initializers/callback_terminator.rb`
- # config/exception_notification.yml:
- production:
- url: http://127.0.0.1:8080
- namespace: my_app_production
- development:
- url: http://localhost:3001
- namespace: my_app_development
+ Newly generated Rails apps have a new initializer called
+ `callback_terminator.rb` which sets the value of the configuration option
+ `config.active_support.halt_callback_chains_on_return_false` to `false`.
- # config/production.rb
- MyApp::Application.configure do
- config.middleware.use ExceptionNotifier, config_for(:exception_notification)
- end
+ As a result, new Rails apps do not halt callback chains when a callback
+ returns `false`; only when they are explicitly halted with `throw(:abort)`.
- *Rafael Mendonça França*, *DHH*
+ The terminator is *not* added when running `rake rails:update`, so returning
+ `false` will still work on old apps ported to Rails 5, displaying a
+ deprecation warning to prompt users to update their code to the new syntax.
-* Deprecate `Rails::Rack::LogTailer` without replacement.
+ *claudiob*
- *Rafael Mendonça França*
+* Generated fixtures won't use the id when generated with references attributes.
-* Add a generic --skip-gems options to generator
+ *Pablo Olmos de Aguilera Corradini*
- This option is useful if users want to remove some gems like jbuilder,
- turbolinks, coffee-rails, etc that don't have specific options on the
- generator.
+* Add `--skip-action-mailer` option to the app generator.
- rails new my_app --skip-gems turbolinks coffee-rails
+ *claudiob*
- *Rafael Mendonça França*
+* Autoload any second level directories called `app/*/concerns`.
-* Invalid `bin/rails generate` commands will now show spelling suggestions.
+ *Alex Robbin*
- *Richard Schneeman*
-
-* Add `bin/setup` script to bootstrap an application.
-
- *Yves Senn*
-
-* Replace double quotes with single quotes while adding an entry into Gemfile.
-
- *Alexander Belaev*
-
-* Default `config.assets.digest` to `true` in development.
-
- *Dan Kang*
-
-* Load database configuration from the first `database.yml` available in paths.
-
- *Pier-Olivier Thibault*
-
-* Reading name and email from git for plugin gemspec.
-
- Fixes #9589.
-
- *Arun Agrawal*, *Abd ar-Rahman Hamidi*, *Roman Shmatov*
-
-* Fix `console` and `generators` blocks defined at different environments.
-
- Fixes #14748.
-
- *Rafael Mendonça França*
-
-* Move configuration of asset precompile list and version to an initializer.
-
- *Matthew Draper*
-
-* Remove sqlite3 lines from `.gitignore` if the application is not using sqlite3.
-
- *Dmitrii Golub*
-
-* Add public API to register new extensions for `rake notes`.
-
- Example:
-
- config.annotations.register_extensions("scss", "sass") { |tag| /\/\/\s*(#{tag}):?\s*(.*)$/ }
-
- *Roberto Miranda*
-
-* Removed unnecessary `rails application` command.
-
- *Arun Agrawal*
-
-* Make the `rails:template` rake task load the application's initializers.
-
- Fixes #12133.
-
- *Robin Dupret*
-
-* Introduce `Rails.gem_version` as a convenience method to return
- `Gem::Version.new(Rails.version)`, suggesting a more reliable way to perform
- version comparison.
-
- Example:
-
- Rails.version #=> "4.1.2"
- Rails.gem_version #=> #<Gem::Version "4.1.2">
-
- Rails.version > "4.1.10" #=> false
- Rails.gem_version > Gem::Version.new("4.1.10") #=> true
- Gem::Requirement.new("~> 4.1.2") =~ Rails.gem_version #=> true
-
- *Prem Sichanugrist*
-
-* Avoid namespacing routes inside engines.
-
- Mountable engines are namespaced by default so the generated routes
- were too while they should not.
-
- Fixes #14079.
-
- *Yves Senn*, *Carlos Antonio da Silva*, *Robin Dupret*
-
-Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/railties/CHANGELOG.md) for previous changes.
+Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/railties/CHANGELOG.md) for previous changes.
diff --git a/railties/MIT-LICENSE b/railties/MIT-LICENSE
index 2950f05b11..7c2197229d 100644
--- a/railties/MIT-LICENSE
+++ b/railties/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004-2014 David Heinemeier Hansson
+Copyright (c) 2004-2015 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/railties/Rakefile b/railties/Rakefile
index a899d069b5..9a377ce4ee 100644
--- a/railties/Rakefile
+++ b/railties/Rakefile
@@ -29,6 +29,7 @@ Rake::TestTask.new('test:regular') do |t|
t.pattern = 'test/**/*_test.rb'
t.warning = true
t.verbose = true
+ t.ruby_opts = ["--dev"] if defined?(JRUBY_VERSION)
end
# Generate GEM ----------------------------------------------------------------------------
diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb
index ecd8c22dd8..a1a105ef2b 100644
--- a/railties/lib/rails.rb
+++ b/railties/lib/rails.rb
@@ -29,7 +29,13 @@ module Rails
autoload :WelcomeController
class << self
- attr_accessor :application, :cache, :logger
+ @application = @app_class = nil
+
+ attr_writer :application
+ attr_accessor :app_class, :cache, :logger
+ def application
+ @application ||= (app_class.instance if app_class)
+ end
delegate :initialize!, :initialized?, to: :application
@@ -50,10 +56,18 @@ module Rails
application && application.config.root
end
+ # Returns the current Rails environment.
+ #
+ # Rails.env # => "development"
+ # Rails.env.development? # => true
+ # Rails.env.production? # => false
def env
@_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development")
end
+ # Sets the Rails environment.
+ #
+ # Rails.env = "staging" # => "staging"
def env=(environment)
@_env = ActiveSupport::StringInquirer.new(environment)
end
diff --git a/railties/lib/rails/all.rb b/railties/lib/rails/all.rb
index 2e83c0fe14..45361fca83 100644
--- a/railties/lib/rails/all.rb
+++ b/railties/lib/rails/all.rb
@@ -5,6 +5,7 @@ require "rails"
action_controller
action_view
action_mailer
+ active_job
rails/test_unit
sprockets
).each do |framework|
diff --git a/railties/lib/rails/api/task.rb b/railties/lib/rails/api/task.rb
index 3e32576040..4d49244807 100644
--- a/railties/lib/rails/api/task.rb
+++ b/railties/lib/rails/api/task.rb
@@ -50,6 +50,13 @@ module Rails
)
},
+ 'activejob' => {
+ :include => %w(
+ README.md
+ lib/active_job/**/*.rb
+ )
+ },
+
'railties' => {
:include => %w(
README.rdoc
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index c5fd08e743..ad8b52a39f 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -87,7 +87,20 @@ module Rails
class << self
def inherited(base)
super
- base.instance
+ Rails.app_class = base
+ add_lib_to_load_path!(find_root(base.called_from))
+ end
+
+ def instance
+ super.run_load_hooks!
+ end
+
+ def create(initial_variable_values = {}, &block)
+ new(initial_variable_values, &block).run_load_hooks!
+ end
+
+ def find_root(from)
+ find_root_with_flag "config.ru", from, Dir.pwd
end
# Makes the +new+ method public.
@@ -116,24 +129,31 @@ module Rails
@ordered_railties = nil
@railties = nil
@message_verifiers = {}
+ @ran_load_hooks = false
- Rails.application ||= self
+ # are these actually used?
+ @initial_variable_values = initial_variable_values
+ @block = block
+ end
- add_lib_to_load_path!
+ # Returns true if the application is initialized.
+ def initialized?
+ @initialized
+ end
+
+ def run_load_hooks! # :nodoc:
+ return self if @ran_load_hooks
+ @ran_load_hooks = true
ActiveSupport.run_load_hooks(:before_configuration, self)
- initial_variable_values.each do |variable_name, value|
+ @initial_variable_values.each do |variable_name, value|
if INITIAL_VARIABLES.include?(variable_name)
instance_variable_set("@#{variable_name}", value)
end
end
- instance_eval(&block) if block_given?
- end
-
- # Returns true if the application is initialized.
- def initialized?
- @initialized
+ instance_eval(&@block) if @block
+ self
end
# Implements call according to the Rack API. It simply
@@ -158,7 +178,7 @@ module Rails
key_generator = ActiveSupport::KeyGenerator.new(secrets.secret_key_base, iterations: 1000)
ActiveSupport::CachingKeyGenerator.new(key_generator)
else
- ActiveSupport::LegacyKeyGenerator.new(config.secret_token)
+ ActiveSupport::LegacyKeyGenerator.new(secrets.secret_token)
end
end
@@ -200,7 +220,7 @@ module Rails
# namespace: my_app_development
#
# # config/production.rb
- # MyApp::Application.configure do
+ # Rails.application.configure do
# config.middleware.use ExceptionNotifier, config_for(:exception_notification)
# end
def config_for(name)
@@ -228,7 +248,7 @@ module Rails
super.merge({
"action_dispatch.parameter_filter" => config.filter_parameters,
"action_dispatch.redirect_filter" => config.filter_redirect,
- "action_dispatch.secret_token" => config.secret_token,
+ "action_dispatch.secret_token" => secrets.secret_token,
"action_dispatch.secret_key_base" => secrets.secret_key_base,
"action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
"action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local,
@@ -239,7 +259,8 @@ module Rails
"action_dispatch.signed_cookie_salt" => config.action_dispatch.signed_cookie_salt,
"action_dispatch.encrypted_cookie_salt" => config.action_dispatch.encrypted_cookie_salt,
"action_dispatch.encrypted_signed_cookie_salt" => config.action_dispatch.encrypted_signed_cookie_salt,
- "action_dispatch.cookies_serializer" => config.action_dispatch.cookies_serializer
+ "action_dispatch.cookies_serializer" => config.action_dispatch.cookies_serializer,
+ "action_dispatch.cookies_digest" => config.action_dispatch.cookies_digest
})
end
end
@@ -295,8 +316,8 @@ module Rails
# are changing config.root inside your application definition or having a custom
# Rails application, you will need to add lib to $LOAD_PATH on your own in case
# you need to load files in lib/ during the application configuration as well.
- def add_lib_to_load_path! #:nodoc:
- path = File.join config.root, 'lib'
+ def self.add_lib_to_load_path!(root) #:nodoc:
+ path = File.join root, 'lib'
if File.exist?(path) && !$LOAD_PATH.include?(path)
$LOAD_PATH.unshift(path)
end
@@ -340,14 +361,28 @@ module Rails
end
def config #:nodoc:
- @config ||= Application::Configuration.new(find_root_with_flag("config.ru", Dir.pwd))
+ @config ||= Application::Configuration.new(self.class.find_root(self.class.called_from))
end
def config=(configuration) #:nodoc:
@config = configuration
end
- def secrets #:nodoc:
+ # Returns secrets added to config/secrets.yml.
+ #
+ # Example:
+ #
+ # development:
+ # secret_key_base: 836fa3665997a860728bcb9e9a1e704d427cfc920e79d847d79c8a9a907b9e965defa4154b2b86bdec6930adbe33f21364523a6f6ce363865724549fdfc08553
+ # test:
+ # secret_key_base: 5a37811464e7d378488b0f073e2193b093682e4e21f5d6f3ae0a4e1781e61a351fdc878a843424e81c73fb484a40d23f92c8dafac4870e74ede6e5e174423010
+ # production:
+ # secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
+ # namespace: my_app_production
+ #
+ # +Rails.application.secrets.namespace+ returns +my_app_production+ in the
+ # production environment.
+ def secrets
@secrets ||= begin
secrets = ActiveSupport::OrderedOptions.new
yaml = config.paths["config/secrets"].first
@@ -360,6 +395,8 @@ module Rails
# Fallback to config.secret_key_base if secrets.secret_key_base isn't set
secrets.secret_key_base ||= config.secret_key_base
+ # Fallback to config.secret_token if secrets.secret_token isn't set
+ secrets.secret_token ||= config.secret_token
secrets
end
@@ -396,8 +433,14 @@ module Rails
end
end
+ # Return an array of railties respecting the order they're loaded
+ # and the order specified by the +railties_order+ config.
+ #
+ # While when running initializers we need engines in reverse
+ # order here when copying migrations from railties we need then in the same
+ # order as given by +railties_order+
def migration_railties # :nodoc:
- (ordered_railties & railties_without_main_app).reverse
+ ordered_railties.flatten - [self]
end
protected
@@ -430,11 +473,6 @@ module Rails
super
end
- def railties_without_main_app # :nodoc:
- @railties_without_main_app ||= Rails::Railtie.subclasses.map(&:instance) +
- Rails::Engine.subclasses.map(&:instance)
- end
-
# Returns the ordered railties for this application considering railties_order.
def ordered_railties #:nodoc:
@ordered_railties ||= begin
@@ -454,13 +492,13 @@ module Rails
index = order.index(:all)
order[index] = all
- order.reverse.flatten
+ order
end
end
def railties_initializers(current) #:nodoc:
initializers = []
- ordered_railties.each do |r|
+ ordered_railties.reverse.flatten.each do |r|
if r == self
initializers += current
else
@@ -488,8 +526,13 @@ module Rails
end
def validate_secret_key_config! #:nodoc:
- if secrets.secret_key_base.blank? && config.secret_token.blank?
- raise "Missing `secret_key_base` for '#{Rails.env}' environment, set this value in `config/secrets.yml`"
+ if secrets.secret_key_base.blank?
+ ActiveSupport::Deprecation.warn "You didn't set `secret_key_base`. " +
+ "Read the upgrade documentation to learn more about this new config option."
+
+ if secrets.secret_token.blank?
+ raise "Missing `secret_token` and `secret_key_base` for '#{Rails.env}' environment, set these values in `config/secrets.yml`"
+ end
end
end
end
diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb
index a26d41c0cf..71d3febde4 100644
--- a/railties/lib/rails/application/bootstrap.rb
+++ b/railties/lib/rails/application/bootstrap.rb
@@ -1,5 +1,6 @@
require "active_support/notifications"
require "active_support/dependencies"
+require "active_support/deprecation"
require "active_support/descendants_tracker"
module Rails
@@ -47,12 +48,25 @@ INFO
logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDERR))
logger.level = ActiveSupport::Logger::WARN
logger.warn(
- "Rails Error: Unable to access log file. Please ensure that #{path} exists and is chmod 0666. " +
+ "Rails Error: Unable to access log file. Please ensure that #{path} exists and is writable " +
+ "(ie, make it writable for user and group: chmod 0664 #{path}). " +
"The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
)
logger
end
+ if Rails.env.production? && !config.has_explicit_log_level?
+ ActiveSupport::Deprecation.warn \
+ "You did not specify a `log_level` in `production.rb`. Currently, " \
+ "the default value for `log_level` is `:info` for the production " \
+ "environment and `:debug` in all other environments. In Rails 5 " \
+ "the default value will be unified to `:debug` across all " \
+ "environments. To preserve the current setting, add the following " \
+ "line to your `production.rb`:\n" \
+ "\n" \
+ " config.log_level = :info\n\n"
+ end
+
Rails.logger.level = ActiveSupport::Logger.const_get(config.log_level.to_s.upcase)
end
diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb
index 5e8f4de847..fdc741dd08 100644
--- a/railties/lib/rails/application/configuration.rb
+++ b/railties/lib/rails/application/configuration.rb
@@ -1,5 +1,7 @@
require 'active_support/core_ext/kernel/reporting'
+require 'active_support/core_ext/string/filters'
require 'active_support/file_update_checker'
+require 'active_support/deprecation'
require 'rails/engine/configuration'
require 'rails/source_annotation_extractor'
@@ -11,11 +13,10 @@ module Rails
:eager_load, :exceptions_app, :file_watcher, :filter_parameters,
:force_ssl, :helpers_paths, :logger, :log_formatter, :log_tags,
:railties_order, :relative_url_root, :secret_key_base, :secret_token,
- :serve_static_assets, :ssl_options, :static_cache_control, :session_options,
+ :serve_static_files, :ssl_options, :static_cache_control, :session_options,
:time_zone, :reload_classes_only_on_change,
- :beginning_of_week, :filter_redirect
+ :beginning_of_week, :filter_redirect, :x
- attr_writer :log_level
attr_reader :encoding
def initialize(*)
@@ -26,7 +27,7 @@ module Rails
@filter_parameters = []
@filter_redirect = []
@helpers_paths = []
- @serve_static_assets = true
+ @serve_static_files = true
@static_cache_control = nil
@force_ssl = false
@ssl_options = {}
@@ -34,6 +35,7 @@ module Rails
@session_options = {}
@time_zone = "UTC"
@beginning_of_week = :monday
+ @has_explicit_log_level = false
@log_level = nil
@middleware = app_middleware
@generators = app_generators
@@ -48,6 +50,7 @@ module Rails
@eager_load = nil
@secret_token = nil
@secret_key_base = nil
+ @x = Custom.new
@assets = ActiveSupport::OrderedOptions.new
@assets.enabled = true
@@ -92,9 +95,10 @@ module Rails
# Loads and returns the entire raw configuration of database from
# values stored in `config/database.yml`.
def database_configuration
- yaml = Pathname.new(paths["config/database"].existent.first || "")
+ path = paths["config/database"].existent.first
+ yaml = Pathname.new(path) if path
- config = if yaml.exist?
+ config = if yaml && yaml.exist?
require "yaml"
require "erb"
YAML.load(ERB.new(yaml.read).result) || {}
@@ -103,7 +107,7 @@ module Rails
# by Active Record.
{}
else
- raise "Could not load database configuration. No such file - #{yaml}"
+ raise "Could not load database configuration. No such file - #{paths["config/database"].instance_variable_get(:@paths)}"
end
config
@@ -115,8 +119,17 @@ module Rails
raise e, "Cannot load `Rails.application.database_configuration`:\n#{e.message}", e.backtrace
end
+ def has_explicit_log_level? # :nodoc:
+ @has_explicit_log_level
+ end
+
+ def log_level=(level)
+ @has_explicit_log_level = !!(level)
+ @log_level = level
+ end
+
def log_level
- @log_level ||= Rails.env.production? ? :info : :debug
+ @log_level ||= (Rails.env.production? ? :info : :debug)
end
def colorize_logging
@@ -128,6 +141,25 @@ module Rails
self.generators.colorize_logging = val
end
+ # :nodoc:
+ SERVE_STATIC_ASSETS_DEPRECATION_MESSAGE = <<-MSG.squish
+ The configuration option `config.serve_static_assets` has been renamed
+ to `config.serve_static_files` to clarify its role (it merely enables
+ serving everything in the `public` folder and is unrelated to the asset
+ pipeline). The `serve_static_assets` alias will be removed in Rails 5.0.
+ Please migrate your configuration files accordingly.
+ MSG
+
+ def serve_static_assets
+ ActiveSupport::Deprecation.warn SERVE_STATIC_ASSETS_DEPRECATION_MESSAGE
+ serve_static_files
+ end
+
+ def serve_static_assets=(value)
+ ActiveSupport::Deprecation.warn SERVE_STATIC_ASSETS_DEPRECATION_MESSAGE
+ self.serve_static_files = value
+ end
+
def session_store(*args)
if args.empty?
case @session_store
@@ -154,6 +186,23 @@ module Rails
def annotations
SourceAnnotationExtractor::Annotation
end
+
+ private
+ class Custom #:nodoc:
+ def initialize
+ @configurations = Hash.new
+ end
+
+ def method_missing(method, *args)
+ if method =~ /=$/
+ @configurations[$`.to_sym] = args.first
+ else
+ @configurations.fetch(method) {
+ @configurations[method] = ActiveSupport::OrderedOptions.new
+ }
+ end
+ end
+ end
end
end
end
diff --git a/railties/lib/rails/application/default_middleware_stack.rb b/railties/lib/rails/application/default_middleware_stack.rb
index a00afe008c..02eea82b0c 100644
--- a/railties/lib/rails/application/default_middleware_stack.rb
+++ b/railties/lib/rails/application/default_middleware_stack.rb
@@ -17,7 +17,7 @@ module Rails
middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
- if config.serve_static_assets
+ if config.serve_static_files
middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control
end
@@ -66,7 +66,11 @@ module Rails
end
def allow_concurrency?
- config.allow_concurrency.nil? ? config.cache_classes : config.allow_concurrency
+ if config.allow_concurrency.nil?
+ config.cache_classes && config.eager_load
+ else
+ config.allow_concurrency
+ end
end
def load_rack_cache
diff --git a/railties/lib/rails/application/routes_reloader.rb b/railties/lib/rails/application/routes_reloader.rb
index 737977adf9..cf0a4e128f 100644
--- a/railties/lib/rails/application/routes_reloader.rb
+++ b/railties/lib/rails/application/routes_reloader.rb
@@ -41,9 +41,7 @@ module Rails
end
def finalize!
- route_sets.each do |routes|
- routes.finalize!
- end
+ route_sets.each(&:finalize!)
end
def revert
diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb
index 8cc8eb1103..5276eb33c9 100644
--- a/railties/lib/rails/backtrace_cleaner.rb
+++ b/railties/lib/rails/backtrace_cleaner.rb
@@ -4,12 +4,16 @@ module Rails
class BacktraceCleaner < ActiveSupport::BacktraceCleaner
APP_DIRS_PATTERN = /^\/?(app|config|lib|test)/
RENDER_TEMPLATE_PATTERN = /:in `_render_template_\w*'/
+ EMPTY_STRING = ''.freeze
+ SLASH = '/'.freeze
+ DOT_SLASH = './'.freeze
def initialize
super
- add_filter { |line| line.sub("#{Rails.root}/", '') }
- add_filter { |line| line.sub(RENDER_TEMPLATE_PATTERN, '') }
- add_filter { |line| line.sub('./', '/') } # for tests
+ @root = "#{Rails.root}/".freeze
+ add_filter { |line| line.sub(@root, EMPTY_STRING) }
+ add_filter { |line| line.sub(RENDER_TEMPLATE_PATTERN, EMPTY_STRING) }
+ add_filter { |line| line.sub(DOT_SLASH, SLASH) } # for tests
add_gem_filters
add_silencer { |line| line !~ APP_DIRS_PATTERN }
@@ -21,7 +25,8 @@ module Rails
return if gems_paths.empty?
gems_regexp = %r{(#{gems_paths.join('|')})/gems/([^/]+)-([\w.]+)/(.*)}
- add_filter { |line| line.sub(gems_regexp, '\2 (\3) \4') }
+ gems_result = '\2 (\3) \4'.freeze
+ add_filter { |line| line.sub(gems_regexp, gems_result) }
end
end
end
diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb
index 0ae6d2a455..27779857b7 100644
--- a/railties/lib/rails/code_statistics.rb
+++ b/railties/lib/rails/code_statistics.rb
@@ -6,6 +6,7 @@ class CodeStatistics #:nodoc:
'Helper tests',
'Model tests',
'Mailer tests',
+ 'Job tests',
'Integration tests',
'Functional tests (old)',
'Unit tests (old)']
diff --git a/railties/lib/rails/commands/commands_tasks.rb b/railties/lib/rails/commands/commands_tasks.rb
index 6cfbc70c51..8bae08e44e 100644
--- a/railties/lib/rails/commands/commands_tasks.rb
+++ b/railties/lib/rails/commands/commands_tasks.rb
@@ -127,7 +127,7 @@ EOT
require 'rails/generators'
require_application_and_environment!
Rails.application.load_generators
- require "rails/commands/#{command}"
+ require_command!(command)
end
# Change to the application's path if there is no config.ru file in current directory.
diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb
index 555d8f31e1..96ced3c2f9 100644
--- a/railties/lib/rails/commands/console.rb
+++ b/railties/lib/rails/commands/console.rb
@@ -18,12 +18,12 @@ module Rails
opt.on("-e", "--environment=name", String,
"Specifies the environment to run this console under (test/development/production).",
"Default: development") { |v| options[:environment] = v.strip }
- opt.on("--debugger", 'Enable the debugger.') do |v|
+ opt.on("--debugger", 'Enables the debugger.') do |v|
if RUBY_VERSION < '2.0.0'
options[:debugger] = v
else
- puts "=> Notice: debugger option is ignored since ruby 2.0 and " \
- "it will be removed in future versions"
+ puts "=> Notice: debugger option is ignored since Ruby 2.0 and " \
+ "it will be removed in future versions."
end
end
opt.parse!(arguments)
diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb
index 1a2613a8d0..0d8b3de0eb 100644
--- a/railties/lib/rails/commands/dbconsole.rb
+++ b/railties/lib/rails/commands/dbconsole.rb
@@ -44,7 +44,7 @@ module Rails
find_cmd_and_exec(['mysql', 'mysql5'], *args)
- when "postgresql", "postgres", "postgis"
+ when /^postgres|^postgis/
ENV['PGUSER'] = config["username"] if config["username"]
ENV['PGHOST'] = config["host"] if config["host"]
ENV['PGPORT'] = config["port"].to_s if config["port"]
@@ -74,6 +74,21 @@ module Rails
find_cmd_and_exec('sqlplus', logon)
+ when "sqlserver"
+ args = []
+
+ args += ["-D", "#{config['database']}"] if config['database']
+ args += ["-U", "#{config['username']}"] if config['username']
+ args += ["-P", "#{config['password']}"] if config['password']
+
+ if config['host']
+ host_arg = "#{config['host']}"
+ host_arg << ":#{config['port']}" if config['port']
+ args += ["-S", host_arg]
+ end
+
+ find_cmd_and_exec("sqsh", *args)
+
else
abort "Unknown command-line client for #{config['database']}. Submit a Rails patch to add support!"
end
@@ -163,7 +178,7 @@ module Rails
found = commands.detect do |cmd|
dirs_on_path.detect do |path|
full_path_command = File.join(path, cmd)
- File.executable? full_path_command
+ File.file?(full_path_command) && File.executable?(full_path_command)
end
end
diff --git a/railties/lib/rails/commands/destroy.rb b/railties/lib/rails/commands/destroy.rb
index 5479da86a0..ce26cc3fde 100644
--- a/railties/lib/rails/commands/destroy.rb
+++ b/railties/lib/rails/commands/destroy.rb
@@ -1,5 +1,7 @@
require 'rails/generators'
+#if no argument/-h/--help is passed to rails destroy command, then
+#it generates the help associated.
if [nil, "-h", "--help"].include?(ARGV.first)
Rails::Generators.help 'destroy'
exit
diff --git a/railties/lib/rails/commands/generate.rb b/railties/lib/rails/commands/generate.rb
index 351c59c645..926c36b967 100644
--- a/railties/lib/rails/commands/generate.rb
+++ b/railties/lib/rails/commands/generate.rb
@@ -1,5 +1,7 @@
require 'rails/generators'
+#if no argument/-h/--help is passed to rails generate command, then
+#it generates the help associated.
if [nil, "-h", "--help"].include?(ARGV.first)
Rails::Generators.help 'generate'
exit
diff --git a/railties/lib/rails/commands/plugin.rb b/railties/lib/rails/commands/plugin.rb
index 95bbdd4cdf..52d8966ead 100644
--- a/railties/lib/rails/commands/plugin.rb
+++ b/railties/lib/rails/commands/plugin.rb
@@ -11,7 +11,7 @@ else
end
if File.exist?(railsrc)
extra_args_string = File.read(railsrc)
- extra_args = extra_args_string.split(/\n+/).flat_map {|l| l.split}
+ extra_args = extra_args_string.split(/\n+/).flat_map(&:split)
puts "Using #{extra_args.join(" ")} from #{railsrc}"
ARGV.insert(1, *extra_args)
end
diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb
index c3b7bb6f84..3f14910edf 100644
--- a/railties/lib/rails/commands/server.rb
+++ b/railties/lib/rails/commands/server.rb
@@ -20,20 +20,20 @@ module Rails
def option_parser(options)
OptionParser.new do |opts|
- opts.banner = "Usage: rails server [mongrel, thin, etc] [options]"
+ opts.banner = "Usage: rails server [mongrel, thin etc] [options]"
opts.on("-p", "--port=port", Integer,
"Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v }
- opts.on("-b", "--binding=ip", String,
- "Binds Rails to the specified ip.", "Default: 0.0.0.0") { |v| options[:Host] = v }
+ opts.on("-b", "--binding=IP", String,
+ "Binds Rails to the specified IP.", "Default: localhost") { |v| options[:Host] = v }
opts.on("-c", "--config=file", String,
- "Use custom rackup configuration file") { |v| options[:config] = v }
- opts.on("-d", "--daemon", "Make server run as a Daemon.") { options[:daemonize] = true }
- opts.on("-u", "--debugger", "Enable the debugger") do
+ "Uses a custom rackup configuration.") { |v| options[:config] = v }
+ opts.on("-d", "--daemon", "Runs server as a Daemon.") { options[:daemonize] = true }
+ opts.on("-u", "--debugger", "Enables the debugger.") do
if RUBY_VERSION < '2.0.0'
options[:debugger] = true
else
- puts "=> Notice: debugger option is ignored since ruby 2.0 and " \
- "it will be removed in future versions"
+ puts "=> Notice: debugger option is ignored since Ruby 2.0 and " \
+ "it will be removed in future versions."
end
end
opts.on("-e", "--environment=name", String,
@@ -45,7 +45,7 @@ module Rails
opts.separator ""
- opts.on("-h", "--help", "Show this help message.") { puts opts; exit }
+ opts.on("-h", "--help", "Shows this help message.") { puts opts; exit }
end
end
end
@@ -126,15 +126,11 @@ module Rails
puts "=> Rails #{Rails.version} application starting in #{Rails.env} on #{url}"
puts "=> Run `rails server -h` for more startup options"
- if options[:Host].to_s.match(/0\.0\.0\.0/)
- puts "=> Notice: server is listening on all interfaces (#{options[:Host]}). Consider using 127.0.0.1 (--binding option)"
- end
-
puts "=> Ctrl-C to shutdown server" unless options[:daemonize]
end
def create_tmp_directories
- %w(cache pids sessions sockets).each do |dir_to_make|
+ %w(cache pids sockets).each do |dir_to_make|
FileUtils.mkdir_p(File.join(Rails.root, 'tmp', dir_to_make))
end
end
diff --git a/railties/lib/rails/commands/update.rb b/railties/lib/rails/commands/update.rb
deleted file mode 100644
index 59fae5c337..0000000000
--- a/railties/lib/rails/commands/update.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-require File.expand_path(File.join(File.dirname(__FILE__), '..', 'generators'))
-
-if ARGV.size == 0
- Rails::Generators.help
- exit
-end
-
-name = ARGV.shift
-Rails::Generators.invoke name, ARGV, behavior: :skip
diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb
index f5d7dede66..f99cec04c5 100644
--- a/railties/lib/rails/configuration.rb
+++ b/railties/lib/rails/configuration.rb
@@ -18,11 +18,11 @@ module Rails
# This will put the <tt>Magical::Unicorns</tt> middleware on the end of the stack.
# You can use +insert_before+ if you wish to add a middleware before another:
#
- # config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns
+ # config.middleware.insert_before Rack::Head, Magical::Unicorns
#
# There's also +insert_after+ which will insert a middleware after another:
#
- # config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns
+ # config.middleware.insert_after Rack::Head, Magical::Unicorns
#
# Middlewares can also be completely swapped out and replaced with others:
#
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
index b36ab3d0d5..a338f31f15 100644
--- a/railties/lib/rails/engine.rb
+++ b/railties/lib/rails/engine.rb
@@ -110,8 +110,8 @@ module Rails
#
# == Endpoint
#
- # An engine can be also a rack application. It can be useful if you have a rack application that
- # you would like to wrap with +Engine+ and provide some of the +Engine+'s features.
+ # An engine can also be a rack application. It can be useful if you have a rack application that
+ # you would like to wrap with +Engine+ and provide with some of the +Engine+'s features.
#
# To do that, use the +endpoint+ method:
#
@@ -351,7 +351,7 @@ module Rails
base.called_from = begin
call_stack = if Kernel.respond_to?(:caller_locations)
- caller_locations.map(&:path)
+ caller_locations.map { |l| l.absolute_path || l.path }
else
# Remove the line number from backtraces making sure we don't leave anything behind
caller.map { |p| p.sub(/:\d+.*/, '') }
@@ -364,6 +364,10 @@ module Rails
super
end
+ def find_root(from)
+ find_root_with_flag "lib", from
+ end
+
def endpoint(endpoint = nil)
@endpoint ||= nil
@endpoint = endpoint if endpoint
@@ -395,7 +399,7 @@ module Rails
end
unless mod.respond_to?(:railtie_routes_url_helpers)
- define_method(:railtie_routes_url_helpers) { railtie.routes.url_helpers }
+ define_method(:railtie_routes_url_helpers) {|include_path_helpers = true| railtie.routes.url_helpers(include_path_helpers) }
end
end
end
@@ -509,7 +513,7 @@ module Rails
def call(env)
env.merge!(env_config)
if env['SCRIPT_NAME']
- env.merge! "ROUTES_#{routes.object_id}_SCRIPT_NAME" => env['SCRIPT_NAME'].dup
+ env["ROUTES_#{routes.object_id}_SCRIPT_NAME"] = env['SCRIPT_NAME'].dup
end
app.call(env)
end
@@ -531,7 +535,7 @@ module Rails
# Define the configuration object for the engine.
def config
- @config ||= Engine::Configuration.new(find_root_with_flag("lib"))
+ @config ||= Engine::Configuration.new(self.class.find_root(self.class.called_from))
end
# Load data from db/seeds.rb file. It can be used in to load engines'
@@ -567,10 +571,10 @@ module Rails
end
initializer :add_routing_paths do |app|
- paths = self.paths["config/routes.rb"].existent
+ routing_paths = self.paths["config/routes.rb"].existent
- if routes? || paths.any?
- app.routes_reloader.paths.unshift(*paths)
+ if routes? || routing_paths.any?
+ app.routes_reloader.paths.unshift(*routing_paths)
app.routes_reloader.route_sets << routes
end
end
@@ -658,8 +662,7 @@ module Rails
paths["db/migrate"].existent.any?
end
- def find_root_with_flag(flag, default=nil) #:nodoc:
- root_path = self.class.called_from
+ def self.find_root_with_flag(flag, root_path, default=nil) #:nodoc:
while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
parent = File.dirname(root_path)
diff --git a/railties/lib/rails/engine/configuration.rb b/railties/lib/rails/engine/configuration.rb
index 10d1821709..62a4139d07 100644
--- a/railties/lib/rails/engine/configuration.rb
+++ b/railties/lib/rails/engine/configuration.rb
@@ -39,7 +39,7 @@ module Rails
@paths ||= begin
paths = Rails::Paths::Root.new(@root)
- paths.add "app", eager_load: true, glob: "*"
+ paths.add "app", eager_load: true, glob: "{*,*/concerns}"
paths.add "app/assets", glob: "*"
paths.add "app/controllers", eager_load: true
paths.add "app/helpers", eager_load: true
@@ -47,9 +47,6 @@ module Rails
paths.add "app/mailers", eager_load: true
paths.add "app/views"
- paths.add "app/controllers/concerns", eager_load: true
- paths.add "app/models/concerns", eager_load: true
-
paths.add "lib", load_path: true
paths.add "lib/assets", glob: "*"
paths.add "lib/tasks", glob: "**/*.rake"
diff --git a/railties/lib/rails/gem_version.rb b/railties/lib/rails/gem_version.rb
index c7397c4f15..7d74b1bfe5 100644
--- a/railties/lib/rails/gem_version.rb
+++ b/railties/lib/rails/gem_version.rb
@@ -5,8 +5,8 @@ module Rails
end
module VERSION
- MAJOR = 4
- MINOR = 2
+ MAJOR = 5
+ MINOR = 0
TINY = 0
PRE = "alpha"
diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb
index bf2390cb7e..e25c364178 100644
--- a/railties/lib/rails/generators.rb
+++ b/railties/lib/rails/generators.rb
@@ -153,7 +153,7 @@ module Rails
def self.invoke(namespace, args=ARGV, config={})
names = namespace.to_s.split(':')
if klass = find_by_namespace(names.pop, names.any? && names.join(':'))
- args << "--help" if args.empty? && klass.arguments.any? { |a| a.required? }
+ args << "--help" if args.empty? && klass.arguments.any?(&:required?)
klass.start(args, config)
else
options = sorted_groups.map(&:last).flatten
@@ -226,7 +226,7 @@ module Rails
def self.public_namespaces
lookup!
- subclasses.map { |k| k.namespace }
+ subclasses.map(&:namespace)
end
def self.print_generators
diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb
index a239874df0..5373121835 100644
--- a/railties/lib/rails/generators/actions.rb
+++ b/railties/lib/rails/generators/actions.rb
@@ -7,6 +7,7 @@ module Rails
def initialize(*) # :nodoc:
super
@in_group = nil
+ @after_bundle_callbacks = []
end
# Adds an entry into +Gemfile+ for the supplied gem.
@@ -84,10 +85,10 @@ module Rails
# environment(nil, env: "development") do
# "config.autoload_paths += %W(#{config.root}/extras)"
# end
- def environment(data=nil, options={}, &block)
+ def environment(data=nil, options={})
sentinel = /class [a-z_:]+ < Rails::Application/i
env_file_sentinel = /Rails\.application\.configure do/
- data = block.call if !data && block_given?
+ data = yield if !data && block_given?
in_root do
if options[:env].nil?
@@ -188,7 +189,7 @@ module Rails
# generate(:authenticated, "user session")
def generate(what, *args)
log :generate, what
- argument = args.flat_map {|arg| arg.to_s }.join(" ")
+ argument = args.flat_map(&:to_s).join(" ")
in_root { run_ruby_script("bin/rails generate #{what} #{argument}", verbose: false) }
end
@@ -232,6 +233,16 @@ module Rails
log File.read(find_in_source_paths(path))
end
+ # Registers a callback to be executed after bundle and spring binstubs
+ # have run.
+ #
+ # after_bundle do
+ # git add: '.'
+ # end
+ def after_bundle(&block)
+ @after_bundle_callbacks << block
+ end
+
protected
# Define log for backwards compatibility. If just one argument is sent,
@@ -257,11 +268,13 @@ module Rails
# Surround string with single quotes if there is no quotes.
# Otherwise fall back to double quotes
- def quote(str)
- if str.include?("'")
- str.inspect
+ def quote(value)
+ return value.inspect unless value.is_a? String
+
+ if value.include?("'")
+ value.inspect
else
- "'#{str}'"
+ "'#{value}'"
end
end
end
diff --git a/railties/lib/rails/generators/actions/create_migration.rb b/railties/lib/rails/generators/actions/create_migration.rb
index 682092fdf2..cffdef6ec9 100644
--- a/railties/lib/rails/generators/actions/create_migration.rb
+++ b/railties/lib/rails/generators/actions/create_migration.rb
@@ -39,7 +39,7 @@ module Rails
protected
- def on_conflict_behavior(&block)
+ def on_conflict_behavior
options = base.options.merge(config)
if identical?
say_status :identical, :blue, relative_existing_migration
@@ -48,7 +48,7 @@ module Rails
say_status :create, :green
unless pretend?
::FileUtils.rm_rf(existing_migration)
- block.call
+ yield
end
elsif options[:skip]
say_status :skip, :yellow
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
index 7f5a916c5d..71186891a3 100644
--- a/railties/lib/rails/generators/app_base.rb
+++ b/railties/lib/rails/generators/app_base.rb
@@ -38,15 +38,13 @@ module Rails
class_option :skip_keeps, type: :boolean, default: false,
desc: 'Skip source control .keep files'
+ class_option :skip_action_mailer, type: :boolean, aliases: "-M",
+ default: false,
+ desc: "Skip Action Mailer files"
+
class_option :skip_active_record, type: :boolean, aliases: '-O', default: false,
desc: 'Skip Active Record files'
- class_option :skip_gems, type: :array, default: [],
- desc: 'Skip the provided gems files'
-
- class_option :skip_action_view, type: :boolean, aliases: '-V', default: false,
- desc: 'Skip Action View files'
-
class_option :skip_sprockets, type: :boolean, aliases: '-S', default: false,
desc: 'Skip Sprockets files'
@@ -68,6 +66,9 @@ module Rails
class_option :edge, type: :boolean, default: false,
desc: "Setup the #{name} with Gemfile pointing to Rails repository"
+ class_option :skip_turbolinks, type: :boolean, default: false,
+ desc: 'Skip turbolinks gem'
+
class_option :skip_test_unit, type: :boolean, aliases: '-T', default: false,
desc: 'Skip Test::Unit files'
@@ -82,7 +83,7 @@ module Rails
end
def initialize(*args)
- @gem_filter = lambda { |gem| !options[:skip_gems].include?(gem.name) }
+ @gem_filter = lambda { |gem| true }
@extra_entries = []
super
convert_database_option_for_jruby
@@ -113,7 +114,6 @@ module Rails
javascript_gemfile_entry,
jbuilder_gemfile_entry,
sdoc_gemfile_entry,
- spring_gemfile_entry,
psych_gemfile_entry,
@extra_entries].flatten.find_all(&@gem_filter)
end
@@ -168,7 +168,7 @@ module Rails
end
def include_all_railties?
- !options[:skip_active_record] && !options[:skip_action_view] && !options[:skip_test_unit] && !options[:skip_sprockets]
+ options.values_at(:skip_active_record, :skip_action_mailer, :skip_test_unit, :skip_sprockets).none?
end
def comment_if(value)
@@ -184,8 +184,12 @@ module Rails
super
end
- def self.github(name, github, comment = nil)
- new(name, nil, comment, github: github)
+ def self.github(name, github, branch = nil, comment = nil)
+ if branch
+ new(name, nil, comment, github: github, branch: branch)
+ else
+ new(name, nil, comment, github: github)
+ end
end
def self.version(name, version, comment = nil)
@@ -195,23 +199,19 @@ module Rails
def self.path(name, path, comment = nil)
new(name, nil, comment, path: path)
end
-
- def padding(max_width)
- ' ' * (max_width - name.length + 2)
- end
end
def rails_gemfile_entry
if options.dev?
- [GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH),
- GemfileEntry.github('arel', 'rails/arel'),
- GemfileEntry.github('rack', 'rack/rack'),
- GemfileEntry.github('i18n', 'svenfuchs/i18n')]
+ [
+ GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH),
+ GemfileEntry.github('arel', 'rails/arel')
+ ]
elsif options.edge?
- [GemfileEntry.github('rails', 'rails/rails'),
- GemfileEntry.github('arel', 'rails/arel'),
- GemfileEntry.github('rack', 'rack/rack'),
- GemfileEntry.github('i18n', 'svenfuchs/i18n')]
+ [
+ GemfileEntry.github('rails', 'rails/rails'),
+ GemfileEntry.github('arel', 'rails/arel')
+ ]
else
[GemfileEntry.version('rails',
Rails::VERSION::STRING,
@@ -250,16 +250,8 @@ module Rails
return [] if options[:skip_sprockets]
gems = []
- if options.dev? || options.edge?
- gems << GemfileEntry.github('sprockets-rails', 'rails/sprockets-rails',
- 'Use edge version of sprockets-rails')
- gems << GemfileEntry.github('sass-rails', 'rails/sass-rails',
- 'Use SCSS for stylesheets')
- else
- gems << GemfileEntry.version('sass-rails',
- '~> 4.0.3',
+ gems << GemfileEntry.version('sass-rails', '~> 5.0',
'Use SCSS for stylesheets')
- end
gems << GemfileEntry.version('uglifier',
'>= 1.3.0',
@@ -279,11 +271,11 @@ module Rails
end
def coffee_gemfile_entry
- comment = 'Use CoffeeScript for .js.coffee assets and views'
+ comment = 'Use CoffeeScript for .coffee assets and views'
if options.dev? || options.edge?
- GemfileEntry.github 'coffee-rails', 'rails/coffee-rails', comment
+ GemfileEntry.github 'coffee-rails', 'rails/coffee-rails', nil, comment
else
- GemfileEntry.version 'coffee-rails', '~> 4.0.0', comment
+ GemfileEntry.version 'coffee-rails', '~> 4.1.0', comment
end
end
@@ -293,10 +285,13 @@ module Rails
else
gems = [coffee_gemfile_entry, javascript_runtime_gemfile_entry]
gems << GemfileEntry.version("#{options[:javascript]}-rails", nil,
- "Use #{options[:javascript]} as the JavaScript library")
+ "Use #{options[:javascript]} as the JavaScript library")
+
+ unless options[:skip_turbolinks]
+ gems << GemfileEntry.version("turbolinks", nil,
+ "Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks")
+ end
- gems << GemfileEntry.version("turbolinks", nil,
- "Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks")
gems
end
end
@@ -310,12 +305,6 @@ module Rails
end
end
- def spring_gemfile_entry
- return [] unless spring_install?
- comment = 'Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring'
- GemfileEntry.new('spring', nil, comment, group: :development)
- end
-
def psych_gemfile_entry
return [] unless defined?(Rubinius)
@@ -353,7 +342,7 @@ module Rails
end
def spring_install?
- !options[:skip_spring] && Process.respond_to?(:fork)
+ !options[:skip_spring] && Process.respond_to?(:fork) && !RUBY_PLATFORM.include?("cygwin")
end
def run_bundle
diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb
index 9af6435f23..813b8b629e 100644
--- a/railties/lib/rails/generators/base.rb
+++ b/railties/lib/rails/generators/base.rb
@@ -273,7 +273,7 @@ module Rails
# Use Rails default banner.
def self.banner
- "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]".gsub(/\s+/, ' ')
+ "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map(&:usage).join(' ')} [options]".gsub(/\s+/, ' ')
end
# Sets the base_name taking into account the current class namespace.
diff --git a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb
index 66b17bd10e..7d27321610 100644
--- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb
+++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb
@@ -1,8 +1,31 @@
-require 'rails/generators/erb/controller/controller_generator'
+require 'rails/generators/erb'
module Erb # :nodoc:
module Generators # :nodoc:
- class MailerGenerator < ControllerGenerator # :nodoc:
+ class MailerGenerator < Base # :nodoc:
+ argument :actions, type: :array, default: [], banner: "method method"
+
+ def copy_view_files
+ view_base_path = File.join("app/views", class_path, file_name)
+ empty_directory view_base_path
+
+ if self.behavior == :invoke
+ formats.each do |format|
+ layout_path = File.join("app/views/layouts", filename_with_extensions("mailer", format))
+ template filename_with_extensions(:layout, format), layout_path
+ end
+ end
+
+ actions.each do |action|
+ @action = action
+
+ formats.each do |format|
+ @path = File.join(view_base_path, filename_with_extensions(action, format))
+ template filename_with_extensions(:view, format), @path
+ end
+ end
+ end
+
protected
def formats
diff --git a/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb b/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb
new file mode 100644
index 0000000000..93110e74ad
--- /dev/null
+++ b/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb
@@ -0,0 +1,5 @@
+<html>
+ <body>
+ <%%= yield %>
+ </body>
+</html>
diff --git a/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb b/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb
new file mode 100644
index 0000000000..6363733e6e
--- /dev/null
+++ b/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb
@@ -0,0 +1 @@
+<%%= yield %>
diff --git a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
index fa73fef5f7..d9713b0238 100644
--- a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
+++ b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
@@ -17,7 +17,7 @@
<%%= f.label :password %><br>
<%%= f.password_field :password %>
</div>
- <div>
+ <div class="field">
<%%= f.label :password_confirmation %><br>
<%%= f.password_field :password_confirmation %>
<% else -%>
diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb
index c5326d70d1..77a3dbf9a2 100644
--- a/railties/lib/rails/generators/generated_attribute.rb
+++ b/railties/lib/rails/generators/generated_attribute.rb
@@ -44,8 +44,11 @@ module Rails
return $1, limit: $2.to_i
when /decimal\{(\d+)[,.-](\d+)\}/
return :decimal, precision: $1.to_i, scale: $2.to_i
- when /(references|belongs_to)\{polymorphic\}/
- return $1, polymorphic: true
+ when /(references|belongs_to)\{(.+)\}/
+ type = $1
+ provided_options = $2.split(/[,.-]/)
+ options = Hash[provided_options.map { |opt| [opt.to_sym, true] }]
+ return type, options
else
return type, {}
end
@@ -123,7 +126,11 @@ module Rails
end
def polymorphic?
- self.attr_options.has_key?(:polymorphic)
+ self.attr_options[:polymorphic]
+ end
+
+ def required?
+ self.attr_options[:required]
end
def has_index?
@@ -139,12 +146,25 @@ module Rails
end
def inject_options
- "".tap { |s| @attr_options.each { |k,v| s << ", #{k}: #{v.inspect}" } }
+ "".tap { |s| options_for_migration.each { |k,v| s << ", #{k}: #{v.inspect}" } }
end
def inject_index_options
has_uniq_index? ? ", unique: true" : ""
end
+
+ def options_for_migration
+ @attr_options.dup.tap do |options|
+ if required?
+ options.delete(:required)
+ options[:null] = false
+ end
+
+ if reference? && !polymorphic?
+ options[:foreign_key] = true
+ end
+ end
+ end
end
end
end
diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb
index b7da44ca2d..36456e64f5 100644
--- a/railties/lib/rails/generators/named_base.rb
+++ b/railties/lib/rails/generators/named_base.rb
@@ -99,7 +99,7 @@ module Rails
end
def class_name
- (class_path + [file_name]).map!{ |m| m.camelize }.join('::')
+ (class_path + [file_name]).map!(&:camelize).join('::')
end
def human_name
@@ -145,7 +145,7 @@ module Rails
@route_url ||= class_path.collect {|dname| "/" + dname }.join + "/" + plural_file_name
end
- # Tries to retrieve the application name or simple return application.
+ # Tries to retrieve the application name or simply return application.
def application_name
if defined?(Rails) && Rails.application
Rails.application.class.name.split('::').first.underscore
@@ -156,7 +156,7 @@ module Rails
def assign_names!(name) #:nodoc:
@class_path = name.include?('/') ? name.split('/') : name.split('::')
- @class_path.map! { |m| m.underscore }
+ @class_path.map!(&:underscore)
@file_name = @class_path.pop
end
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index 188e62b6c8..0550bf113e 100644
--- a/railties/lib/rails/generators/rails/app/app_generator.rb
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -88,9 +88,14 @@ module Rails
def config_when_updating
cookie_serializer_config_exist = File.exist?('config/initializers/cookies_serializer.rb')
+ callback_terminator_config_exist = File.exist?('config/initializers/callback_terminator.rb')
config
+ unless callback_terminator_config_exist
+ remove_file 'config/initializers/callback_terminator.rb'
+ end
+
unless cookie_serializer_config_exist
gsub_file 'config/initializers/cookies_serializer.rb', /json/, 'marshal'
end
@@ -259,6 +264,10 @@ module Rails
public_task :apply_rails_template, :run_bundle
public_task :generate_spring_binstubs
+ def run_after_bundle_callbacks
+ @after_bundle_callbacks.each(&:call)
+ end
+
protected
def self.banner
@@ -334,7 +343,7 @@ module Rails
#
# This class should be called before the AppGenerator is required and started
# since it configures and mutates ARGV correctly.
- class ARGVScrubber # :nodoc
+ class ARGVScrubber # :nodoc:
def initialize(argv = ARGV)
@argv = argv
end
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index 5bdbd58097..ecaec618dc 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -1,6 +1,5 @@
source 'https://rubygems.org'
-<% max_width = gemfile_entries.map { |g| g.name.length }.max -%>
<% gemfile_entries.each do |gem| -%>
<% if gem.comment -%>
@@ -8,7 +7,7 @@ source 'https://rubygems.org'
<% end -%>
<%= gem.commented_out ? '# ' : '' %>gem '<%= gem.name %>'<%= %(, '#{gem.version}') if gem.version -%>
<% if gem.options.any? -%>
-,<%= gem.padding(max_width) %><%= gem.options.map { |k,v|
+, <%= gem.options.map { |k,v|
"#{k}: #{v.inspect}" }.join(', ') %>
<% end -%>
<% end -%>
@@ -22,16 +21,30 @@ source 'https://rubygems.org'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
-<% unless defined?(JRUBY_VERSION) -%>
-# To use a debugger
+group :development, :test do
+<% if RUBY_ENGINE == 'ruby' -%>
<%- if RUBY_VERSION < '2.0.0' -%>
-# gem 'debugger', group: [:development, :test]
+ # Call 'debugger' anywhere in the code to stop execution and get a debugger console
+ gem 'debugger'
<%- else -%>
-# gem 'byebug', group: [:development, :test]
+ # Call 'byebug' anywhere in the code to stop execution and get a debugger console
+ gem 'byebug'
<%- end -%>
+
+ # Access an IRB console on exception pages or by using <%%= console %> in views
+ <%- if options.dev? || options.edge? -%>
+ gem 'web-console', github: "rails/web-console"
+ <%- else -%>
+ gem 'web-console', '~> 2.0'
+ <%- end -%>
+<%- if spring_install? %>
+ # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
+ gem 'spring'
+<% end -%>
<% end -%>
+end
-<% if RUBY_PLATFORM.match(/bccwin|cygwin|emx|mingw|mswin|wince/) -%>
+<% if RUBY_PLATFORM.match(/bccwin|cygwin|emx|mingw|mswin|wince|java/) -%>
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
-gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw]
+gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
<% end -%>
diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt
index 07ea09cdbd..c1a77944e8 100644
--- a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt
+++ b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt
@@ -2,7 +2,7 @@
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
-// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
+// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css
index a443db3401..f9cd5b3483 100644
--- a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css
+++ b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css
@@ -3,7 +3,7 @@
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
- * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
+ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the bottom of the
* compiled file so the styles you add here take precedence over styles defined in any styles
diff --git a/railties/lib/rails/generators/rails/app/templates/bin/rails b/railties/lib/rails/generators/rails/app/templates/bin/rails
index 6a128b95e5..80ec8080ab 100644
--- a/railties/lib/rails/generators/rails/app/templates/bin/rails
+++ b/railties/lib/rails/generators/rails/app/templates/bin/rails
@@ -1,3 +1,3 @@
-APP_PATH = File.expand_path('../../config/application', __FILE__)
+APP_PATH = File.expand_path('../../config/application', __FILE__)
require_relative '../config/boot'
require 'rails/commands'
diff --git a/railties/lib/rails/generators/rails/app/templates/bin/setup b/railties/lib/rails/generators/rails/app/templates/bin/setup
index 0e22b3fa5c..eee810be30 100644
--- a/railties/lib/rails/generators/rails/app/templates/bin/setup
+++ b/railties/lib/rails/generators/rails/app/templates/bin/setup
@@ -1,28 +1,30 @@
require 'pathname'
+require 'fileutils'
+include FileUtils
# path to your application root.
-APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
+APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
-Dir.chdir APP_ROOT do
+chdir APP_ROOT do
# This script is a starting point to setup your application.
- # Add necessary setup steps to this file:
+ # Add necessary setup steps to this file.
- puts "== Installing dependencies =="
- system "gem install bundler --conservative"
- system "bundle check || bundle install"
+ puts '== Installing dependencies =='
+ system 'gem install bundler --conservative'
+ system('bundle check') or system('bundle install')
# puts "\n== Copying sample files =="
- # unless File.exist?("config/database.yml")
- # system "cp config/database.yml.sample config/database.yml"
+ # unless File.exist?('config/database.yml')
+ # cp 'config/database.yml.sample', 'config/database.yml'
# end
puts "\n== Preparing database =="
- system "bin/rake db:setup"
+ system 'ruby bin/rake db:setup'
puts "\n== Removing old logs and tempfiles =="
- system "rm -f log/*"
- system "rm -rf tmp/cache"
+ rm_f Dir.glob('log/*')
+ rm_rf 'tmp/cache'
puts "\n== Restarting application server =="
- system "touch tmp/restart.txt"
+ touch 'tmp/restart.txt'
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config.ru b/railties/lib/rails/generators/rails/app/templates/config.ru
index 5bc2a619e8..bd83b25412 100644
--- a/railties/lib/rails/generators/rails/app/templates/config.ru
+++ b/railties/lib/rails/generators/rails/app/templates/config.ru
@@ -1,4 +1,4 @@
# This file is used by Rack-based servers to start the application.
-require ::File.expand_path('../config/environment', __FILE__)
+require ::File.expand_path('../config/environment', __FILE__)
run Rails.application
diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb
index 16fe50bab8..dc0cc07888 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/application.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb
@@ -5,10 +5,11 @@ require 'rails/all'
<% else -%>
# Pick the frameworks you want:
require "active_model/railtie"
+require "active_job/railtie"
<%= comment_if :skip_active_record %>require "active_record/railtie"
require "action_controller/railtie"
-require "action_mailer/railtie"
-<%= comment_if :skip_action_view %>require "action_view/railtie"
+<%= comment_if :skip_action_mailer %>require "action_mailer/railtie"
+require "action_view/railtie"
<%= comment_if :skip_sprockets %>require "sprockets/railtie"
<%= comment_if :skip_test_unit %>require "rails/test_unit/railtie"
<% end -%>
@@ -30,5 +31,10 @@ module <%= app_const_base %>
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
+ <%- unless options.skip_active_record? -%>
+
+ # Do not swallow errors in after_commit/after_rollback callbacks.
+ config.active_record.raise_in_transactional_callbacks = true
+ <%- end -%>
end
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml
index 4b2e6646c7..596c916573 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml
@@ -1,6 +1,6 @@
# MySQL. Versions 5.0+ are recommended.
#
-# Install the MYSQL driver
+# Install the MySQL driver
# gem install mysql2
#
# Ensure the MySQL gem is defined in your Gemfile
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
index bbb409616d..ecb5d4170f 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
@@ -12,9 +12,11 @@ Rails.application.configure do
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
+ <%- unless options.skip_action_mailer? -%>
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
+ <%- end -%>
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
@@ -30,7 +32,8 @@ Rails.application.configure do
# number of complex assets.
config.assets.debug = true
- # Generate digests for assets URLs.
+ # Asset digests allow you to set far-future HTTP expiration dates on all assets,
+ # yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
index 5e52f97249..99d7bfb3c9 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
@@ -16,11 +16,13 @@ Rails.application.configure do
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
- # For large-scale production use, consider using a caching reverse proxy like NGINX, varnish or squid.
+ # For large-scale production use, consider using a caching reverse proxy like
+ # NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
- # Disable Rails's static asset server (Apache or NGINX will already do this).
- config.serve_static_assets = false
+ # Disable serving static files from the `/public` folder by default since
+ # Apache or NGINX already handles this.
+ config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
<%- unless options.skip_sprockets? -%>
# Compress JavaScripts and CSS.
@@ -30,21 +32,23 @@ Rails.application.configure do
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
- # Generate digests for assets URLs.
+ # Asset digests allow you to set far-future HTTP expiration dates on all assets,
+ # yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
<%- end -%>
# Specifies the header that your server uses for sending files.
- # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache
+ # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
- # Set to :debug to see everything in the log.
- config.log_level = :info
+ # Use the lowest log level to ensure availability of diagnostic information
+ # when problems arise.
+ config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
@@ -56,11 +60,13 @@ Rails.application.configure do
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
- # config.action_controller.asset_host = "http://assets.example.com"
+ # config.action_controller.asset_host = 'http://assets.example.com'
+ <%- unless options.skip_action_mailer? -%>
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
+ <%- end -%>
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
@@ -69,9 +75,6 @@ Rails.application.configure do
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
- # Disable automatic flushing of the log to improve performance.
- # config.autoflush_log = false
-
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
<%- unless options.skip_active_record? -%>
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
index 053f5b66d7..0306deb18c 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
@@ -12,8 +12,8 @@ Rails.application.configure do
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
- # Configure static asset server for tests with Cache-Control for performance.
- config.serve_static_assets = true
+ # Configure static file server for tests with Cache-Control for performance.
+ config.serve_static_files = true
config.static_cache_control = 'public, max-age=3600'
# Show full error reports and disable caching.
@@ -25,11 +25,16 @@ Rails.application.configure do
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
+ <%- unless options.skip_action_mailer? -%>
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
+ <%- end -%>
+
+ # Randomize the order test cases are executed.
+ config.active_support.test_order = :random
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/assets.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/assets.rb.tt
index d2f4ec33a6..01ef3e6630 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/assets.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/assets.rb.tt
@@ -3,6 +3,9 @@
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
+# Add additional assets to the asset load path
+# Rails.application.config.assets.paths << Emoji.images_path
+
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb
new file mode 100644
index 0000000000..e63022da91
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb
@@ -0,0 +1,4 @@
+# Be sure to restart your server when you modify this file.
+
+# Do not halt callback chains when a callback returns false.
+Rails.application.config.active_support.halt_callback_chains_on_return_false = false
diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore
index 8775e5e235..7c6f2098b8 100644
--- a/railties/lib/rails/generators/rails/app/templates/gitignore
+++ b/railties/lib/rails/generators/rails/app/templates/gitignore
@@ -14,5 +14,6 @@
<% end -%>
# Ignore all logfiles and tempfiles.
-/log/*.log
+/log/*
+!/log/.keep
/tmp
diff --git a/railties/lib/rails/generators/rails/controller/USAGE b/railties/lib/rails/generators/rails/controller/USAGE
index de33900e0a..64239ad599 100644
--- a/railties/lib/rails/generators/rails/controller/USAGE
+++ b/railties/lib/rails/generators/rails/controller/USAGE
@@ -16,4 +16,3 @@ Example:
Test: test/controllers/credit_cards_controller_test.rb
Views: app/views/credit_cards/debit.html.erb [...]
Helper: app/helpers/credit_cards_helper.rb
- Test: test/helpers/credit_cards_helper_test.rb
diff --git a/railties/lib/rails/generators/rails/controller/controller_generator.rb b/railties/lib/rails/generators/rails/controller/controller_generator.rb
index fbecab1823..df615c88b5 100644
--- a/railties/lib/rails/generators/rails/controller/controller_generator.rb
+++ b/railties/lib/rails/generators/rails/controller/controller_generator.rb
@@ -2,7 +2,7 @@ module Rails
module Generators
class ControllerGenerator < NamedBase # :nodoc:
argument :actions, type: :array, default: [], banner: "action action"
- class_option :skip_routes, type: :boolean, desc: "Dont' add routes to config/routes.rb."
+ class_option :skip_routes, type: :boolean, desc: "Don't add routes to config/routes.rb."
check_class_collision suffix: "Controller"
@@ -12,7 +12,7 @@ module Rails
def add_routes
unless options[:skip_routes]
- actions.reverse.each do |action|
+ actions.reverse_each do |action|
route generate_routing_code(action)
end
end
diff --git a/railties/lib/rails/generators/rails/helper/USAGE b/railties/lib/rails/generators/rails/helper/USAGE
index 30e323a858..8855ef3b01 100644
--- a/railties/lib/rails/generators/rails/helper/USAGE
+++ b/railties/lib/rails/generators/rails/helper/USAGE
@@ -5,13 +5,9 @@ Description:
To create a helper within a module, specify the helper name as a
path like 'parent_module/helper_name'.
- This generates a helper class in app/helpers and invokes the configured
- test framework.
-
Example:
`rails generate helper CreditCard`
Credit card helper.
Helper: app/helpers/credit_card_helper.rb
- Test: test/helpers/credit_card_helper_test.rb
diff --git a/railties/lib/rails/generators/rails/model/USAGE b/railties/lib/rails/generators/rails/model/USAGE
index 833b7beb7f..8c3b63c3b4 100644
--- a/railties/lib/rails/generators/rails/model/USAGE
+++ b/railties/lib/rails/generators/rails/model/USAGE
@@ -6,6 +6,11 @@ Description:
model's attributes. Timestamps are added by default, so you don't have to
specify them by hand as 'created_at:datetime updated_at:datetime'.
+ As a special case, specifying 'password:digest' will generate a
+ password_digest field of string type, and configure your generated model and
+ tests for use with ActiveModel has_secure_password (assuming the default ORM
+ and test framework are being used).
+
You don't have to think up every attribute up front, but it helps to
sketch out a few so you can start working with the model immediately.
@@ -27,7 +32,8 @@ Available field types:
`rails generate model post title:string body:text`
will generate a title column with a varchar type and a body column with a text
- type. You can use the following types:
+ type. If no type is specified the string type will be used by default.
+ You can use the following types:
integer
primary_key
@@ -40,7 +46,6 @@ Available field types:
date
time
datetime
- timestamp
You can also consider `references` as a kind of type. For instance, if you run:
@@ -73,6 +78,10 @@ Available field types:
`rails generate model user username:string{30}:uniq`
`rails generate model product supplier:references{polymorphic}:index`
+ If you require a `password_digest` string column for use with
+ has_secure_password, you should specify `password:digest`:
+
+ `rails generate model user password:digest`
Examples:
`rails generate model account`
diff --git a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
index 584f776c01..1c270dd7d4 100644
--- a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
+++ b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
@@ -74,7 +74,8 @@ task default: :test
end
PASSTHROUGH_OPTIONS = [
- :skip_active_record, :skip_javascript, :database, :javascript, :quiet, :pretend, :force, :skip
+ :skip_active_record, :skip_action_mailer, :skip_javascript, :database,
+ :javascript, :quiet, :pretend, :force, :skip
]
def generate_test_dummy(force = false)
diff --git a/railties/lib/rails/generators/rails/plugin/templates/Gemfile b/railties/lib/rails/generators/rails/plugin/templates/Gemfile
index 796587f316..84cef9525e 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/plugin/templates/Gemfile
@@ -31,13 +31,13 @@ end
<% end -%>
<%= gem.commented_out ? '# ' : '' %>gem '<%= gem.name %>'<%= %(, '#{gem.version}') if gem.version -%>
<% if gem.options.any? -%>
-,<%= gem.padding(max_width) %><%= gem.options.map { |k,v|
+, <%= gem.options.map { |k,v|
"#{k}: #{v.inspect}" }.join(', ') %>
<% end -%>
<% end -%>
<% end -%>
-<% unless defined?(JRUBY_VERSION) -%>
+<% if RUBY_ENGINE == 'ruby' -%>
# To use a debugger
<%- if RUBY_VERSION < '2.0.0' -%>
# gem 'debugger', group: [:development, :test]
@@ -45,3 +45,7 @@ end
# gem 'byebug', group: [:development, :test]
<%- end -%>
<% end -%>
+
+<% if RUBY_PLATFORM.match(/bccwin|cygwin|emx|mingw|mswin|wince|java/) -%>
+gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
+<% end -%>
diff --git a/railties/lib/rails/generators/rails/plugin/templates/rails/application.rb b/railties/lib/rails/generators/rails/plugin/templates/rails/application.rb
index 5508829f6b..3a9a7e5437 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/rails/application.rb
+++ b/railties/lib/rails/generators/rails/plugin/templates/rails/application.rb
@@ -6,8 +6,8 @@ require 'rails/all'
# Pick the frameworks you want:
<%= comment_if :skip_active_record %>require "active_record/railtie"
require "action_controller/railtie"
-require "action_mailer/railtie"
-<%= comment_if :skip_action_view %>require "action_view/railtie"
+<%= comment_if :skip_action_mailer %>require "action_mailer/railtie"
+require "action_view/railtie"
<%= comment_if :skip_sprockets %>require "sprockets/railtie"
<%= comment_if :skip_test_unit %>require "rails/test_unit/railtie"
<% end -%>
diff --git a/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js b/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js
index 5bc2e1c8b5..c28e5badc6 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js
+++ b/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js
@@ -2,7 +2,7 @@
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
-// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
+// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
diff --git a/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css b/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css
index a443db3401..f9cd5b3483 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css
+++ b/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css
@@ -3,7 +3,7 @@
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
- * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
+ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the bottom of the
* compiled file so the styles you add here take precedence over styles defined in any styles
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 1e26a313cd..bf3da1fc4d 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
@@ -1,15 +1,23 @@
# Configure Rails Environment
ENV["RAILS_ENV"] = "test"
-require File.expand_path("../dummy/config/environment.rb", __FILE__)
+require File.expand_path("../../<%= options[:dummy_path] -%>/config/environment.rb", __FILE__)
+<% unless options[:skip_active_record] -%>
+ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../<%= options[:dummy_path] -%>/db/migrate", __FILE__)]
+<% if options[:mountable] -%>
+ActiveRecord::Migrator.migrations_paths << File.expand_path('../../db/migrate', __FILE__)
+<% end -%>
+<% end -%>
require "rails/test_help"
-Rails.backtrace_cleaner.remove_silencers!
+# Filter out Minitest backtrace while allowing backtrace from other libraries
+# to be shown.
+Minitest.backtrace_filter = Minitest::BacktraceFilter.new
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
# Load fixtures from the engine
-if ActiveSupport::TestCase.method_defined?(:fixture_path=)
+if ActiveSupport::TestCase.respond_to?(:fixture_path=)
ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__)
end
diff --git a/railties/lib/rails/generators/rails/scaffold/USAGE b/railties/lib/rails/generators/rails/scaffold/USAGE
index 4a3eb2c7c7..1b2a944103 100644
--- a/railties/lib/rails/generators/rails/scaffold/USAGE
+++ b/railties/lib/rails/generators/rails/scaffold/USAGE
@@ -9,11 +9,16 @@ Description:
Attributes are field arguments specifying the model's attributes. You can
optionally pass the type and an index to each field. For instance:
- "title body:text tracking_id:integer:uniq" will generate a title field of
+ 'title body:text tracking_id:integer:uniq' will generate a title field of
string type, a body with text type and a tracking_id as an integer with an
unique index. "index" could also be given instead of "uniq" if one desires
a non unique index.
+ As a special case, specifying 'password:digest' will generate a
+ password_digest field of string type, and configure your generated model,
+ controller, views, and test suite for use with ActiveModel
+ has_secure_password (assuming they are using Rails defaults).
+
Timestamps are added by default, so you don't have to specify them by hand
as 'created_at:datetime updated_at:datetime'.
@@ -33,3 +38,4 @@ Examples:
`rails generate scaffold post`
`rails generate scaffold post title body:text published:boolean`
`rails generate scaffold purchase amount:decimal tracking_id:integer:uniq`
+ `rails generate scaffold user email:uniq password:digest`
diff --git a/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb b/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb
index 6bf0a33a5f..c01b82884d 100644
--- a/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb
+++ b/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb
@@ -7,6 +7,7 @@ module Rails
check_class_collision suffix: "Controller"
+ class_option :helper, type: :boolean
class_option :orm, banner: "NAME", type: :string, required: true,
desc: "ORM to generate the controller for"
diff --git a/railties/lib/rails/generators/resource_helpers.rb b/railties/lib/rails/generators/resource_helpers.rb
index 4669935156..3f84d76ae0 100644
--- a/railties/lib/rails/generators/resource_helpers.rb
+++ b/railties/lib/rails/generators/resource_helpers.rb
@@ -39,7 +39,7 @@ module Rails
def assign_controller_names!(name)
@controller_name = name
@controller_class_path = name.include?('/') ? name.split('/') : name.split('::')
- @controller_class_path.map! { |m| m.underscore }
+ @controller_class_path.map!(&:underscore)
@controller_file_name = @controller_class_path.pop
end
@@ -48,7 +48,7 @@ module Rails
end
def controller_class_name
- (controller_class_path + [controller_file_name]).map!{ |m| m.camelize }.join('::')
+ (controller_class_path + [controller_file_name]).map!(&:camelize).join('::')
end
def controller_i18n_scope
diff --git a/railties/lib/rails/generators/test_unit/helper/helper_generator.rb b/railties/lib/rails/generators/test_unit/helper/helper_generator.rb
index 0db76f9eaf..bde4e88915 100644
--- a/railties/lib/rails/generators/test_unit/helper/helper_generator.rb
+++ b/railties/lib/rails/generators/test_unit/helper/helper_generator.rb
@@ -3,11 +3,7 @@ require 'rails/generators/test_unit'
module TestUnit # :nodoc:
module Generators # :nodoc:
class HelperGenerator < Base # :nodoc:
- check_class_collision suffix: "HelperTest"
-
- def create_helper_files
- template 'helper_test.rb', File.join('test/helpers', class_path, "#{file_name}_helper_test.rb")
- end
+ # Rails does not generate anything here.
end
end
end
diff --git a/railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb b/railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb
deleted file mode 100644
index 7d37bda0f9..0000000000
--- a/railties/lib/rails/generators/test_unit/helper/templates/helper_test.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-require 'test_helper'
-
-<% module_namespacing do -%>
-class <%= class_name %>HelperTest < ActionView::TestCase
-end
-<% end -%>
diff --git a/railties/lib/rails/generators/test_unit/job/job_generator.rb b/railties/lib/rails/generators/test_unit/job/job_generator.rb
new file mode 100644
index 0000000000..566b61ca66
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/job/job_generator.rb
@@ -0,0 +1,13 @@
+require 'rails/generators/test_unit'
+
+module TestUnit # :nodoc:
+ module Generators # :nodoc:
+ class JobGenerator < Base # :nodoc:
+ check_class_collision suffix: 'JobTest'
+
+ def create_test_file
+ template 'unit_test.rb.erb', File.join('test/jobs', class_path, "#{file_name}_job_test.rb")
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/test_unit/job/templates/unit_test.rb.erb b/railties/lib/rails/generators/test_unit/job/templates/unit_test.rb.erb
new file mode 100644
index 0000000000..f5351d0ec6
--- /dev/null
+++ b/railties/lib/rails/generators/test_unit/job/templates/unit_test.rb.erb
@@ -0,0 +1,9 @@
+require 'test_helper'
+
+<% module_namespacing do -%>
+class <%= class_name %>JobTest < ActiveJob::TestCase
+ # test "the truth" do
+ # assert true
+ # end
+end
+<% end -%>
diff --git a/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml
index f19e9d1d87..50ca61a35b 100644
--- a/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml
+++ b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml
@@ -5,6 +5,8 @@
<% attributes.each do |attribute| -%>
<%- if attribute.password_digest? -%>
password_digest: <%%= BCrypt::Password.create('secret') %>
+ <%- elsif attribute.reference? -%>
+ <%= yaml_key_value(attribute.column_name.sub(/_id$/, ''), attribute.default) %>
<%- else -%>
<%= yaml_key_value(attribute.column_name, attribute.default) %>
<%- end -%>
diff --git a/railties/lib/rails/generators/testing/behaviour.rb b/railties/lib/rails/generators/testing/behaviour.rb
index e0600d0b59..fd2ea274e1 100644
--- a/railties/lib/rails/generators/testing/behaviour.rb
+++ b/railties/lib/rails/generators/testing/behaviour.rb
@@ -50,7 +50,7 @@ module Rails
# class AppGeneratorTest < Rails::Generators::TestCase
# tests AppGenerator
# destination File.expand_path("../tmp", File.dirname(__FILE__))
- # teardown :cleanup_destination_root
+ # setup :prepare_destination
#
# test "database.yml is not created when skipping Active Record" do
# run_generator %w(myapp --skip-active-record)
diff --git a/railties/lib/rails/info.rb b/railties/lib/rails/info.rb
index 9502876ebb..5909446b66 100644
--- a/railties/lib/rails/info.rb
+++ b/railties/lib/rails/info.rb
@@ -1,11 +1,14 @@
require "cgi"
module Rails
+ # This module helps build the runtime properties used to display in the
+ # Rails::InfoController responses. Including the active Rails version, Ruby
+ # version, Rack version, and so on.
module Info
mattr_accessor :properties
class << (@@properties = [])
def names
- map {|val| val.first }
+ map(&:first)
end
def value_for(property_name)
@@ -22,19 +25,8 @@ module Rails
rescue Exception
end
- def frameworks
- %w( active_record action_pack action_view action_mailer active_support active_model )
- end
-
- def framework_version(framework)
- if Object.const_defined?(framework.classify)
- require "#{framework}/version"
- framework.classify.constantize.version.to_s
- end
- end
-
def to_s
- column_width = properties.names.map {|name| name.length}.max
+ column_width = properties.names.map(&:length).max
info = properties.map do |name, value|
value = value.join(", ") if value.is_a?(Array)
"%-#{column_width}s %s" % [name, value]
@@ -61,6 +53,11 @@ module Rails
end
end
+ # The Rails version.
+ property 'Rails version' do
+ Rails.version.to_s
+ end
+
# The Ruby version and platform, e.g. "2.0.0-p247 (x86_64-darwin12.4.0)".
property 'Ruby version' do
"#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL} (#{RUBY_PLATFORM})"
@@ -75,23 +72,10 @@ module Rails
::Rack.release
end
- # The Rails version.
- property 'Rails version' do
- Rails.version.to_s
- end
-
property 'JavaScript Runtime' do
ExecJS.runtime.name
end
- # Versions of each Rails framework (Active Record, Action Pack,
- # Action Mailer, and Active Support).
- frameworks.each do |framework|
- property "#{framework.titlecase} version" do
- framework_version(framework)
- end
- end
-
property 'Middleware' do
Rails.configuration.middleware.map(&:inspect)
end
diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb
index 3eb66c07af..5458036219 100644
--- a/railties/lib/rails/paths.rb
+++ b/railties/lib/rails/paths.rb
@@ -77,23 +77,23 @@ module Rails
end
def all_paths
- values.tap { |v| v.uniq! }
+ values.tap(&:uniq!)
end
def autoload_once
- filter_by { |p| p.autoload_once? }
+ filter_by(&:autoload_once?)
end
def eager_load
- filter_by { |p| p.eager_load? }
+ filter_by(&:eager_load?)
end
def autoload_paths
- filter_by { |p| p.autoload? }
+ filter_by(&:autoload?)
end
def load_paths
- filter_by { |p| p.load_path? }
+ filter_by(&:load_path?)
end
private
@@ -167,8 +167,8 @@ module Rails
@paths.concat paths
end
- def unshift(path)
- @paths.unshift path
+ def unshift(*paths)
+ @paths.unshift(*paths)
end
def to_ary
diff --git a/railties/lib/rails/rack/log_tailer.rb b/railties/lib/rails/rack/log_tailer.rb
index bc26421a9e..46517713c9 100644
--- a/railties/lib/rails/rack/log_tailer.rb
+++ b/railties/lib/rails/rack/log_tailer.rb
@@ -4,7 +4,7 @@ module Rails
module Rack
class LogTailer
def initialize(app, log = nil)
- ActiveSupport::Deprecation.warn "LogTailer is deprecated and will be removed on Rails 5"
+ ActiveSupport::Deprecation.warn('LogTailer is deprecated and will be removed on Rails 5.')
@app = app
diff --git a/railties/lib/rails/ruby_version_check.rb b/railties/lib/rails/ruby_version_check.rb
index df74643a59..aea3d2339c 100644
--- a/railties/lib/rails/ruby_version_check.rb
+++ b/railties/lib/rails/ruby_version_check.rb
@@ -1,13 +1,13 @@
-if RUBY_VERSION < '1.9.3'
+if RUBY_VERSION < '2.2.0'
desc = defined?(RUBY_DESCRIPTION) ? RUBY_DESCRIPTION : "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})"
abort <<-end_message
- Rails 4 prefers to run on Ruby 2.1 or newer.
+ Rails 5 requires to run on Ruby 2.2.0 or newer.
You're running
#{desc}
- Please upgrade to Ruby 1.9.3 or newer to continue.
+ Please upgrade to Ruby 2.2.0 or newer to continue.
end_message
end
diff --git a/railties/lib/rails/rubyprof_ext.rb b/railties/lib/rails/rubyprof_ext.rb
deleted file mode 100644
index 017eba3a76..0000000000
--- a/railties/lib/rails/rubyprof_ext.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-require 'prof'
-
-module Prof #:nodoc:
- # Adapted from Shugo Maeda's unprof.rb
- def self.print_profile(results, io = $stderr)
- total = results.detect { |i|
- i.method_class.nil? && i.method_id == :"#toplevel"
- }.total_time
- total = 0.001 if total < 0.001
-
- io.puts " %% cumulative self self total"
- io.puts " time seconds seconds calls ms/call ms/call name"
-
- sum = 0.0
- results.each do |r|
- sum += r.self_time
-
- name = if r.method_class.nil?
- r.method_id.to_s
- elsif r.method_class.is_a?(Class)
- "#{r.method_class}##{r.method_id}"
- else
- "#{r.method_class}.#{r.method_id}"
- end
- io.printf "%6.2f %8.3f %8.3f %8d %8.2f %8.2f %s\n",
- r.self_time / total * 100,
- sum,
- r.self_time,
- r.count,
- r.self_time * 1000 / r.count,
- r.total_time * 1000 / r.count,
- name
- end
- end
-end
diff --git a/railties/lib/rails/source_annotation_extractor.rb b/railties/lib/rails/source_annotation_extractor.rb
index 201532d299..9b058a1848 100644
--- a/railties/lib/rails/source_annotation_extractor.rb
+++ b/railties/lib/rails/source_annotation_extractor.rb
@@ -80,9 +80,8 @@ class SourceAnnotationExtractor
# Returns a hash that maps filenames under +dir+ (recursively) to arrays
# with their annotations. Only files with annotations are included. Files
- # with extension +.builder+, +.rb+, +.erb+, +.haml+, +.slim+, +.css+,
- # +.scss+, +.js+, +.coffee+, +.rake+, +.sass+ and +.less+
- # are taken into account.
+ # with extension +.builder+, +.rb+, +.rake+, +.yml+, +.yaml+, +.ruby+,
+ # +.css+, +.js+ and +.erb+ are taken into account.
def find_in(dir)
results = {}
diff --git a/railties/lib/rails/tasks.rb b/railties/lib/rails/tasks.rb
index af5f2707b1..2f82d1285d 100644
--- a/railties/lib/rails/tasks.rb
+++ b/railties/lib/rails/tasks.rb
@@ -1,3 +1,5 @@
+require 'rake'
+
# Load Rails Rakefile extensions
%w(
annotations
diff --git a/railties/lib/rails/tasks/statistics.rake b/railties/lib/rails/tasks/statistics.rake
index ae5a7d2759..ba6168e208 100644
--- a/railties/lib/rails/tasks/statistics.rake
+++ b/railties/lib/rails/tasks/statistics.rake
@@ -1,9 +1,10 @@
-# while having global constant is not good,
-# many 3rd party tools depend on it, like rspec-rails, cucumber-rails, etc
-# so if will be removed - deprecation warning is needed
+# While global constants are bad, many 3rd party tools depend on this one (e.g
+# rspec-rails & cucumber-rails). So a deprecation warning is needed if we want
+# to remove it.
STATS_DIRECTORIES = [
%w(Controllers app/controllers),
%w(Helpers app/helpers),
+ %w(Jobs app/jobs),
%w(Models app/models),
%w(Mailers app/mailers),
%w(Javascripts app/assets/javascripts),
@@ -13,10 +14,11 @@ STATS_DIRECTORIES = [
%w(Helper\ tests test/helpers),
%w(Model\ tests test/models),
%w(Mailer\ tests test/mailers),
+ %w(Job\ tests test/jobs),
%w(Integration\ tests test/integration),
%w(Functional\ tests\ (old) test/functional),
%w(Unit\ tests \ (old) test/unit)
-].collect do |name, dir|
+].collect do |name, dir|
[ name, "#{File.dirname(Rake.application.rakefile_location)}/#{dir}" ]
end.select { |name, dir| File.directory?(dir) }
@@ -24,4 +26,4 @@ desc "Report code statistics (KLOCs, etc) from the application or engine"
task :stats do
require 'rails/code_statistics'
CodeStatistics.new(*STATS_DIRECTORIES).to_s
-end \ No newline at end of file
+end
diff --git a/railties/lib/rails/tasks/tmp.rake b/railties/lib/rails/tasks/tmp.rake
index 116988665f..b33ae9862b 100644
--- a/railties/lib/rails/tasks/tmp.rake
+++ b/railties/lib/rails/tasks/tmp.rake
@@ -1,9 +1,8 @@
namespace :tmp do
- desc "Clear session, cache, and socket files from tmp/ (narrow w/ tmp:sessions:clear, tmp:cache:clear, tmp:sockets:clear)"
- task clear: [ "tmp:sessions:clear", "tmp:cache:clear", "tmp:sockets:clear"]
+ desc "Clear cache and socket files from tmp/ (narrow w/ tmp:cache:clear, tmp:sockets:clear)"
+ task clear: ["tmp:cache:clear", "tmp:sockets:clear"]
- tmp_dirs = [ 'tmp/sessions',
- 'tmp/cache',
+ tmp_dirs = [ 'tmp/cache',
'tmp/sockets',
'tmp/pids',
'tmp/cache/assets/development',
@@ -15,13 +14,6 @@ namespace :tmp do
desc "Creates tmp directories for sessions, cache, sockets, and pids"
task create: tmp_dirs
- namespace :sessions do
- # desc "Clears all files in tmp/sessions"
- task :clear do
- FileUtils.rm(Dir['tmp/sessions/[^.]*'])
- end
- end
-
namespace :cache do
# desc "Clears all files and directories in tmp/cache"
task :clear do
diff --git a/railties/lib/rails/templates/rails/mailers/email.html.erb b/railties/lib/rails/templates/rails/mailers/email.html.erb
index 977feb922b..0b08a01896 100644
--- a/railties/lib/rails/templates/rails/mailers/email.html.erb
+++ b/railties/lib/rails/templates/rails/mailers/email.html.erb
@@ -2,6 +2,14 @@
<html><head>
<meta name="viewport" content="width=device-width" />
<style type="text/css">
+ html, body, iframe {
+ height: 100%;
+ }
+
+ body {
+ margin: 0;
+ }
+
header {
width: 100%;
padding: 10px 0 0 0;
@@ -34,7 +42,6 @@
iframe {
border: 0;
width: 100%;
- height: 800px;
}
</style>
</head>
@@ -95,4 +102,4 @@
<iframe seamless name="messageBody" src="?part=<%= Rack::Utils.escape(@part.mime_type) %>"></iframe>
</body>
-</html> \ No newline at end of file
+</html>
diff --git a/railties/lib/rails/templates/rails/welcome/index.html.erb b/railties/lib/rails/templates/rails/welcome/index.html.erb
index eb620caa00..6726c23fc9 100644
--- a/railties/lib/rails/templates/rails/welcome/index.html.erb
+++ b/railties/lib/rails/templates/rails/welcome/index.html.erb
@@ -19,13 +19,13 @@
}
a {color: #03c}
+
a:hover {
background-color: #03c;
color: white;
text-decoration: none;
}
-
#page {
background-color: #f0f0f0;
width: 750px;
@@ -57,21 +57,21 @@
padding-right: 30px;
}
-
#header {
background-image: url(data:image/png;base64,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);
background-repeat: no-repeat;
background-position: top left;
height: 64px;
}
+
#header h1, #header h2 {margin: 0}
+
#header h2 {
color: #888;
font-weight: normal;
font-size: 16px;
}
-
#about h3 {
margin: 0;
margin-bottom: 10px;
@@ -84,18 +84,26 @@
margin-left: -55px;
margin-right: -10px;
}
+
#about-content table {
margin-top: 10px;
margin-bottom: 10px;
font-size: 11px;
border-collapse: collapse;
}
+
#about-content td {
padding: 10px;
padding-top: 3px;
padding-bottom: 3px;
}
- #about-content td.name {color: #555}
+
+ #about-content td.name {
+ font-weight: bold;
+ vertical-align: top;
+ color: #555;
+ }
+
#about-content td.value {color: #000}
#about-content ul {
@@ -107,21 +115,23 @@
background-color: #fcc;
border: 1px solid #f00;
}
+
#about-content.failure p {
margin: 0;
padding: 10px;
}
-
#getting-started {
border-top: 1px solid #ccc;
margin-top: 25px;
padding-top: 15px;
}
+
#getting-started h1 {
margin: 0;
font-size: 20px;
}
+
#getting-started h2 {
margin: 0;
font-size: 14px;
@@ -129,40 +139,46 @@
color: #333;
margin-bottom: 25px;
}
+
#getting-started ol {
margin-left: 0;
padding-left: 0;
}
+
#getting-started li {
font-size: 18px;
color: #888;
margin-bottom: 25px;
}
+
#getting-started li h2 {
margin: 0;
font-weight: normal;
font-size: 18px;
color: #333;
}
+
#getting-started li p {
color: #555;
font-size: 13px;
}
-
#sidebar ul {
margin-left: 0;
padding-left: 0;
}
+
#sidebar ul h3 {
margin-top: 25px;
font-size: 16px;
padding-bottom: 10px;
border-bottom: 1px solid #ccc;
}
+
#sidebar li {
list-style-type: none;
}
+
#sidebar ul.links li {
margin-bottom: 5px;
}
@@ -221,7 +237,7 @@
<ol>
<li>
- <h2>Use <code>rails generate</code> to create your models and controllers</h2>
+ <h2>Use <code>bin/rails generate</code> to create your models and controllers</h2>
<p>To see all available options, run it without parameters.</p>
</li>
diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake
index 285e2ce846..254ea9ecf6 100644
--- a/railties/lib/rails/test_unit/testing.rake
+++ b/railties/lib/rails/test_unit/testing.rake
@@ -3,32 +3,50 @@ require 'rails/test_unit/sub_test_task'
task default: :test
-desc 'Runs test:units, test:functionals, test:generators, test:integration together'
+desc "Runs all tests in test folder"
task :test do
Rails::TestTask.test_creator(Rake.application.top_level_tasks).invoke_rake_task
end
namespace :test do
task :prepare do
- # Placeholder task for other Railtie and plugins to enhance. See Active Record for an example.
+ # Placeholder task for other Railtie and plugins to enhance.
+ # If used with Active Record, this task runs before the database schema is synchronized.
end
- task :run => ['test:units', 'test:functionals', 'test:generators', 'test:integration']
+ Rails::TestTask.new(:run) do |t|
+ t.pattern = "test/**/*_test.rb"
+ end
+
+ desc "Run tests quickly, but also reset db"
+ task :db => %w[db:test:prepare test]
- # Inspired by: http://ngauthier.com/2012/02/quick-tests-with-bash.html
desc "Run tests quickly by merging all types and not resetting db"
Rails::TestTask.new(:all) do |t|
t.pattern = "test/**/*_test.rb"
end
+ Rake::Task["test:all"].enhance do
+ Rake::Task["test:deprecate_all"].invoke
+ end
+
+ task :deprecate_all do
+ ActiveSupport::Deprecation.warn "rake test:all is deprecated and will be removed in Rails 5. " \
+ "Use rake test to run all tests in test directory."
+ end
+
namespace :all do
desc "Run tests quickly, but also reset db"
task :db => %w[db:test:prepare test:all]
+
+ Rake::Task["test:all:db"].enhance do
+ Rake::Task["test:deprecate_all"].invoke
+ end
end
Rails::TestTask.new(single: "test:prepare")
- ["models", "helpers", "controllers", "mailers", "integration"].each do |name|
+ ["models", "helpers", "controllers", "mailers", "integration", "jobs"].each do |name|
Rails::TestTask.new(name => "test:prepare") do |t|
t.pattern = "test/#{name}/**/*_test.rb"
end
diff --git a/railties/railties.gemspec b/railties/railties.gemspec
index 56b8736800..7a1c897e3d 100644
--- a/railties/railties.gemspec
+++ b/railties/railties.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Tools for creating, working with, and running Rails applications.'
s.description = 'Rails internals: application bootup, plugins, generators, and rake tasks.'
- s.required_ruby_version = '>= 1.9.3'
+ s.required_ruby_version = '>= 2.2.0'
s.license = 'MIT'
diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb
index b6533a5fb2..0749615d03 100644
--- a/railties/test/abstract_unit.rb
+++ b/railties/test/abstract_unit.rb
@@ -28,24 +28,26 @@ def jruby_skip(message = '')
end
class ActiveSupport::TestCase
+ # FIXME: we have tests that depend on run order, we should fix that and
+ # remove this method call.
+ self.test_order = :sorted
+
private
- unless defined?(:capture)
- def capture(stream)
- stream = stream.to_s
- captured_stream = Tempfile.new(stream)
- stream_io = eval("$#{stream}")
- origin_stream = stream_io.dup
- stream_io.reopen(captured_stream)
-
- yield
-
- stream_io.rewind
- return captured_stream.read
- ensure
- captured_stream.close
- captured_stream.unlink
- stream_io.reopen(origin_stream)
- end
+ def capture(stream)
+ stream = stream.to_s
+ captured_stream = Tempfile.new(stream)
+ stream_io = eval("$#{stream}")
+ origin_stream = stream_io.dup
+ stream_io.reopen(captured_stream)
+
+ yield
+
+ stream_io.rewind
+ return captured_stream.read
+ ensure
+ captured_stream.close
+ captured_stream.unlink
+ stream_io.reopen(origin_stream)
end
end
diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb
index 8f091cfdbf..d58a27403e 100644
--- a/railties/test/application/assets_test.rb
+++ b/railties/test/application/assets_test.rb
@@ -225,7 +225,7 @@ module ApplicationTests
test "assets do not require any assets group gem when manifest file is present" do
app_file "app/assets/javascripts/application.js", "alert();"
- add_to_env_config "production", "config.serve_static_assets = true"
+ add_to_env_config "production", "config.serve_static_files = true"
ENV["RAILS_ENV"] = "production"
precompile!
diff --git a/railties/test/application/configuration/base_test.rb b/railties/test/application/configuration/base_test.rb
new file mode 100644
index 0000000000..d6a82b139d
--- /dev/null
+++ b/railties/test/application/configuration/base_test.rb
@@ -0,0 +1,37 @@
+require 'isolation/abstract_unit'
+require 'rack/test'
+require 'env_helpers'
+
+module ApplicationTests
+ module ConfigurationTests
+ class BaseTest < ActiveSupport::TestCase
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf("#{app_path}/config/environments")
+ end
+
+ def teardown
+ teardown_app
+ FileUtils.rm_rf(new_app) if File.directory?(new_app)
+ end
+
+ private
+ def new_app
+ File.expand_path("#{app_path}/../new_app")
+ end
+
+ def copy_app
+ FileUtils.cp_r(app_path, new_app)
+ end
+
+ def app
+ @app ||= Rails.application
+ end
+
+ def require_environment
+ require "#{app_path}/config/environment"
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/railties/test/application/configuration/custom_test.rb b/railties/test/application/configuration/custom_test.rb
new file mode 100644
index 0000000000..f8d22f6d97
--- /dev/null
+++ b/railties/test/application/configuration/custom_test.rb
@@ -0,0 +1,22 @@
+require 'application/configuration/base_test'
+
+class ApplicationTests::ConfigurationTests::CustomTest < ApplicationTests::ConfigurationTests::BaseTest
+ test 'access custom configuration point' do
+ add_to_config <<-RUBY
+ config.x.payment_processing.schedule = :daily
+ config.x.payment_processing.retries = 3
+ config.x.super_debugger = true
+ config.x.hyper_debugger = false
+ config.x.nil_debugger = nil
+ RUBY
+ require_environment
+
+ x = Rails.configuration.x
+ assert_equal :daily, x.payment_processing.schedule
+ assert_equal 3, x.payment_processing.retries
+ assert_equal true, x.super_debugger
+ assert_equal false, x.hyper_debugger
+ assert_equal nil, x.nil_debugger
+ assert_nil x.i_do_not_exist.zomg
+ end
+end
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index 21244188dd..ad15e30b6a 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -41,7 +41,7 @@ module ApplicationTests
def setup
build_app
boot_rails
- FileUtils.rm_rf("#{app_path}/config/environments")
+ supress_default_config
end
def teardown
@@ -49,6 +49,15 @@ module ApplicationTests
FileUtils.rm_rf(new_app) if File.directory?(new_app)
end
+ def supress_default_config
+ FileUtils.mv("#{app_path}/config/environments", "#{app_path}/config/__environments__")
+ end
+
+ def restore_default_config
+ FileUtils.rm_rf("#{app_path}/config/environments")
+ FileUtils.mv("#{app_path}/config/__environments__", "#{app_path}/config/environments")
+ end
+
test "Rails.env does not set the RAILS_ENV environment variable which would leak out into rake tasks" do
require "rails"
@@ -59,6 +68,20 @@ module ApplicationTests
end
end
+ test "lib dir is on LOAD_PATH during config" do
+ app_file 'lib/my_logger.rb', <<-RUBY
+ require "logger"
+ class MyLogger < ::Logger
+ end
+ RUBY
+ add_to_top_of_config <<-RUBY
+ require 'my_logger'
+ config.logger = MyLogger.new STDOUT
+ RUBY
+ require "#{app_path}/config/environment"
+ assert_equal 'MyLogger', Rails.application.config.logger.class.name
+ end
+
test "a renders exception on pending migration" do
add_to_config <<-RUBY
config.active_record.migration_error = :page_load
@@ -118,7 +141,7 @@ module ApplicationTests
test "Rails::Application responds to paths" do
require "#{app_path}/config/environment"
assert_respond_to AppTemplate::Application, :paths
- assert_equal AppTemplate::Application.paths["app/views"].expanded, ["#{app_path}/app/views"]
+ assert_equal ["#{app_path}/app/views"], AppTemplate::Application.paths["app/views"].expanded
end
test "the application root is set correctly" do
@@ -182,7 +205,7 @@ module ApplicationTests
test "application is always added to eager_load namespaces" do
require "#{app_path}/config/application"
- assert Rails.application, Rails.application.config.eager_load_namespaces
+ assert_includes Rails.application.config.eager_load_namespaces, AppTemplate::Application
end
test "the application can be eager loaded even when there are no frameworks" do
@@ -266,10 +289,57 @@ module ApplicationTests
assert_equal Pathname.new(app_path).join("somewhere"), Rails.public_path
end
+ test "In production mode, config.serve_static_files is off by default" do
+ restore_default_config
+
+ with_rails_env "production" do
+ require "#{app_path}/config/environment"
+ assert_not app.config.serve_static_files
+ end
+ end
+
+ test "In production mode, config.serve_static_files is enabled when RAILS_SERVE_STATIC_FILES is set" do
+ restore_default_config
+
+ with_rails_env "production" do
+ switch_env "RAILS_SERVE_STATIC_FILES", "1" do
+ require "#{app_path}/config/environment"
+ assert app.config.serve_static_files
+ end
+ end
+ end
+
+ test "In production mode, config.serve_static_files is disabled when RAILS_SERVE_STATIC_FILES is blank" do
+ restore_default_config
+
+ with_rails_env "production" do
+ switch_env "RAILS_SERVE_STATIC_FILES", " " do
+ require "#{app_path}/config/environment"
+ assert_not app.config.serve_static_files
+ end
+ end
+ end
+
+ test "config.serve_static_assets is deprecated" do
+ require "#{app_path}/config/application"
+
+ assert_deprecated(/serve_static_assets/) do
+ app.config.serve_static_assets = false
+ end
+
+ assert_not app.config.serve_static_files
+ assert_deprecated(/serve_static_assets/) { assert_not app.config.serve_static_assets }
+
+ app.config.serve_static_files = true
+
+ assert app.config.serve_static_files
+ assert_deprecated(/serve_static_assets/) { assert app.config.serve_static_assets }
+ end
+
test "Use key_generator when secret_key_base is set" do
- make_basic_app do |app|
- app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
- app.config.session_store :disabled
+ make_basic_app do |application|
+ application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
+ application.config.session_store :disabled
end
class ::OmgController < ActionController::Base
@@ -287,9 +357,9 @@ module ApplicationTests
end
test "application verifier can be used in the entire application" do
- make_basic_app do |app|
- app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
- app.config.session_store :disabled
+ make_basic_app do |application|
+ application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
+ application.config.session_store :disabled
end
message = app.message_verifier(:sensitive_value).generate("some_value")
@@ -301,10 +371,55 @@ module ApplicationTests
assert_equal 'some_value', verifier.verify(message)
end
+ test "application message verifier can be used when the key_generator is ActiveSupport::LegacyKeyGenerator" do
+ app_file 'config/initializers/secret_token.rb', <<-RUBY
+ Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33"
+ RUBY
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_key_base:
+ YAML
+ require "#{app_path}/config/environment"
+
+
+ assert_equal app.env_config['action_dispatch.key_generator'], Rails.application.key_generator
+ assert_equal app.env_config['action_dispatch.key_generator'].class, ActiveSupport::LegacyKeyGenerator
+ message = app.message_verifier(:sensitive_value).generate("some_value")
+ assert_equal 'some_value', Rails.application.message_verifier(:sensitive_value).verify(message)
+ end
+
+ test "warns when secrets.secret_key_base is blank and config.secret_token is set" do
+ app_file 'config/initializers/secret_token.rb', <<-RUBY
+ Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33"
+ RUBY
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_key_base:
+ YAML
+ require "#{app_path}/config/environment"
+
+ assert_deprecated(/You didn't set `secret_key_base`./) do
+ app.env_config
+ end
+ end
+
+ test "prefer secrets.secret_token over config.secret_token" do
+ app_file 'config/initializers/secret_token.rb', <<-RUBY
+ Rails.application.config.secret_token = ""
+ RUBY
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_token: 3b7cd727ee24e8444053437c36cc66c3
+ YAML
+ require "#{app_path}/config/environment"
+
+ assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token
+ end
+
test "application verifier can build different verifiers" do
- make_basic_app do |app|
- app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
- app.config.session_store :disabled
+ make_basic_app do |application|
+ application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
+ application.config.session_store :disabled
end
default_verifier = app.message_verifier(:sensitive_value)
@@ -341,6 +456,21 @@ module ApplicationTests
assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_key_base
end
+ test "config.secret_token over-writes a blank secrets.secret_token" do
+ app_file 'config/initializers/secret_token.rb', <<-RUBY
+ Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33"
+ RUBY
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_key_base:
+ secret_token:
+ YAML
+ require "#{app_path}/config/environment"
+
+ assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.secrets.secret_token
+ assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token
+ end
+
test "custom secrets saved in config/secrets.yml are loaded in app secrets" do
app_file 'config/secrets.yml', <<-YAML
development:
@@ -362,6 +492,51 @@ module ApplicationTests
assert_nil app.secrets.not_defined
end
+ test "config.secret_key_base over-writes a blank secrets.secret_key_base" do
+ app_file 'config/initializers/secret_token.rb', <<-RUBY
+ Rails.application.config.secret_key_base = "iaminallyoursecretkeybase"
+ RUBY
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_key_base:
+ YAML
+ require "#{app_path}/config/environment"
+
+ assert_equal "iaminallyoursecretkeybase", app.secrets.secret_key_base
+ end
+
+ test "uses ActiveSupport::LegacyKeyGenerator as app.key_generator when secrets.secret_key_base is blank" do
+ app_file 'config/initializers/secret_token.rb', <<-RUBY
+ Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33"
+ RUBY
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_key_base:
+ YAML
+ require "#{app_path}/config/environment"
+
+ assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token
+ assert_equal nil, app.secrets.secret_key_base
+ assert_equal app.key_generator.class, ActiveSupport::LegacyKeyGenerator
+ end
+
+ test "uses ActiveSupport::LegacyKeyGenerator with config.secret_token as app.key_generator when secrets.secret_key_base is blank" do
+ app_file 'config/initializers/secret_token.rb', <<-RUBY
+ Rails.application.config.secret_token = ""
+ RUBY
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_key_base:
+ YAML
+ require "#{app_path}/config/environment"
+
+ assert_equal '', app.config.secret_token
+ assert_equal nil, app.secrets.secret_key_base
+ assert_raise ArgumentError, /\AA secret is required/ do
+ app.key_generator
+ end
+ end
+
test "protect from forgery is the default in a new app" do
make_basic_app
@@ -375,6 +550,45 @@ module ApplicationTests
assert last_response.body =~ /csrf\-param/
end
+ test "default form builder specified as a string" do
+
+ app_file 'config/initializers/form_builder.rb', <<-RUBY
+ class CustomFormBuilder < ActionView::Helpers::FormBuilder
+ def text_field(attribute, *args)
+ label(attribute) + super(attribute, *args)
+ end
+ end
+ Rails.configuration.action_view.default_form_builder = "CustomFormBuilder"
+ RUBY
+
+ app_file 'app/models/post.rb', <<-RUBY
+ class Post
+ include ActiveModel::Model
+ attr_accessor :name
+ end
+ RUBY
+
+
+ app_file 'app/controllers/posts_controller.rb', <<-RUBY
+ class PostsController < ApplicationController
+ def index
+ render inline: "<%= begin; form_for(Post.new) {|f| f.text_field(:name)}; rescue => e; e.to_s; end %>"
+ end
+ end
+ RUBY
+
+ add_to_config <<-RUBY
+ routes.prepend do
+ resources :posts
+ end
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ get "/posts"
+ assert_match(/label/, last_response.body)
+ end
+
test "default method for update can be changed" do
app_file 'app/models/post.rb', <<-RUBY
class Post
@@ -429,8 +643,8 @@ module ApplicationTests
end
test "request forgery token param can be changed" do
- make_basic_app do
- app.config.action_controller.request_forgery_protection_token = '_xsrf_token_here'
+ make_basic_app do |application|
+ application.config.action_controller.request_forgery_protection_token = '_xsrf_token_here'
end
class ::OmgController < ActionController::Base
@@ -440,7 +654,7 @@ module ApplicationTests
end
get "/"
- assert last_response.body =~ /_xsrf_token_here/
+ assert_match "_xsrf_token_here", last_response.body
end
test "sets ActionDispatch.test_app" do
@@ -449,8 +663,8 @@ module ApplicationTests
end
test "sets ActionDispatch::Response.default_charset" do
- make_basic_app do |app|
- app.config.action_dispatch.default_charset = "utf-16"
+ make_basic_app do |application|
+ application.config.action_dispatch.default_charset = "utf-16"
end
assert_equal "utf-16", ActionDispatch::Response.default_charset
@@ -631,8 +845,8 @@ module ApplicationTests
end
test "config.action_dispatch.show_exceptions is sent in env" do
- make_basic_app do |app|
- app.config.action_dispatch.show_exceptions = true
+ make_basic_app do |application|
+ application.config.action_dispatch.show_exceptions = true
end
class ::OmgController < ActionController::Base
@@ -793,8 +1007,8 @@ module ApplicationTests
end
test "config.action_dispatch.ignore_accept_header" do
- make_basic_app do |app|
- app.config.action_dispatch.ignore_accept_header = true
+ make_basic_app do |application|
+ application.config.action_dispatch.ignore_accept_header = true
end
class ::OmgController < ActionController::Base
@@ -831,9 +1045,9 @@ module ApplicationTests
test "config.session_store with :active_record_store with activerecord-session_store gem" do
begin
- make_basic_app do |app|
+ make_basic_app do |application|
ActionDispatch::Session::ActiveRecordStore = Class.new(ActionDispatch::Session::CookieStore)
- app.config.session_store :active_record_store
+ application.config.session_store :active_record_store
end
ensure
ActionDispatch::Session.send :remove_const, :ActiveRecordStore
@@ -842,16 +1056,46 @@ module ApplicationTests
test "config.session_store with :active_record_store without activerecord-session_store gem" do
assert_raise RuntimeError, /activerecord-session_store/ do
- make_basic_app do |app|
- app.config.session_store :active_record_store
+ make_basic_app do |application|
+ application.config.session_store :active_record_store
+ end
+ end
+ end
+
+ test "Blank config.log_level is not deprecated for non-production environment" do
+ with_rails_env "development" do
+ assert_not_deprecated do
+ make_basic_app do |application|
+ application.config.log_level = nil
+ end
+ end
+ end
+ end
+
+ test "Blank config.log_level is deprecated for the production environment" do
+ with_rails_env "production" do
+ assert_deprecated(/log_level/) do
+ make_basic_app do |application|
+ application.config.log_level = nil
+ end
+ end
+ end
+ end
+
+ test "Not blank config.log_level is not deprecated for the production environment" do
+ with_rails_env "production" do
+ assert_not_deprecated do
+ make_basic_app do |application|
+ application.config.log_level = :info
+ end
end
end
end
test "config.log_level with custom logger" do
- make_basic_app do |app|
- app.config.logger = Logger.new(STDOUT)
- app.config.log_level = :info
+ make_basic_app do |application|
+ application.config.logger = Logger.new(STDOUT)
+ application.config.log_level = :info
end
assert_equal Logger::INFO, Rails.logger.level
end
@@ -881,8 +1125,8 @@ module ApplicationTests
end
test "config.annotations wrapping SourceAnnotationExtractor::Annotation class" do
- make_basic_app do |app|
- app.config.annotations.register_extensions("coffee") do |tag|
+ make_basic_app do |application|
+ application.config.annotations.register_extensions("coffee") do |tag|
/#\s*(#{tag}):?\s*(.*)$/
end
end
@@ -891,95 +1135,102 @@ module ApplicationTests
end
test "rake_tasks block works at instance level" do
- $ran_block = false
-
app_file "config/environments/development.rb", <<-RUBY
Rails.application.configure do
+ config.ran_block = false
+
rake_tasks do
- $ran_block = true
+ config.ran_block = true
end
end
RUBY
require "#{app_path}/config/environment"
+ assert_not Rails.configuration.ran_block
- assert !$ran_block
require 'rake'
require 'rake/testtask'
require 'rdoc/task'
Rails.application.load_tasks
- assert $ran_block
+ assert Rails.configuration.ran_block
end
test "generators block works at instance level" do
- $ran_block = false
-
app_file "config/environments/development.rb", <<-RUBY
Rails.application.configure do
+ config.ran_block = false
+
generators do
- $ran_block = true
+ config.ran_block = true
end
end
RUBY
require "#{app_path}/config/environment"
+ assert_not Rails.configuration.ran_block
- assert !$ran_block
Rails.application.load_generators
- assert $ran_block
+ assert Rails.configuration.ran_block
end
test "console block works at instance level" do
- $ran_block = false
-
app_file "config/environments/development.rb", <<-RUBY
Rails.application.configure do
+ config.ran_block = false
+
console do
- $ran_block = true
+ config.ran_block = true
end
end
RUBY
require "#{app_path}/config/environment"
+ assert_not Rails.configuration.ran_block
- assert !$ran_block
Rails.application.load_console
- assert $ran_block
+ assert Rails.configuration.ran_block
end
test "runner block works at instance level" do
- $ran_block = false
-
app_file "config/environments/development.rb", <<-RUBY
Rails.application.configure do
+ config.ran_block = false
+
runner do
- $ran_block = true
+ config.ran_block = true
end
end
RUBY
require "#{app_path}/config/environment"
+ assert_not Rails.configuration.ran_block
- assert !$ran_block
Rails.application.load_runner
- assert $ran_block
+ assert Rails.configuration.ran_block
end
test "loading the first existing database configuration available" do
app_file 'config/environments/development.rb', <<-RUBY
Rails.application.configure do
- config.paths.add 'config/database', with: 'config/nonexistant.yml'
+ config.paths.add 'config/database', with: 'config/nonexistent.yml'
config.paths['config/database'] << 'config/database.yml'
end
RUBY
require "#{app_path}/config/environment"
- db_config = Rails.application.config.database_configuration
+ assert_kind_of Hash, Rails.application.config.database_configuration
+ end
- assert db_config.is_a?(Hash)
+ test 'raises with proper error message if no database configuration found' do
+ FileUtils.rm("#{app_path}/config/database.yml")
+ require "#{app_path}/config/environment"
+ err = assert_raises RuntimeError do
+ Rails.application.config.database_configuration
+ end
+ assert_match 'config/database', err.message
end
test 'config.action_mailer.show_previews defaults to true in development' do
@@ -993,7 +1244,7 @@ module ApplicationTests
Rails.env = "production"
require "#{app_path}/config/environment"
- assert_equal Rails.application.config.action_mailer.show_previews, false
+ assert_equal false, Rails.application.config.action_mailer.show_previews
end
test 'config.action_mailer.show_previews can be set in the configuration file' do
@@ -1003,7 +1254,7 @@ module ApplicationTests
RUBY
require "#{app_path}/config/environment"
- assert_equal Rails.application.config.action_mailer.show_previews, true
+ assert_equal true, Rails.application.config.action_mailer.show_previews
end
test "config_for loads custom configuration from yaml files" do
diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb
index 8e76bf27f3..2d45c9b53f 100644
--- a/railties/test/application/initializers/frameworks_test.rb
+++ b/railties/test/application/initializers/frameworks_test.rb
@@ -35,8 +35,8 @@ module ApplicationTests
require "#{app_path}/config/environment"
expanded_path = File.expand_path("app/views", app_path)
- assert_equal ActionController::Base.view_paths[0].to_s, expanded_path
- assert_equal ActionMailer::Base.view_paths[0].to_s, expanded_path
+ assert_equal expanded_path, ActionController::Base.view_paths[0].to_s
+ assert_equal expanded_path, ActionMailer::Base.view_paths[0].to_s
end
test "allows me to configure default url options for ActionMailer" do
@@ -50,7 +50,7 @@ module ApplicationTests
assert_equal "test.rails", ActionMailer::Base.default_url_options[:host]
end
- test "does not include url helpers as action methods" do
+ test "includes url helpers as action methods" do
app_file "config/routes.rb", <<-RUBY
Rails.application.routes.draw do
get "/foo", :to => lambda { |env| [200, {}, []] }, :as => :foo
@@ -66,8 +66,8 @@ module ApplicationTests
require "#{app_path}/config/environment"
assert Foo.method_defined?(:foo_path)
+ assert Foo.method_defined?(:foo_url)
assert Foo.method_defined?(:main_app)
- assert_equal Set.new(["notify"]), Foo.action_methods
end
test "allows to not load all helpers for controllers" do
diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb
index 4f30f30f95..85066210f3 100644
--- a/railties/test/application/loading_test.rb
+++ b/railties/test/application/loading_test.rb
@@ -33,6 +33,35 @@ class LoadingTest < ActiveSupport::TestCase
assert_equal 'omg', p.title
end
+ test "concerns in app are autoloaded" do
+ app_file "app/controllers/concerns/trackable.rb", <<-CONCERN
+ module Trackable
+ end
+ CONCERN
+
+ app_file "app/mailers/concerns/email_loggable.rb", <<-CONCERN
+ module EmailLoggable
+ end
+ CONCERN
+
+ app_file "app/models/concerns/orderable.rb", <<-CONCERN
+ module Orderable
+ end
+ CONCERN
+
+ app_file "app/validators/concerns/matchable.rb", <<-CONCERN
+ module Matchable
+ end
+ CONCERN
+
+ require "#{rails_root}/config/environment"
+
+ assert_nothing_raised(NameError) { Trackable }
+ assert_nothing_raised(NameError) { EmailLoggable }
+ assert_nothing_raised(NameError) { Orderable }
+ assert_nothing_raised(NameError) { Matchable }
+ end
+
test "models without table do not panic on scope definitions when loaded" do
app_file "app/models/user.rb", <<-MODEL
class User < ActiveRecord::Base
diff --git a/railties/test/application/mailer_previews_test.rb b/railties/test/application/mailer_previews_test.rb
index 8b91a1171f..9e4f858539 100644
--- a/railties/test/application/mailer_previews_test.rb
+++ b/railties/test/application/mailer_previews_test.rb
@@ -40,6 +40,17 @@ module ApplicationTests
assert_equal 404, last_response.status
end
+ test "/rails/mailers is accessible with globbing route present" do
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ get '*foo', to: 'foo#index'
+ end
+ RUBY
+ app("development")
+ get "/rails/mailers"
+ assert_equal 200, last_response.status
+ end
+
test "mailer previews are loaded from the default preview_path" do
mailer 'notifier', <<-RUBY
class Notifier < ActionMailer::Base
@@ -417,6 +428,58 @@ module ApplicationTests
assert_match '<option selected value="?part=text%2Fplain">View as plain-text email</option>', last_response.body
end
+ test "*_path helpers emit a deprecation" do
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ get 'foo', to: 'foo#index'
+ end
+ RUBY
+
+ mailer 'notifier', <<-RUBY
+ class Notifier < ActionMailer::Base
+ default from: "from@example.com"
+
+ def path_in_view
+ mail to: "to@example.org"
+ end
+
+ def path_in_mailer
+ @url = foo_path
+ mail to: "to@example.org"
+ end
+ end
+ RUBY
+
+ html_template 'notifier/path_in_view', "<%= link_to 'foo', foo_path %>"
+
+ mailer_preview 'notifier', <<-RUBY
+ class NotifierPreview < ActionMailer::Preview
+ def path_in_view
+ Notifier.path_in_view
+ end
+
+ def path_in_mailer
+ Notifier.path_in_mailer
+ end
+ end
+ RUBY
+
+ app('development')
+
+ assert_deprecated do
+ get "/rails/mailers/notifier/path_in_view.html"
+ assert_equal 200, last_response.status
+ end
+
+ html_template 'notifier/path_in_mailer', "No ERB in here"
+
+ assert_deprecated do
+ get "/rails/mailers/notifier/path_in_mailer.html"
+ assert_equal 200, last_response.status
+ end
+ end
+
private
def build_app
super
diff --git a/railties/test/application/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb
index b4db840e68..c951dabd6c 100644
--- a/railties/test/application/middleware/cache_test.rb
+++ b/railties/test/application/middleware/cache_test.rb
@@ -81,8 +81,8 @@ module ApplicationTests
add_to_config "config.action_dispatch.rack_cache = true"
get "/expires/expires_header"
- assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"]
- assert_equal "max-age=10, public", last_response.headers["Cache-Control"]
+ assert_equal "miss, store", last_response.headers["X-Rack-Cache"]
+ assert_equal "max-age=10, public", last_response.headers["Cache-Control"]
body = last_response.body
@@ -115,8 +115,8 @@ module ApplicationTests
add_to_config "config.action_dispatch.rack_cache = true"
get "/expires/expires_etag"
- assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"]
- assert_equal "public", last_response.headers["Cache-Control"]
+ assert_equal "miss, store", last_response.headers["X-Rack-Cache"]
+ assert_equal "public", last_response.headers["Cache-Control"]
body = last_response.body
etag = last_response.headers["ETag"]
@@ -149,8 +149,8 @@ module ApplicationTests
add_to_config "config.action_dispatch.rack_cache = true"
get "/expires/expires_last_modified"
- assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"]
- assert_equal "public", last_response.headers["Cache-Control"]
+ assert_equal "miss, store", last_response.headers["X-Rack-Cache"]
+ assert_equal "public", last_response.headers["Cache-Control"]
body = last_response.body
last = last_response.headers["Last-Modified"]
diff --git a/railties/test/application/middleware/exceptions_test.rb b/railties/test/application/middleware/exceptions_test.rb
index 42096cfec4..a7472b37f1 100644
--- a/railties/test/application/middleware/exceptions_test.rb
+++ b/railties/test/application/middleware/exceptions_test.rb
@@ -60,6 +60,21 @@ module ApplicationTests
assert_equal "YOU FAILED BRO", last_response.body
end
+ test "url generation error when action_dispatch.show_exceptions is set raises an exception" do
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ raise ActionController::UrlGenerationError
+ end
+ end
+ RUBY
+
+ app.config.action_dispatch.show_exceptions = true
+
+ get '/foo'
+ assert_equal 500, last_response.status
+ end
+
test "unspecified route when action_dispatch.show_exceptions is not set raises an exception" do
app.config.action_dispatch.show_exceptions = false
diff --git a/railties/test/application/middleware/remote_ip_test.rb b/railties/test/application/middleware/remote_ip_test.rb
index 946b82eeb3..97d5b5c698 100644
--- a/railties/test/application/middleware/remote_ip_test.rb
+++ b/railties/test/application/middleware/remote_ip_test.rb
@@ -1,3 +1,4 @@
+require 'ipaddr'
require 'isolation/abstract_unit'
require 'active_support/key_generator'
@@ -53,12 +54,25 @@ module ApplicationTests
end
end
+ test "remote_ip works with HTTP_X_FORWARDED_FOR" do
+ make_basic_app
+ assert_equal "4.2.42.42", remote_ip("REMOTE_ADDR" => "1.1.1.1", "HTTP_X_FORWARDED_FOR" => "4.2.42.42")
+ end
+
test "the user can set trusted proxies" do
make_basic_app do |app|
app.config.action_dispatch.trusted_proxies = /^4\.2\.42\.42$/
end
- assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "4.2.42.42,1.1.1.1")
+ assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "1.1.1.1", "HTTP_X_FORWARDED_FOR" => "4.2.42.42")
+ end
+
+ test "the user can set trusted proxies with an IPAddr argument" do
+ make_basic_app do |app|
+ app.config.action_dispatch.trusted_proxies = IPAddr.new('4.2.42.0/24')
+ end
+
+ assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "1.1.1.1", "HTTP_X_FORWARDED_FOR" => "10.0.0.0,4.2.42.42")
end
end
end
diff --git a/railties/test/application/middleware/sendfile_test.rb b/railties/test/application/middleware/sendfile_test.rb
index eb791f5687..dc96480d6d 100644
--- a/railties/test/application/middleware/sendfile_test.rb
+++ b/railties/test/application/middleware/sendfile_test.rb
@@ -61,7 +61,7 @@ module ApplicationTests
test "files handled by ActionDispatch::Static are handled by Rack::Sendfile" do
make_basic_app do |app|
app.config.action_dispatch.x_sendfile_header = 'X-Sendfile'
- app.config.serve_static_assets = true
+ app.config.serve_static_files = true
app.paths["public"] = File.join(rails_root, "public")
end
diff --git a/railties/test/application/middleware/session_test.rb b/railties/test/application/middleware/session_test.rb
index 31a64c2f5a..eb7885e5b1 100644
--- a/railties/test/application/middleware/session_test.rb
+++ b/railties/test/application/middleware/session_test.rb
@@ -203,7 +203,7 @@ module ApplicationTests
RUBY
add_to_config <<-RUBY
- config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
+ secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
RUBY
require "#{app_path}/config/environment"
@@ -258,7 +258,7 @@ module ApplicationTests
RUBY
add_to_config <<-RUBY
- config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
+ secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
RUBY
require "#{app_path}/config/environment"
@@ -317,7 +317,7 @@ module ApplicationTests
RUBY
add_to_config <<-RUBY
- config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
+ secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
secrets.secret_key_base = nil
RUBY
@@ -334,7 +334,7 @@ module ApplicationTests
get '/foo/read_signed_cookie'
assert_equal '2', last_response.body
- verifier = ActiveSupport::MessageVerifier.new(app.config.secret_token)
+ verifier = ActiveSupport::MessageVerifier.new(app.secrets.secret_token)
get '/foo/read_raw_cookie'
assert_equal 2, verifier.verify(last_response.body)['foo']
diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb
index 1557b90d27..c64fe082f3 100644
--- a/railties/test/application/middleware_test.rb
+++ b/railties/test/application/middleware_test.rb
@@ -83,7 +83,7 @@ module ApplicationTests
add_to_config "config.ssl_options = { host: 'example.com' }"
boot!
- assert_equal Rails.application.middleware.first.args, [{host: 'example.com'}]
+ assert_equal [{host: 'example.com'}], Rails.application.middleware.first.args
end
test "removing Active Record omits its middleware" do
@@ -94,20 +94,27 @@ module ApplicationTests
assert !middleware.include?("ActiveRecord::Migration::CheckPending")
end
- test "removes lock if cache classes is set" do
+ test "includes lock if cache_classes is set but eager_load is not" do
add_to_config "config.cache_classes = true"
boot!
+ assert middleware.include?("Rack::Lock")
+ 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")
end
- test "removes lock if allow concurrency is set" do
+ test "does not include lock if allow_concurrency is set" do
add_to_config "config.allow_concurrency = true"
boot!
assert !middleware.include?("Rack::Lock")
end
- test "removes static asset server if serve_static_assets is disabled" do
- add_to_config "config.serve_static_assets = false"
+ test "removes static asset server if serve_static_files is disabled" do
+ add_to_config "config.serve_static_files = false"
boot!
assert !middleware.include?("ActionDispatch::Static")
end
@@ -188,7 +195,7 @@ module ApplicationTests
end
end
- etag = "5af83e3196bf99f440f31f2e1a6c9afe".inspect
+ etag = "W/" + "5af83e3196bf99f440f31f2e1a6c9afe".inspect
get "/"
assert_equal 200, last_response.status
diff --git a/railties/test/application/multiple_applications_test.rb b/railties/test/application/multiple_applications_test.rb
index f8d8a673ae..cddc79cc85 100644
--- a/railties/test/application/multiple_applications_test.rb
+++ b/railties/test/application/multiple_applications_test.rb
@@ -8,6 +8,7 @@ module ApplicationTests
build_app(initializers: true)
boot_rails
require "#{rails_root}/config/environment"
+ Rails.application.config.some_setting = 'something_or_other'
end
def teardown
@@ -18,7 +19,7 @@ module ApplicationTests
clone = Rails.application.clone
assert_equal Rails.application.config, clone.config, "The cloned application should get a copy of the config"
- assert_equal Rails.application.config.secret_key_base, clone.config.secret_key_base, "The base secret key on the config should be the same"
+ assert_equal Rails.application.config.some_setting, clone.config.some_setting, "The some_setting on the config should be the same"
end
def test_inheriting_multiple_times_from_application
@@ -36,23 +37,23 @@ module ApplicationTests
end
def test_initialization_of_application_with_previous_config
- application1 = AppTemplate::Application.new(config: Rails.application.config)
- application2 = AppTemplate::Application.new
+ application1 = AppTemplate::Application.create(config: Rails.application.config)
+ application2 = AppTemplate::Application.create
assert_equal Rails.application.config, application1.config, "Creating a new application while setting an initial config should result in the same config"
assert_not_equal Rails.application.config, application2.config, "New applications without setting an initial config should not have the same config"
end
def test_initialization_of_application_with_previous_railties
- application1 = AppTemplate::Application.new(railties: Rails.application.railties)
- application2 = AppTemplate::Application.new
+ application1 = AppTemplate::Application.create(railties: Rails.application.railties)
+ application2 = AppTemplate::Application.create
assert_equal Rails.application.railties, application1.railties
assert_not_equal Rails.application.railties, application2.railties
end
def test_initialize_new_application_with_all_previous_initialization_variables
- application1 = AppTemplate::Application.new(
+ application1 = AppTemplate::Application.create(
config: Rails.application.config,
railties: Rails.application.railties,
routes_reloader: Rails.application.routes_reloader,
@@ -72,26 +73,26 @@ module ApplicationTests
end
def test_rake_tasks_defined_on_different_applications_go_to_the_same_class
- $run_count = 0
+ run_count = 0
application1 = AppTemplate::Application.new
application1.rake_tasks do
- $run_count += 1
+ run_count += 1
end
application2 = AppTemplate::Application.new
application2.rake_tasks do
- $run_count += 1
+ run_count += 1
end
require "#{app_path}/config/environment"
- assert_equal 0, $run_count, "The count should stay at zero without any calls to the rake tasks"
+ assert_equal 0, run_count, "The count should stay at zero without any calls to the rake tasks"
require 'rake'
require 'rake/testtask'
require 'rdoc/task'
Rails.application.load_tasks
- assert_equal 2, $run_count, "Calling a rake task should result in two increments to the count"
+ assert_equal 2, run_count, "Calling a rake task should result in two increments to the count"
end
def test_multiple_applications_can_be_initialized
@@ -100,56 +101,56 @@ module ApplicationTests
def test_initializers_run_on_different_applications_go_to_the_same_class
application1 = AppTemplate::Application.new
- $run_count = 0
+ run_count = 0
AppTemplate::Application.initializer :init0 do
- $run_count += 1
+ run_count += 1
end
application1.initializer :init1 do
- $run_count += 1
+ run_count += 1
end
AppTemplate::Application.new.initializer :init2 do
- $run_count += 1
+ run_count += 1
end
- assert_equal 0, $run_count, "Without loading the initializers, the count should be 0"
+ assert_equal 0, run_count, "Without loading the initializers, the count should be 0"
# Set config.eager_load to false so that an eager_load warning doesn't pop up
AppTemplate::Application.new { config.eager_load = false }.initialize!
- assert_equal 3, $run_count, "There should have been three initializers that incremented the count"
+ assert_equal 3, run_count, "There should have been three initializers that incremented the count"
end
def test_consoles_run_on_different_applications_go_to_the_same_class
- $run_count = 0
- AppTemplate::Application.console { $run_count += 1 }
- AppTemplate::Application.new.console { $run_count += 1 }
+ run_count = 0
+ AppTemplate::Application.console { run_count += 1 }
+ AppTemplate::Application.new.console { run_count += 1 }
- assert_equal 0, $run_count, "Without loading the consoles, the count should be 0"
+ assert_equal 0, run_count, "Without loading the consoles, the count should be 0"
Rails.application.load_console
- assert_equal 2, $run_count, "There should have been two consoles that increment the count"
+ assert_equal 2, run_count, "There should have been two consoles that increment the count"
end
def test_generators_run_on_different_applications_go_to_the_same_class
- $run_count = 0
- AppTemplate::Application.generators { $run_count += 1 }
- AppTemplate::Application.new.generators { $run_count += 1 }
+ run_count = 0
+ AppTemplate::Application.generators { run_count += 1 }
+ AppTemplate::Application.new.generators { run_count += 1 }
- assert_equal 0, $run_count, "Without loading the generators, the count should be 0"
+ assert_equal 0, run_count, "Without loading the generators, the count should be 0"
Rails.application.load_generators
- assert_equal 2, $run_count, "There should have been two generators that increment the count"
+ assert_equal 2, run_count, "There should have been two generators that increment the count"
end
def test_runners_run_on_different_applications_go_to_the_same_class
- $run_count = 0
- AppTemplate::Application.runner { $run_count += 1 }
- AppTemplate::Application.new.runner { $run_count += 1 }
+ run_count = 0
+ AppTemplate::Application.runner { run_count += 1 }
+ AppTemplate::Application.new.runner { run_count += 1 }
- assert_equal 0, $run_count, "Without loading the runners, the count should be 0"
+ assert_equal 0, run_count, "Without loading the runners, the count should be 0"
Rails.application.load_runner
- assert_equal 2, $run_count, "There should have been two runners that increment the count"
+ assert_equal 2, run_count, "There should have been two runners that increment the count"
end
def test_isolate_namespace_on_an_application
@@ -160,13 +161,14 @@ module ApplicationTests
def test_inserting_configuration_into_application
app = AppTemplate::Application.new(config: Rails.application.config)
- new_config = Rails::Application::Configuration.new("root_of_application")
- new_config.secret_key_base = "some_secret_key_dude"
- app.config.secret_key_base = "a_different_secret_key"
+ app.config.some_setting = "a_different_setting"
+ assert_equal "a_different_setting", app.config.some_setting, "The configuration's some_setting should be set."
- assert_equal "a_different_secret_key", app.config.secret_key_base, "The configuration's secret key should be set."
+ new_config = Rails::Application::Configuration.new("root_of_application")
+ new_config.some_setting = "some_setting_dude"
app.config = new_config
- assert_equal "some_secret_key_dude", app.config.secret_key_base, "The configuration's secret key should have changed."
+
+ assert_equal "some_setting_dude", app.config.some_setting, "The configuration's some_setting should have changed."
assert_equal "root_of_application", app.config.root, "The root should have changed to the new config's root."
assert_equal new_config, app.config, "The application's config should have changed to the new config."
end
diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb
index 15414db00f..c414732f92 100644
--- a/railties/test/application/rake/dbs_test.rb
+++ b/railties/test/application/rake/dbs_test.rb
@@ -109,6 +109,16 @@ module ApplicationTests
db_fixtures_load database_url_db_name
end
+ 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`
+ require "#{app_path}/app/models/admin/book"
+ assert_equal 2, Admin::Book.count
+ end
+ end
+
def db_structure_dump_and_load(expected_database)
Dir.chdir(app_path) do
`rails generate model book title:string;
@@ -146,6 +156,31 @@ module ApplicationTests
end
end
+ test 'db:schema:load and db:structure:load do not purge the existing database' do
+ Dir.chdir(app_path) do
+ `bin/rails runner 'ActiveRecord::Base.connection.create_table(:posts) {|t| t.string :title }'`
+
+ app_file 'db/schema.rb', <<-RUBY
+ ActiveRecord::Schema.define(version: 20140423102712) do
+ create_table(:comments) {}
+ end
+ RUBY
+
+ list_tables = lambda { `bin/rails runner 'p ActiveRecord::Base.connection.tables'`.strip }
+
+ assert_equal '["posts"]', list_tables[]
+ `bin/rake db:schema:load`
+ assert_equal '["posts", "comments", "schema_migrations"]', list_tables[]
+
+ app_file 'db/structure.sql', <<-SQL
+ CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255));
+ SQL
+
+ `bin/rake db:structure:load`
+ assert_equal '["posts", "comments", "schema_migrations", "users"]', list_tables[]
+ end
+ end
+
def db_test_load_structure
Dir.chdir(app_path) do
`rails generate model book title:string;
@@ -165,12 +200,32 @@ module ApplicationTests
db_test_load_structure
end
- test 'db:test deprecation' do
- require "#{app_path}/config/environment"
- Dir.chdir(app_path) do
- output = `bundle exec rake db:migrate db:test:prepare 2>&1`
- assert_equal "WARNING: db:test:prepare is deprecated. The Rails test helper now maintains " \
- "your test schema automatically, see the release notes for details.\n", output
+ test 'db:setup loads schema and seeds database' do
+ begin
+ @old_rails_env = ENV["RAILS_ENV"]
+ @old_rack_env = ENV["RACK_ENV"]
+ ENV.delete "RAILS_ENV"
+ ENV.delete "RACK_ENV"
+
+ app_file 'db/schema.rb', <<-RUBY
+ ActiveRecord::Schema.define(version: "1") do
+ create_table :users do |t|
+ t.string :name
+ end
+ end
+ RUBY
+
+ app_file 'db/seeds.rb', <<-RUBY
+ puts ActiveRecord::Base.connection_config[:database]
+ RUBY
+
+ Dir.chdir(app_path) do
+ database_path = `bundle exec rake db:setup`
+ assert_equal "development.sqlite3", File.basename(database_path.strip)
+ end
+ ensure
+ ENV["RAILS_ENV"] = @old_rails_env
+ ENV["RACK_ENV"] = @old_rack_env
end
end
end
diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb
index 8576a2b738..cbada6be97 100644
--- a/railties/test/application/routing_test.rb
+++ b/railties/test/application/routing_test.rb
@@ -123,6 +123,26 @@ module ApplicationTests
assert_equal '/archives', last_response.body
end
+ test "mount named rack app" do
+ controller :foo, <<-RUBY
+ class FooController < ApplicationController
+ def index
+ render text: my_blog_path
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ Rails.application.routes.draw do
+ mount lambda { |env| [200, {}, [env["PATH_INFO"]]] }, at: "/blog", as: "my_blog"
+ get '/foo' => 'foo#index'
+ end
+ RUBY
+
+ get '/foo'
+ assert_equal '/blog', last_response.body
+ end
+
test "multiple controllers" do
controller :foo, <<-RUBY
class FooController < ApplicationController
diff --git a/railties/test/application/test_runner_test.rb b/railties/test/application/test_runner_test.rb
index 118f22995e..032b11a95f 100644
--- a/railties/test/application/test_runner_test.rb
+++ b/railties/test/application/test_runner_test.rb
@@ -109,6 +109,17 @@ module ApplicationTests
end
end
+ def test_run_jobs
+ create_test_file :jobs, 'foo_job'
+ create_test_file :jobs, 'bar_job'
+ create_test_file :models, 'foo'
+ run_test_jobs_command.tap do |output|
+ assert_match "FooJobTest", output
+ assert_match "BarJobTest", output
+ assert_match "2 runs, 2 assertions, 0 failures", output
+ end
+ end
+
def test_run_functionals
create_test_file :mailers, 'foo_mailer'
create_test_file :controllers, 'bar_controller'
@@ -132,11 +143,11 @@ module ApplicationTests
end
def test_run_all_suites
- suites = [:models, :helpers, :unit, :controllers, :mailers, :functional, :integration]
+ suites = [:models, :helpers, :unit, :controllers, :mailers, :functional, :integration, :jobs]
suites.each { |suite| create_test_file suite, "foo_#{suite}" }
run_test_command('') .tap do |output|
suites.each { |suite| assert_match "Foo#{suite.to_s.camelize}Test", output }
- assert_match "7 runs, 7 assertions, 0 failures", output
+ assert_match "8 runs, 8 assertions, 0 failures", output
end
end
@@ -245,7 +256,7 @@ module ApplicationTests
def run_test_command(arguments = 'test/unit/test_test.rb')
run_task ['test', arguments]
end
- %w{ mailers models helpers units controllers functionals integration }.each do |type|
+ %w{ mailers models helpers units controllers functionals integration jobs }.each do |type|
define_method("run_test_#{type}_command") do
run_task ["test:#{type}"]
end
diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb
index a223180169..c7132837b1 100644
--- a/railties/test/application/test_test.rb
+++ b/railties/test/application/test_test.rb
@@ -67,7 +67,7 @@ module ApplicationTests
assert_match %r{/app/test/unit/failing_test\.rb}, output
end
- test "migrations" do
+ test "ruby schema migrations" do
output = script('generate model user name:string')
version = output.match(/(\d+)_create_users\.rb/)[1]
@@ -104,6 +104,187 @@ module ApplicationTests
assert !result.include?("create_table(:users)")
end
+ test "sql structure migrations" do
+ output = script('generate model user name:string')
+ version = output.match(/(\d+)_create_users\.rb/)[1]
+
+ app_file 'test/models/user_test.rb', <<-RUBY
+ require 'test_helper'
+
+ class UserTest < ActiveSupport::TestCase
+ test "user" do
+ User.create! name: "Jon"
+ end
+ end
+ RUBY
+
+ app_file 'db/structure.sql', ''
+ app_file 'config/initializers/enable_sql_schema_format.rb', <<-RUBY
+ Rails.application.config.active_record.schema_format = :sql
+ RUBY
+
+ assert_unsuccessful_run "models/user_test.rb", "Migrations are pending"
+
+ app_file 'db/structure.sql', <<-SQL
+ CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL);
+ CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version");
+ CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255));
+ INSERT INTO schema_migrations (version) VALUES ('#{version}');
+ SQL
+
+ app_file 'config/initializers/disable_maintain_test_schema.rb', <<-RUBY
+ Rails.application.config.active_record.maintain_test_schema = false
+ RUBY
+
+ assert_unsuccessful_run "models/user_test.rb", "Could not find table 'users'"
+
+ File.delete "#{app_path}/config/initializers/disable_maintain_test_schema.rb"
+
+ assert_successful_test_run('models/user_test.rb')
+ end
+
+ test "sql structure migrations when adding column to existing table" do
+ output_1 = script('generate model user name:string')
+ version_1 = output_1.match(/(\d+)_create_users\.rb/)[1]
+
+ app_file 'test/models/user_test.rb', <<-RUBY
+ require 'test_helper'
+ class UserTest < ActiveSupport::TestCase
+ test "user" do
+ User.create! name: "Jon"
+ end
+ end
+ RUBY
+
+ app_file 'config/initializers/enable_sql_schema_format.rb', <<-RUBY
+ Rails.application.config.active_record.schema_format = :sql
+ RUBY
+
+ app_file 'db/structure.sql', <<-SQL
+ CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL);
+ CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version");
+ CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255));
+ INSERT INTO schema_migrations (version) VALUES ('#{version_1}');
+ SQL
+
+ assert_successful_test_run('models/user_test.rb')
+
+ output_2 = script('generate migration add_email_to_users')
+ version_2 = output_2.match(/(\d+)_add_email_to_users\.rb/)[1]
+
+ app_file 'test/models/user_test.rb', <<-RUBY
+ require 'test_helper'
+
+ class UserTest < ActiveSupport::TestCase
+ test "user" do
+ User.create! name: "Jon", email: "jon@doe.com"
+ end
+ end
+ RUBY
+
+ app_file 'db/structure.sql', <<-SQL
+ CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL);
+ CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version");
+ CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255), "email" varchar(255));
+ INSERT INTO schema_migrations (version) VALUES ('#{version_1}');
+ INSERT INTO schema_migrations (version) VALUES ('#{version_2}');
+ SQL
+
+ assert_successful_test_run('models/user_test.rb')
+ end
+
+ # TODO: would be nice if we could detect the schema change automatically.
+ # For now, the user has to synchronize the schema manually.
+ # This test-case serves as a reminder for this use-case.
+ test "manually synchronize test schema after rollback" do
+ output = script('generate model user name:string')
+ version = output.match(/(\d+)_create_users\.rb/)[1]
+
+ app_file 'test/models/user_test.rb', <<-RUBY
+ require 'test_helper'
+
+ class UserTest < ActiveSupport::TestCase
+ test "user" do
+ assert_equal ["id", "name"], User.columns_hash.keys
+ end
+ end
+ RUBY
+ app_file 'db/schema.rb', <<-RUBY
+ ActiveRecord::Schema.define(version: #{version}) do
+ create_table :users do |t|
+ t.string :name
+ end
+ end
+ RUBY
+
+ assert_successful_test_run "models/user_test.rb"
+
+ # Simulate `db:rollback` + edit of the migration file + `db:migrate`
+ app_file 'db/schema.rb', <<-RUBY
+ ActiveRecord::Schema.define(version: #{version}) do
+ create_table :users do |t|
+ t.string :name
+ t.integer :age
+ end
+ end
+ RUBY
+
+ assert_successful_test_run "models/user_test.rb"
+
+ Dir.chdir(app_path) { `bin/rake db:test:prepare` }
+
+ assert_unsuccessful_run "models/user_test.rb", <<-ASSERTION
+Expected: ["id", "name"]
+ Actual: ["id", "name", "age"]
+ ASSERTION
+ end
+
+ test "hooks for plugins" do
+ output = script('generate model user name:string')
+ version = output.match(/(\d+)_create_users\.rb/)[1]
+
+ app_file 'lib/tasks/hooks.rake', <<-RUBY
+ task :before_hook do
+ has_user_table = ActiveRecord::Base.connection.table_exists?('users')
+ puts "before: " + has_user_table.to_s
+ end
+
+ task :after_hook do
+ has_user_table = ActiveRecord::Base.connection.table_exists?('users')
+ puts "after: " + has_user_table.to_s
+ end
+
+ Rake::Task["db:test:prepare"].enhance [:before_hook] do
+ Rake::Task[:after_hook].invoke
+ end
+ RUBY
+ app_file 'test/models/user_test.rb', <<-RUBY
+ require 'test_helper'
+ class UserTest < ActiveSupport::TestCase
+ test "user" do
+ User.create! name: "Jon"
+ end
+ end
+ RUBY
+
+ # Simulate `db:migrate`
+ app_file 'db/schema.rb', <<-RUBY
+ ActiveRecord::Schema.define(version: #{version}) do
+ create_table :users do |t|
+ t.string :name
+ end
+ end
+ RUBY
+
+ output = assert_successful_test_run "models/user_test.rb"
+ assert_includes output, "before: false\nafter: true"
+
+ # running tests again won't trigger a schema update
+ output = assert_successful_test_run "models/user_test.rb"
+ assert_not_includes output, "before:"
+ assert_not_includes output, "after:"
+ end
+
private
def assert_unsuccessful_run(name, message)
result = run_test_file(name)
@@ -119,7 +300,7 @@ module ApplicationTests
end
def run_test_file(name, options = {})
- ruby '-Itest', "#{app_path}/test/#{name}", options
+ ruby '-Itest', "#{app_path}/test/#{name}", options.deep_merge(env: {"RAILS_ENV" => "test"})
end
def ruby(*args)
diff --git a/railties/test/application/url_generation_test.rb b/railties/test/application/url_generation_test.rb
index efbc853d7b..ef16ab56ed 100644
--- a/railties/test/application/url_generation_test.rb
+++ b/railties/test/application/url_generation_test.rb
@@ -15,7 +15,7 @@ module ApplicationTests
require "action_view/railtie"
class MyApp < Rails::Application
- config.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4"
+ secrets.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4"
config.session_store :cookie_store, key: "_myapp_session"
config.active_support.deprecation = :log
config.eager_load = false
diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb
index ede08e7b86..a3cd1eb0ed 100644
--- a/railties/test/commands/dbconsole_test.rb
+++ b/railties/test/commands/dbconsole_test.rb
@@ -28,7 +28,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
}
}
app_db_config(config_sample) do
- assert_equal Rails::DBConsole.new.config, config_sample["test"]
+ assert_equal config_sample["test"], Rails::DBConsole.new.config
end
end
@@ -79,22 +79,23 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
end
def test_env
- assert_equal Rails::DBConsole.new.environment, "test"
+ assert_equal "test", Rails::DBConsole.new.environment
ENV['RAILS_ENV'] = nil
ENV['RACK_ENV'] = nil
Rails.stub(:respond_to?, false) do
- assert_equal Rails::DBConsole.new.environment, "development"
+ assert_equal "development", Rails::DBConsole.new.environment
ENV['RACK_ENV'] = "rack_env"
- assert_equal Rails::DBConsole.new.environment, "rack_env"
+ assert_equal "rack_env", Rails::DBConsole.new.environment
ENV['RAILS_ENV'] = "rails_env"
- assert_equal Rails::DBConsole.new.environment, "rails_env"
+ assert_equal "rails_env", Rails::DBConsole.new.environment
end
ensure
ENV['RAILS_ENV'] = "test"
+ ENV['RACK_ENV'] = nil
end
def test_rails_env_is_development_when_argument_is_dev
diff --git a/railties/test/configuration/middleware_stack_proxy_test.rb b/railties/test/configuration/middleware_stack_proxy_test.rb
index 6f3e45f320..d5072614cf 100644
--- a/railties/test/configuration/middleware_stack_proxy_test.rb
+++ b/railties/test/configuration/middleware_stack_proxy_test.rb
@@ -1,3 +1,4 @@
+require 'active_support'
require 'active_support/testing/autorun'
require 'rails/configuration'
require 'active_support/test_case'
diff --git a/railties/test/engine_test.rb b/railties/test/engine_test.rb
index 7970913d21..f46fb748f5 100644
--- a/railties/test/engine_test.rb
+++ b/railties/test/engine_test.rb
@@ -11,4 +11,15 @@ class EngineTest < ActiveSupport::TestCase
assert !engine.routes?
end
+
+ def test_application_can_be_subclassed
+ klass = Class.new(Rails::Application) do
+ attr_reader :hello
+ def initialize
+ @hello = "world"
+ super
+ end
+ end
+ assert_equal "world", klass.instance.hello
+ end
end
diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb
index a4337926d1..c4b6441397 100644
--- a/railties/test/generators/actions_test.rb
+++ b/railties/test/generators/actions_test.rb
@@ -79,6 +79,16 @@ class ActionsTest < Rails::Generators::TestCase
assert_file 'Gemfile', /gem 'rspec', github: 'dchelimsky\/rspec', tag: '1\.2\.9\.rc1'/
end
+ def test_gem_with_non_string_options
+ run_generator
+
+ action :gem, 'rspec', require: false
+ action :gem, 'rspec-rails', group: [:development, :test]
+
+ assert_file 'Gemfile', /^gem 'rspec', require: false$/
+ assert_file 'Gemfile', /^gem 'rspec-rails', group: \[:development, :test\]$/
+ end
+
def test_gem_falls_back_to_inspect_if_string_contains_single_quote
run_generator
@@ -119,7 +129,7 @@ class ActionsTest < Rails::Generators::TestCase
run_generator
action :environment do
- '# This wont be added'
+ _ = '# This wont be added'# assignment to silence parse-time warning "unused literal ignored"
'# This will be added'
end
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index aff484f3eb..e30c9a7b2f 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -160,6 +160,38 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file("#{app_root}/config/initializers/cookies_serializer.rb", /Rails\.application\.config\.action_dispatch\.cookies_serializer = :json/)
end
+ def test_rails_update_does_not_create_callback_terminator_initializer
+ app_root = File.join(destination_root, 'myapp')
+ run_generator [app_root]
+
+ FileUtils.rm("#{app_root}/config/initializers/callback_terminator.rb")
+
+ Rails.application.config.root = app_root
+ Rails.application.class.stubs(:name).returns("Myapp")
+ Rails.application.stubs(:is_a?).returns(Rails::Application)
+
+ generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, destination_root: app_root, shell: @shell
+ generator.send(:app_const)
+ quietly { generator.send(:update_config_files) }
+ assert_no_file "#{app_root}/config/initializers/callback_terminator.rb"
+ end
+
+ def test_rails_update_does_not_remove_callback_terminator_initializer_if_already_present
+ app_root = File.join(destination_root, 'myapp')
+ run_generator [app_root]
+
+ FileUtils.touch("#{app_root}/config/initializers/callback_terminator.rb")
+
+ Rails.application.config.root = app_root
+ Rails.application.class.stubs(:name).returns("Myapp")
+ Rails.application.stubs(:is_a?).returns(Rails::Application)
+
+ generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, destination_root: app_root, shell: @shell
+ generator.send(:app_const)
+ quietly { generator.send(:update_config_files) }
+ assert_file "#{app_root}/config/initializers/callback_terminator.rb"
+ end
+
def test_rails_update_set_the_cookie_serializer_to_marchal_if_it_is_not_already_configured
app_root = File.join(destination_root, 'myapp')
run_generator [app_root]
@@ -194,20 +226,20 @@ class AppGeneratorTest < Rails::Generators::TestCase
def test_config_database_is_added_by_default
run_generator
assert_file "config/database.yml", /sqlite3/
- unless defined?(JRUBY_VERSION)
- assert_gem "sqlite3"
- else
+ if defined?(JRUBY_VERSION)
assert_gem "activerecord-jdbcsqlite3-adapter"
+ else
+ assert_gem "sqlite3"
end
end
def test_config_another_database
run_generator([destination_root, "-d", "mysql"])
assert_file "config/database.yml", /mysql/
- unless defined?(JRUBY_VERSION)
- assert_gem "mysql2"
- else
+ if defined?(JRUBY_VERSION)
assert_gem "activerecord-jdbcmysql-adapter"
+ else
+ assert_gem "mysql2"
end
end
@@ -219,10 +251,10 @@ class AppGeneratorTest < Rails::Generators::TestCase
def test_config_postgresql_database
run_generator([destination_root, "-d", "postgresql"])
assert_file "config/database.yml", /postgresql/
- unless defined?(JRUBY_VERSION)
- assert_gem "pg"
- else
+ if defined?(JRUBY_VERSION)
assert_gem "activerecord-jdbcpostgresql-adapter"
+ else
+ assert_gem "pg"
end
end
@@ -251,14 +283,28 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_gem "activerecord-jdbc-adapter"
end
- def test_config_jdbc_database_when_no_option_given
- if defined?(JRUBY_VERSION)
- run_generator([destination_root])
+ if defined?(JRUBY_VERSION)
+ def test_config_jdbc_database_when_no_option_given
+ run_generator
assert_file "config/database.yml", /sqlite3/
assert_gem "activerecord-jdbcsqlite3-adapter"
end
end
+ def test_generator_without_skips
+ run_generator
+ assert_file "config/application.rb", /\s+require\s+["']rails\/all["']/
+ assert_file "config/environments/development.rb" do |content|
+ assert_match(/config\.action_mailer\.raise_delivery_errors = false/, content)
+ end
+ assert_file "config/environments/test.rb" do |content|
+ assert_match(/config\.action_mailer\.delivery_method = :test/, content)
+ end
+ assert_file "config/environments/production.rb" do |content|
+ assert_match(/# config\.action_mailer\.raise_delivery_errors = false/, content)
+ end
+ end
+
def test_generator_if_skip_active_record_is_given
run_generator [destination_root, "--skip-active-record"]
assert_no_file "config/database.yml"
@@ -268,9 +314,18 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
end
- def test_generator_if_skip_action_view_is_given
- run_generator [destination_root, "--skip-action-view"]
- assert_file "config/application.rb", /#\s+require\s+["']action_view\/railtie["']/
+ def test_generator_if_skip_action_mailer_is_given
+ run_generator [destination_root, "--skip-action-mailer"]
+ assert_file "config/application.rb", /#\s+require\s+["']action_mailer\/railtie["']/
+ assert_file "config/environments/development.rb" do |content|
+ assert_no_match(/config\.action_mailer/, content)
+ end
+ assert_file "config/environments/test.rb" do |content|
+ assert_no_match(/config\.action_mailer/, content)
+ end
+ assert_file "config/environments/production.rb" do |content|
+ assert_no_match(/config\.action_mailer/, content)
+ end
end
def test_generator_if_skip_sprockets_is_given
@@ -295,11 +350,11 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
def test_inclusion_of_javascript_runtime
- run_generator([destination_root])
+ run_generator
if defined?(JRUBY_VERSION)
assert_gem "therubyrhino"
else
- assert_file "Gemfile", /# gem\s+["']therubyracer["']+, \s+platforms: :ruby$/
+ assert_file "Gemfile", /# gem 'therubyracer', platforms: :ruby/
end
end
@@ -340,20 +395,20 @@ class AppGeneratorTest < Rails::Generators::TestCase
def test_inclusion_of_jbuilder
run_generator
- assert_file "Gemfile", /gem 'jbuilder'/
+ assert_gem 'jbuilder'
end
def test_inclusion_of_a_debugger
run_generator
- if defined?(JRUBY_VERSION)
+ if defined?(JRUBY_VERSION) || RUBY_ENGINE == "rbx"
assert_file "Gemfile" do |content|
assert_no_match(/byebug/, content)
assert_no_match(/debugger/, content)
end
elsif RUBY_VERSION < '2.0.0'
- assert_file "Gemfile", /# gem 'debugger'/
+ assert_gem 'debugger'
else
- assert_file "Gemfile", /# gem 'byebug'/
+ assert_gem 'byebug'
end
end
@@ -395,10 +450,11 @@ class AppGeneratorTest < Rails::Generators::TestCase
run_generator [destination_root, "--skip-test-unit", "--skip-active-record"]
assert_file "config/application.rb", /#\s+require\s+["']rails\/test_unit\/railtie["']/
assert_file "config/application.rb", /#\s+require\s+["']active_record\/railtie["']/
+ assert_file "config/application.rb", /\s+require\s+["']active_job\/railtie["']/
end
def test_new_hash_style
- run_generator [destination_root]
+ run_generator
assert_file "config/initializers/session_store.rb" do |file|
assert_match(/config.session_store :cookie_store, key: '_.+_session'/, file)
end
@@ -419,9 +475,32 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "foo bar/config/initializers/session_store.rb", /key: '_foo_bar/
end
+ def test_web_console
+ run_generator
+ assert_gem 'web-console'
+ end
+
+ def test_web_console_with_dev_option
+ run_generator [destination_root, "--dev"]
+
+ assert_file "Gemfile" do |content|
+ assert_match(/gem 'web-console',\s+github: "rails\/web-console"/, content)
+ assert_no_match(/gem 'web-console', '~> 2.0'/, content)
+ end
+ end
+
+ def test_web_console_with_edge_option
+ run_generator [destination_root, "--edge"]
+
+ assert_file "Gemfile" do |content|
+ assert_match(/gem 'web-console',\s+github: "rails\/web-console"/, content)
+ assert_no_match(/gem 'web-console', '~> 2.0'/, content)
+ end
+ end
+
def test_spring
run_generator
- assert_file "Gemfile", /gem 'spring', \s+group: :development/
+ assert_gem 'spring'
end
def test_spring_binstubs
@@ -449,12 +528,11 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
end
- def test_generator_if_skip_gems_is_given
- run_generator [destination_root, "--skip-gems", "turbolinks", "coffee-rails"]
+ def test_generator_if_skip_turbolinks_is_given
+ run_generator [destination_root, "--skip-turbolinks"]
assert_file "Gemfile" do |content|
assert_no_match(/turbolinks/, content)
- assert_no_match(/coffee-rails/, content)
end
assert_file "app/views/layouts/application.html.erb" do |content|
assert_no_match(/data-turbolinks-track/, content)
@@ -490,7 +568,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
def test_psych_gem
run_generator
- gem_regex = /gem 'psych',\s+'~> 2.0', \s+platforms: :rbx/
+ gem_regex = /gem 'psych',\s+'~> 2.0',\s+platforms: :rbx/
assert_file "Gemfile" do |content|
if defined?(Rubinius)
@@ -501,6 +579,21 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_after_bundle_callback
+ path = 'http://example.org/rails_template'
+ template = %{ after_bundle { run 'echo ran after_bundle' } }
+ template.instance_eval "def read; self; end" # Make the string respond to read
+
+ generator([destination_root], template: path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
+
+ bundler_first = sequence('bundle, binstubs, after_bundle')
+ generator.expects(:bundle_command).with('install').once.in_sequence(bundler_first)
+ generator.expects(:bundle_command).with('exec spring binstub --all').in_sequence(bundler_first)
+ generator.expects(:run).with('echo ran after_bundle').in_sequence(bundler_first)
+
+ quietly { generator.invoke_all }
+ end
+
protected
def action(*args, &block)
@@ -508,6 +601,6 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
def assert_gem(gem)
- assert_file "Gemfile", /^gem\s+["']#{gem}["']$/
+ assert_file "Gemfile", /^\s*gem\s+["']#{gem}["']$*/
end
end
diff --git a/railties/test/generators/argv_scrubber_test.rb b/railties/test/generators/argv_scrubber_test.rb
index 31c2d846e2..31e07bc8da 100644
--- a/railties/test/generators/argv_scrubber_test.rb
+++ b/railties/test/generators/argv_scrubber_test.rb
@@ -1,5 +1,5 @@
-require 'active_support/testing/autorun'
require 'active_support/test_case'
+require 'active_support/testing/autorun'
require 'rails/generators/rails/app/app_generator'
require 'tempfile'
diff --git a/railties/test/generators/controller_generator_test.rb b/railties/test/generators/controller_generator_test.rb
index 28b527cb0e..a7d56dd352 100644
--- a/railties/test/generators/controller_generator_test.rb
+++ b/railties/test/generators/controller_generator_test.rb
@@ -28,13 +28,11 @@ class ControllerGeneratorTest < Rails::Generators::TestCase
def test_invokes_helper
run_generator
assert_file "app/helpers/account_helper.rb"
- assert_file "test/helpers/account_helper_test.rb"
end
def test_does_not_invoke_helper_if_required
run_generator ["account", "--skip-helper"]
assert_no_file "app/helpers/account_helper.rb"
- assert_no_file "test/helpers/account_helper_test.rb"
end
def test_invokes_assets
diff --git a/railties/test/generators/generated_attribute_test.rb b/railties/test/generators/generated_attribute_test.rb
index c48bc20899..ee7c009305 100644
--- a/railties/test/generators/generated_attribute_test.rb
+++ b/railties/test/generators/generated_attribute_test.rb
@@ -141,4 +141,12 @@ class GeneratedAttributeTest < Rails::Generators::TestCase
assert_equal "post_id", create_generated_attribute('references', 'post').column_name
assert_equal "post_id", create_generated_attribute('belongs_to', 'post').column_name
end
+
+ def test_parse_required_attribute_with_index
+ att = Rails::Generators::GeneratedAttribute.parse("supplier:references{required}:index")
+ assert_equal "supplier", att.name
+ assert_equal :references, att.type
+ assert att.has_index?
+ assert att.required?
+ end
end
diff --git a/railties/test/generators/generator_test.rb b/railties/test/generators/generator_test.rb
index b136239795..7871399dd7 100644
--- a/railties/test/generators/generator_test.rb
+++ b/railties/test/generators/generator_test.rb
@@ -1,5 +1,5 @@
-require 'active_support/testing/autorun'
require 'active_support/test_case'
+require 'active_support/testing/autorun'
require 'rails/generators/app_base'
module Rails
diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb
index de1e56e7b3..6cc91f166b 100644
--- a/railties/test/generators/generators_test_helper.rb
+++ b/railties/test/generators/generators_test_helper.rb
@@ -7,7 +7,7 @@ module Rails
class << self
remove_possible_method :root
def root
- @root ||= File.expand_path(File.join(File.dirname(__FILE__), '..', 'fixtures'))
+ @root ||= Pathname.new(File.expand_path('../../fixtures', __FILE__))
end
end
end
diff --git a/railties/test/generators/helper_generator_test.rb b/railties/test/generators/helper_generator_test.rb
index 81d4fcb129..add04f21a4 100644
--- a/railties/test/generators/helper_generator_test.rb
+++ b/railties/test/generators/helper_generator_test.rb
@@ -13,26 +13,11 @@ class HelperGeneratorTest < Rails::Generators::TestCase
assert_file "app/helpers/admin_helper.rb", /module AdminHelper/
end
- def test_invokes_default_test_framework
- run_generator
- assert_file "test/helpers/admin_helper_test.rb", /class AdminHelperTest < ActionView::TestCase/
- end
-
- def test_logs_if_the_test_framework_cannot_be_found
- content = run_generator ["admin", "--test-framework=rspec"]
- assert_match(/rspec \[not found\]/, content)
- end
-
def test_check_class_collision
content = capture(:stderr){ run_generator ["object"] }
assert_match(/The name 'ObjectHelper' is either already used in your application or reserved/, content)
end
- def test_check_class_collision_on_tests
- content = capture(:stderr){ run_generator ["another_object"] }
- assert_match(/The name 'AnotherObjectHelperTest' is either already used in your application or reserved/, content)
- end
-
def test_namespaced_and_not_namespaced_helpers
run_generator ["products"]
diff --git a/railties/test/generators/job_generator_test.rb b/railties/test/generators/job_generator_test.rb
new file mode 100644
index 0000000000..a9e0cea94f
--- /dev/null
+++ b/railties/test/generators/job_generator_test.rb
@@ -0,0 +1,29 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/job/job_generator'
+
+class JobGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+
+ def test_job_skeleton_is_created
+ run_generator ["refresh_counters"]
+ assert_file "app/jobs/refresh_counters_job.rb" do |job|
+ assert_match(/class RefreshCountersJob < ActiveJob::Base/, job)
+ end
+ end
+
+ def test_job_queue_param
+ run_generator ["refresh_counters", "--queue", "important"]
+ assert_file "app/jobs/refresh_counters_job.rb" do |job|
+ assert_match(/class RefreshCountersJob < ActiveJob::Base/, job)
+ assert_match(/queue_as :important/, job)
+ end
+ end
+
+ def test_job_namespace
+ run_generator ["admin/refresh_counters", "--queue", "admin"]
+ assert_file "app/jobs/admin/refresh_counters_job.rb" do |job|
+ assert_match(/class Admin::RefreshCountersJob < ActiveJob::Base/, job)
+ assert_match(/queue_as :admin/, job)
+ end
+ end
+end
diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb
index 25649881eb..3d1cf87dae 100644
--- a/railties/test/generators/mailer_generator_test.rb
+++ b/railties/test/generators/mailer_generator_test.rb
@@ -8,8 +8,18 @@ class MailerGeneratorTest < Rails::Generators::TestCase
def test_mailer_skeleton_is_created
run_generator
assert_file "app/mailers/notifier.rb" do |mailer|
- assert_match(/class Notifier < ActionMailer::Base/, mailer)
+ assert_match(/class Notifier < ApplicationMailer/, mailer)
+ assert_no_match(/default from: "from@example.com"/, mailer)
+ assert_no_match(/layout :mailer_notifier/, mailer)
+ end
+ end
+
+ def test_application_mailer_skeleton_is_created
+ run_generator
+ assert_file "app/mailers/application_mailer.rb" do |mailer|
+ assert_match(/class ApplicationMailer < ActionMailer::Base/, mailer)
assert_match(/default from: "from@example.com"/, mailer)
+ assert_match(/layout 'mailer'/, mailer)
end
end
@@ -77,6 +87,10 @@ class MailerGeneratorTest < Rails::Generators::TestCase
assert_match(%r(\sapp/views/notifier/bar\.text\.erb), view)
assert_match(/<%= @greeting %>/, view)
end
+
+ assert_file "app/views/layouts/mailer.text.erb" do |view|
+ assert_match(/<%= yield %>/, view)
+ end
end
def test_invokes_default_html_template_engine
@@ -90,11 +104,17 @@ class MailerGeneratorTest < Rails::Generators::TestCase
assert_match(%r(\sapp/views/notifier/bar\.html\.erb), view)
assert_match(/<%= @greeting %>/, view)
end
+
+ assert_file "app/views/layouts/mailer.html.erb" do |view|
+ assert_match(%r{<html>\n <body>\n <%= yield %>\n </body>\n</html>}, view)
+ end
end
def test_invokes_default_template_engine_even_with_no_action
run_generator ["notifier"]
assert_file "app/views/notifier"
+ assert_file "app/views/layouts/mailer.text.erb"
+ assert_file "app/views/layouts/mailer.html.erb"
end
def test_logs_if_the_template_engine_cannot_be_found
@@ -105,7 +125,7 @@ class MailerGeneratorTest < Rails::Generators::TestCase
def test_mailer_with_namedspaced_mailer
run_generator ["Farm::Animal", "moos"]
assert_file "app/mailers/farm/animal.rb" do |mailer|
- assert_match(/class Farm::Animal < ActionMailer::Base/, mailer)
+ assert_match(/class Farm::Animal < ApplicationMailer/, mailer)
assert_match(/en\.farm\.animal\.moos\.subject/, mailer)
end
assert_file "test/mailers/previews/farm/animal_preview.rb" do |preview|
@@ -132,4 +152,19 @@ class MailerGeneratorTest < Rails::Generators::TestCase
end
end
end
+
+ def test_mailer_on_revoke
+ run_generator
+ run_generator ["notifier"], behavior: :revoke
+
+ assert_no_file "app/mailers/notifier.rb"
+ assert_no_file "app/views/notifier/foo.text.erb"
+ assert_no_file "app/views/notifier/bar.text.erb"
+ assert_no_file "app/views/notifier/foo.html.erb"
+ assert_no_file "app/views/notifier/bar.html.erb"
+
+ assert_file "app/mailers/application_mailer.rb"
+ assert_file "app/views/layouts/mailer.text.erb"
+ assert_file "app/views/layouts/mailer.html.erb"
+ end
end
diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb
index 6fac643ed0..413d457d54 100644
--- a/railties/test/generators/migration_generator_test.rb
+++ b/railties/test/generators/migration_generator_test.rb
@@ -85,6 +85,19 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_remove_migration_with_references_removes_foreign_keys
+ migration = "remove_references_from_books"
+ run_generator [migration, "author:belongs_to", "distributor:references{polymorphic}"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/remove_reference :books, :author,.*\sforeign_key: true/, change)
+ assert_match(/remove_reference :books, :distributor/, change) # sanity check
+ assert_no_match(/remove_reference :books, :distributor,.*\sforeign_key: true/, change)
+ end
+ end
+ end
+
def test_add_migration_with_attributes_and_indices
migration = "add_title_with_index_and_body_to_posts"
run_generator [migration, "title:string:index", "body:text", "user_id:integer:uniq"]
@@ -159,6 +172,31 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_add_migration_with_required_references
+ migration = "add_references_to_books"
+ run_generator [migration, "author:belongs_to{required}", "distributor:references{polymorphic,required}"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/add_reference :books, :author, index: true, null: false/, change)
+ assert_match(/add_reference :books, :distributor, polymorphic: true, index: true, null: false/, change)
+ end
+ end
+ end
+
+ def test_add_migration_with_references_adds_foreign_keys
+ migration = "add_references_to_books"
+ run_generator [migration, "author:belongs_to", "distributor:references{polymorphic}"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/add_reference :books, :author,.*\sforeign_key: true/, change)
+ assert_match(/add_reference :books, :distributor/, change) # sanity check
+ assert_no_match(/add_reference :books, :distributor,.*\sforeign_key: true/, change)
+ end
+ end
+ end
+
def test_create_join_table_migration
migration = "add_media_join_table"
run_generator [migration, "artist_id", "musics:uniq"]
@@ -193,7 +231,7 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
end
end
end
-
+
def test_properly_identifies_usage_file
assert generator_class.send(:usage_path)
end
diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb
index b67cf02d7b..afee0a655d 100644
--- a/railties/test/generators/model_generator_test.rb
+++ b/railties/test/generators/model_generator_test.rb
@@ -1,5 +1,6 @@
require 'generators/generators_test_helper'
require 'rails/generators/rails/model/model_generator'
+require 'active_support/core_ext/string/strip'
class ModelGeneratorTest < Rails::Generators::TestCase
include GeneratorsTestHelper
@@ -222,7 +223,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
def test_migration_with_timestamps
run_generator
- assert_migration "db/migrate/create_accounts.rb", /t.timestamps/
+ assert_migration "db/migrate/create_accounts.rb", /t.timestamps null: false/
end
def test_migration_timestamps_are_skipped
@@ -286,18 +287,18 @@ class ModelGeneratorTest < Rails::Generators::TestCase
def test_fixtures_use_the_references_ids
run_generator ["LineItem", "product:references", "cart:belongs_to"]
- assert_file "test/fixtures/line_items.yml", /product_id: \n cart_id: /
+ assert_file "test/fixtures/line_items.yml", /product: \n cart: /
assert_generated_fixture("test/fixtures/line_items.yml",
- {"one"=>{"product_id"=>nil, "cart_id"=>nil}, "two"=>{"product_id"=>nil, "cart_id"=>nil}})
+ {"one"=>{"product"=>nil, "cart"=>nil}, "two"=>{"product"=>nil, "cart"=>nil}})
end
def test_fixtures_use_the_references_ids_and_type
run_generator ["LineItem", "product:references{polymorphic}", "cart:belongs_to"]
- assert_file "test/fixtures/line_items.yml", /product_id: \n product_type: Product\n cart_id: /
+ assert_file "test/fixtures/line_items.yml", /product: \n product_type: Product\n cart: /
assert_generated_fixture("test/fixtures/line_items.yml",
- {"one"=>{"product_id"=>nil, "product_type"=>"Product", "cart_id"=>nil},
- "two"=>{"product_id"=>nil, "product_type"=>"Product", "cart_id"=>nil}})
+ {"one"=>{"product"=>nil, "product_type"=>"Product", "cart"=>nil},
+ "two"=>{"product"=>nil, "product_type"=>"Product", "cart"=>nil}})
end
def test_fixtures_respect_reserved_yml_keywords
@@ -363,6 +364,80 @@ class ModelGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_required_belongs_to_adds_required_association
+ run_generator ["account", "supplier:references{required}"]
+
+ expected_file = <<-FILE.strip_heredoc
+ class Account < ActiveRecord::Base
+ belongs_to :supplier, required: true
+ end
+ FILE
+ assert_file "app/models/account.rb", expected_file
+ end
+
+ def test_required_polymorphic_belongs_to_generages_correct_model
+ run_generator ["account", "supplier:references{required,polymorphic}"]
+
+ expected_file = <<-FILE.strip_heredoc
+ class Account < ActiveRecord::Base
+ belongs_to :supplier, polymorphic: true, required: true
+ end
+ FILE
+ assert_file "app/models/account.rb", expected_file
+ end
+
+ def test_required_and_polymorphic_are_order_independent
+ run_generator ["account", "supplier:references{polymorphic.required}"]
+
+ expected_file = <<-FILE.strip_heredoc
+ class Account < ActiveRecord::Base
+ belongs_to :supplier, polymorphic: true, required: true
+ end
+ FILE
+ assert_file "app/models/account.rb", expected_file
+ end
+
+ def test_required_adds_null_false_to_column
+ run_generator ["account", "supplier:references{required}"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/t\.references :supplier,.*\snull: false/, up)
+ end
+ end
+ end
+
+ def test_foreign_key_is_not_added_for_non_references
+ run_generator ["account", "supplier:string"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_no_match(/foreign_key/, up)
+ end
+ end
+ end
+
+ def test_foreign_key_is_added_for_references
+ run_generator ["account", "supplier:belongs_to", "user:references"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/t\.belongs_to :supplier,.*\sforeign_key: true/, up)
+ assert_match(/t\.references :user,.*\sforeign_key: true/, up)
+ end
+ end
+ end
+
+ def test_foreign_key_is_skipped_for_polymorphic_references
+ run_generator ["account", "supplier:belongs_to{polymorphic}"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_no_match(/foreign_key/, up)
+ end
+ end
+ end
+
private
def assert_generated_fixture(path, parsed_contents)
fixture_file = File.new File.expand_path(path, destination_root)
diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb
index d677c21f15..6075805152 100644
--- a/railties/test/generators/namespaced_generators_test.rb
+++ b/railties/test/generators/namespaced_generators_test.rb
@@ -47,7 +47,6 @@ class NamespacedControllerGeneratorTest < NamespacedGeneratorTestCase
def test_helper_is_also_namespaced
run_generator
assert_file "app/helpers/test_app/account_helper.rb", /module TestApp/, / module AccountHelper/
- assert_file "test/helpers/test_app/account_helper_test.rb", /module TestApp/, / class AccountHelperTest/
end
def test_invokes_default_test_framework
@@ -149,8 +148,8 @@ class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase
run_generator
assert_file "app/mailers/test_app/notifier.rb" do |mailer|
assert_match(/module TestApp/, mailer)
- assert_match(/class Notifier < ActionMailer::Base/, mailer)
- assert_match(/default from: "from@example.com"/, mailer)
+ assert_match(/class Notifier < ApplicationMailer/, mailer)
+ assert_no_match(/default from: "from@example.com"/, mailer)
end
end
@@ -229,7 +228,6 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
# Helpers
assert_file "app/helpers/test_app/product_lines_helper.rb"
- assert_file "test/helpers/test_app/product_lines_helper_test.rb"
# Stylesheets
assert_file "app/assets/stylesheets/scaffold.css"
@@ -260,7 +258,6 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
# Helpers
assert_no_file "app/helpers/test_app/product_lines_helper.rb"
- assert_no_file "test/helpers/test_app/product_lines_helper_test.rb"
# Stylesheets (should not be removed)
assert_file "app/assets/stylesheets/scaffold.css"
@@ -297,7 +294,6 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
# Helpers
assert_file "app/helpers/test_app/admin/roles_helper.rb"
- assert_file "test/helpers/test_app/admin/roles_helper_test.rb"
# Stylesheets
assert_file "app/assets/stylesheets/scaffold.css"
@@ -329,7 +325,6 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
# Helpers
assert_no_file "app/helpers/test_app/admin/roles_helper.rb"
- assert_no_file "test/helpers/test_app/admin/roles_helper_test.rb"
# Stylesheets (should not be removed)
assert_file "app/assets/stylesheets/scaffold.css"
@@ -366,7 +361,6 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
# Helpers
assert_file "app/helpers/test_app/admin/user/special/roles_helper.rb"
- assert_file "test/helpers/test_app/admin/user/special/roles_helper_test.rb"
# Stylesheets
assert_file "app/assets/stylesheets/scaffold.css"
@@ -397,7 +391,6 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
# Helpers
assert_no_file "app/helpers/test_app/admin/user/special/roles_helper.rb"
- assert_no_file "test/helpers/test_app/admin/user/special/roles_helper_test.rb"
# Stylesheets (should not be removed)
assert_file "app/assets/stylesheets/scaffold.css"
diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb
index 0d01931daa..e9f06a1fd7 100644
--- a/railties/test/generators/plugin_generator_test.rb
+++ b/railties/test/generators/plugin_generator_test.rb
@@ -54,7 +54,11 @@ class PluginGeneratorTest < Rails::Generators::TestCase
run_generator
assert_file "README.rdoc", /Bukkits/
assert_no_file "config/routes.rb"
- assert_file "test/test_helper.rb"
+ assert_file "test/test_helper.rb" do |content|
+ assert_match(/require.+test\/dummy\/config\/environment/, content)
+ assert_match(/ActiveRecord::Migrator\.migrations_paths.+test\/dummy\/db\/migrate/, content)
+ assert_match(/Minitest\.backtrace_filter = Minitest::BacktraceFilter\.new/, content)
+ end
assert_file "test/bukkits_test.rb", /assert_kind_of Module, Bukkits/
end
@@ -67,7 +71,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase
def test_inclusion_of_a_debugger
run_generator [destination_root, '--full']
- if defined?(JRUBY_VERSION)
+ if defined?(JRUBY_VERSION) || RUBY_ENGINE == "rbx"
assert_file "Gemfile" do |content|
assert_no_match(/byebug/, content)
assert_no_match(/debugger/, content)
@@ -95,7 +99,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase
end
def test_generating_adds_dummy_app_without_javascript_and_assets_deps
- run_generator [destination_root]
+ run_generator
assert_file "test/dummy/app/assets/stylesheets/application.css"
@@ -136,6 +140,20 @@ class PluginGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_app_generator_without_skips
+ run_generator
+ assert_file "test/dummy/config/application.rb", /\s+require\s+["']rails\/all["']/
+ assert_file "test/dummy/config/environments/development.rb" do |content|
+ assert_match(/config\.action_mailer\.raise_delivery_errors = false/, content)
+ end
+ assert_file "test/dummy/config/environments/test.rb" do |content|
+ assert_match(/config\.action_mailer\.delivery_method = :test/, content)
+ end
+ assert_file "test/dummy/config/environments/production.rb" do |content|
+ assert_match(/# config\.action_mailer\.raise_delivery_errors = false/, content)
+ end
+ end
+
def test_active_record_is_removed_from_frameworks_if_skip_active_record_is_given
run_generator [destination_root, "--skip-active-record"]
assert_file "test/dummy/config/application.rb", /#\s+require\s+["']active_record\/railtie["']/
@@ -149,6 +167,20 @@ class PluginGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_action_mailer_is_removed_from_frameworks_if_skip_action_mailer_is_given
+ run_generator [destination_root, "--skip-action-mailer"]
+ assert_file "test/dummy/config/application.rb", /#\s+require\s+["']action_mailer\/railtie["']/
+ assert_file "test/dummy/config/environments/development.rb" do |content|
+ assert_no_match(/config\.action_mailer/, content)
+ end
+ assert_file "test/dummy/config/environments/test.rb" do |content|
+ assert_no_match(/config\.action_mailer/, content)
+ end
+ assert_file "test/dummy/config/environments/production.rb" do |content|
+ assert_no_match(/config\.action_mailer/, content)
+ end
+ end
+
def test_ensure_that_database_option_is_passed_to_app_generator
run_generator [destination_root, "--database", "postgresql"]
assert_file "test/dummy/config/database.yml", /postgres/
@@ -242,6 +274,10 @@ class PluginGeneratorTest < Rails::Generators::TestCase
assert_match(/stylesheet_link_tag\s+['"]bukkits\/application['"]/, contents)
assert_match(/javascript_include_tag\s+['"]bukkits\/application['"]/, contents)
end
+ assert_file "test/test_helper.rb" do |content|
+ assert_match(/ActiveRecord::Migrator\.migrations_paths.+\.\.\/test\/dummy\/db\/migrate/, content)
+ assert_match(/ActiveRecord::Migrator\.migrations_paths.+<<.+\.\.\/db\/migrate/, content)
+ end
end
def test_creating_gemspec
@@ -270,6 +306,10 @@ class PluginGeneratorTest < Rails::Generators::TestCase
assert_file "spec/dummy"
assert_file "spec/dummy/config/application.rb"
assert_no_file "test/dummy"
+ assert_file "test/test_helper.rb" do |content|
+ assert_match(/require.+spec\/dummy\/config\/environment/, content)
+ assert_match(/ActiveRecord::Migrator\.migrations_paths.+spec\/dummy\/db\/migrate/, content)
+ end
end
def test_creating_dummy_application_with_different_name
@@ -277,6 +317,10 @@ class PluginGeneratorTest < Rails::Generators::TestCase
assert_file "spec/fake"
assert_file "spec/fake/config/application.rb"
assert_no_file "test/dummy"
+ assert_file "test/test_helper.rb" do |content|
+ assert_match(/require.+spec\/fake\/config\/environment/, content)
+ assert_match(/ActiveRecord::Migrator\.migrations_paths.+spec\/fake\/db\/migrate/, content)
+ end
end
def test_creating_dummy_without_tests_but_with_dummy_path
@@ -284,6 +328,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase
assert_file "spec/dummy"
assert_file "spec/dummy/config/application.rb"
assert_no_file "test"
+ assert_no_file "test/test_helper.rb"
assert_file '.gitignore' do |contents|
assert_match(/spec\/dummy/, contents)
end
@@ -335,7 +380,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase
Object.const_set('APP_PATH', Rails.root)
FileUtils.touch gemfile_path
- run_generator [destination_root]
+ run_generator
assert_file gemfile_path, /gem 'bukkits', path: 'tmp\/bukkits'/
ensure
@@ -376,19 +421,19 @@ class PluginGeneratorTest < Rails::Generators::TestCase
name = `git config user.name`.chomp rescue "TODO: Write your name"
email = `git config user.email`.chomp rescue "TODO: Write your email address"
- run_generator [destination_root]
+ run_generator
assert_file "bukkits.gemspec" do |contents|
- assert_match(/#{Regexp.escape(name)}/, contents)
- assert_match(/#{Regexp.escape(email)}/, contents)
+ assert_match name, contents
+ assert_match email, contents
end
end
def test_git_name_in_license_file
name = `git config user.name`.chomp rescue "TODO: Write your name"
- run_generator [destination_root]
+ run_generator
assert_file "MIT-LICENSE" do |contents|
- assert_match(/#{Regexp.escape(name)}/, contents)
+ assert_match name, contents
end
end
@@ -398,11 +443,11 @@ class PluginGeneratorTest < Rails::Generators::TestCase
run_generator [destination_root, '--skip-git']
assert_file "MIT-LICENSE" do |contents|
- assert_match(/#{Regexp.escape(name)}/, contents)
+ assert_match name, contents
end
assert_file "bukkits.gemspec" do |contents|
- assert_match(/#{Regexp.escape(name)}/, contents)
- assert_match(/#{Regexp.escape(email)}/, contents)
+ assert_match name, contents
+ assert_match email, contents
end
end
@@ -416,10 +461,10 @@ protected
end
def assert_match_sqlite3(contents)
- unless defined?(JRUBY_VERSION)
- assert_match(/group :development do\n gem 'sqlite3'\nend/, contents)
- else
+ if defined?(JRUBY_VERSION)
assert_match(/group :development do\n gem 'activerecord-jdbcsqlite3-adapter'\nend/, contents)
+ else
+ assert_match(/group :development do\n gem 'sqlite3'\nend/, contents)
end
end
end
diff --git a/railties/test/generators/resource_generator_test.rb b/railties/test/generators/resource_generator_test.rb
index dcdff22152..581d80d60e 100644
--- a/railties/test/generators/resource_generator_test.rb
+++ b/railties/test/generators/resource_generator_test.rb
@@ -36,7 +36,6 @@ class ResourceGeneratorTest < Rails::Generators::TestCase
assert_file "test/controllers/accounts_controller_test.rb", /class AccountsControllerTest < ActionController::TestCase/
assert_file "app/helpers/accounts_helper.rb", /module AccountsHelper/
- assert_file "test/helpers/accounts_helper_test.rb", /class AccountsHelperTest < ActionView::TestCase/
end
def test_resource_controller_with_actions
diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb
index 46eacd2845..ca972a3bdd 100644
--- a/railties/test/generators/scaffold_controller_generator_test.rb
+++ b/railties/test/generators/scaffold_controller_generator_test.rb
@@ -81,7 +81,6 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
def test_helper_are_invoked_with_a_pluralized_name
run_generator
assert_file "app/helpers/users_helper.rb", /module UsersHelper/
- assert_file "test/helpers/users_helper_test.rb", /class UsersHelperTest < ActionView::TestCase/
end
def test_views_are_generated
@@ -126,7 +125,6 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
def test_skip_helper_if_required
run_generator ["User", "name:string", "age:integer", "--no-helper"]
assert_no_file "app/helpers/users_helper.rb"
- assert_no_file "test/helpers/users_helper_test.rb"
end
def test_skip_layout_if_required
diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb
index c44ce32122..ad365f45d0 100644
--- a/railties/test/generators/scaffold_generator_test.rb
+++ b/railties/test/generators/scaffold_generator_test.rb
@@ -81,7 +81,6 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
# Helpers
assert_file "app/helpers/product_lines_helper.rb"
- assert_file "test/helpers/product_lines_helper_test.rb"
# Assets
assert_file "app/assets/stylesheets/scaffold.css"
@@ -125,7 +124,6 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
# Helpers
assert_no_file "app/helpers/product_lines_helper.rb"
- assert_no_file "test/helpers/product_lines_helper_test.rb"
# Assets
assert_file "app/assets/stylesheets/scaffold.css", /:visited/
@@ -193,7 +191,6 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
# Helpers
assert_file "app/helpers/admin/roles_helper.rb"
- assert_file "test/helpers/admin/roles_helper_test.rb"
# Assets
assert_file "app/assets/stylesheets/scaffold.css", /:visited/
@@ -227,7 +224,6 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
# Helpers
assert_no_file "app/helpers/admin/roles_helper.rb"
- assert_no_file "test/helpers/admin/roles_helper_test.rb"
# Assets
assert_file "app/assets/stylesheets/scaffold.css"
@@ -264,13 +260,27 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
assert_no_file "app/assets/stylesheets/posts.css"
end
- def test_scaffold_generator_no_assets_with_switch_resource_route_false
+ def test_scaffold_generator_with_switch_resource_route_false
run_generator [ "posts", "--resource-route=false" ]
assert_file "config/routes.rb" do |route|
assert_no_match(/resources :posts$/, route)
end
end
+ def test_scaffold_generator_no_helper_with_switch_no_helper
+ output = run_generator [ "posts", "--no-helper" ]
+
+ assert_no_match(/error/, output)
+ assert_no_file "app/helpers/posts_helper.rb"
+ end
+
+ def test_scaffold_generator_no_helper_with_switch_helper_false
+ output = run_generator [ "posts", "--helper=false" ]
+
+ assert_no_match(/error/, output)
+ assert_no_file "app/helpers/posts_helper.rb"
+ end
+
def test_scaffold_generator_no_stylesheets
run_generator [ "posts", "--no-stylesheets" ]
assert_no_file "app/assets/stylesheets/scaffold.css"
diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb
index b5765c391e..127e059bf1 100644
--- a/railties/test/generators_test.rb
+++ b/railties/test/generators_test.rb
@@ -152,6 +152,8 @@ class GeneratorsTest < Rails::Generators::TestCase
klass = Rails::Generators.find_by_namespace(:plugin, :remarkable)
assert klass
assert_equal "test_unit:plugin", klass.namespace
+ ensure
+ Rails::Generators.fallbacks.delete(:remarkable)
end
def test_fallbacks_for_generators_on_find_by_namespace_with_context
@@ -159,18 +161,26 @@ class GeneratorsTest < Rails::Generators::TestCase
klass = Rails::Generators.find_by_namespace(:remarkable, :rails, :plugin)
assert klass
assert_equal "test_unit:plugin", klass.namespace
+ ensure
+ Rails::Generators.fallbacks.delete(:remarkable)
end
def test_fallbacks_for_generators_on_invoke
Rails::Generators.fallbacks[:shoulda] = :test_unit
TestUnit::Generators::ModelGenerator.expects(:start).with(["Account"], {})
Rails::Generators.invoke "shoulda:model", ["Account"]
+ ensure
+ Rails::Generators.fallbacks.delete(:shoulda)
end
def test_nested_fallbacks_for_generators
+ Rails::Generators.fallbacks[:shoulda] = :test_unit
Rails::Generators.fallbacks[:super_shoulda] = :shoulda
TestUnit::Generators::ModelGenerator.expects(:start).with(["Account"], {})
Rails::Generators.invoke "super_shoulda:model", ["Account"]
+ ensure
+ Rails::Generators.fallbacks.delete(:shoulda)
+ Rails::Generators.fallbacks.delete(:super_shoulda)
end
def test_developer_options_are_overwritten_by_user_options
diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb
index 92d6a1729c..9ad0ec0d34 100644
--- a/railties/test/isolation/abstract_unit.rb
+++ b/railties/test/isolation/abstract_unit.rb
@@ -9,6 +9,7 @@
require 'fileutils'
require 'bundler/setup' unless defined?(Bundler)
+require 'active_support'
require 'active_support/testing/autorun'
require 'active_support/test_case'
@@ -140,7 +141,9 @@ module TestHelpers
config.eager_load = false
config.session_store :cookie_store, key: "_myapp_session"
config.active_support.deprecation = :log
+ config.active_support.test_order = :random
config.action_controller.allow_forgery_protection = false
+ config.log_level = :info
RUBY
end
@@ -160,6 +163,8 @@ module TestHelpers
app.secrets.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4"
app.config.session_store :cookie_store, key: "_myapp_session"
app.config.active_support.deprecation = :log
+ app.config.active_support.test_order = :random
+ app.config.log_level = :info
yield app if block_given?
app.initialize!
@@ -229,6 +234,15 @@ module TestHelpers
end
end
+ def add_to_top_of_config(str)
+ environment = File.read("#{app_path}/config/application.rb")
+ if environment =~ /(Rails::Application\s*)/
+ File.open("#{app_path}/config/application.rb", 'w') do |f|
+ f.puts $` + $1 + "\n#{str}\n" + $'
+ end
+ end
+ end
+
def add_to_config(str)
environment = File.read("#{app_path}/config/application.rb")
if environment =~ /(\n\s*end\s*end\s*)\Z/
@@ -276,8 +290,12 @@ module TestHelpers
end
def use_frameworks(arr)
- to_remove = [:actionmailer,
- :activerecord] - arr
+ to_remove = [:actionmailer, :activerecord] - arr
+
+ if to_remove.include?(:activerecord)
+ remove_from_config 'config.active_record.*'
+ end
+
$:.reject! {|path| path =~ %r'/(#{to_remove.join('|')})/' }
end
@@ -292,6 +310,8 @@ class ActiveSupport::TestCase
include TestHelpers::Rack
include TestHelpers::Generation
+ self.test_order = :sorted
+
private
def capture(stream)
diff --git a/railties/test/path_generation_test.rb b/railties/test/path_generation_test.rb
new file mode 100644
index 0000000000..13bf29d3c3
--- /dev/null
+++ b/railties/test/path_generation_test.rb
@@ -0,0 +1,88 @@
+# encoding: utf-8
+require 'abstract_unit'
+require 'active_support/core_ext/object/with_options'
+require 'active_support/core_ext/object/json'
+require 'rails'
+require 'rails/application'
+
+ROUTING = ActionDispatch::Routing
+
+class PathGenerationTest < ActiveSupport::TestCase
+ attr_reader :app
+
+ class TestSet < ROUTING::RouteSet
+ def initialize(block)
+ @block = block
+ super()
+ end
+
+ class Dispatcher < ROUTING::RouteSet::Dispatcher
+ def initialize(defaults, set, block)
+ super(defaults)
+ @block = block
+ @set = set
+ end
+
+ def controller_reference(controller_param)
+ block = @block
+ set = @set
+ Class.new(ActionController::Base) {
+ include set.url_helpers
+ define_method(:process) { |name| block.call(self) }
+ def to_a; [200, {}, []]; end
+ }
+ end
+ end
+
+ def dispatcher defaults
+ TestSet::Dispatcher.new defaults, self, @block
+ end
+ end
+
+ def send_request(uri_or_host, method, path, script_name = nil)
+ host = uri_or_host.host unless path
+ path ||= uri_or_host.path
+
+ params = {'PATH_INFO' => path,
+ 'REQUEST_METHOD' => method,
+ 'HTTP_HOST' => host }
+
+ params['SCRIPT_NAME'] = script_name if script_name
+
+ status, headers, body = app.call(params)
+ new_body = []
+ body.each { |part| new_body << part }
+ body.close if body.respond_to? :close
+ [status, headers, new_body]
+ end
+
+ def test_original_script_name
+ original_logger = Rails.logger
+ Rails.logger = Logger.new nil
+
+ app = Class.new(Rails::Application) {
+ attr_accessor :controller
+ def initialize
+ super
+ app = self
+ @routes = TestSet.new ->(c) { app.controller = c }
+ secrets.secret_key_base = "foo"
+ secrets.secret_token = "foo"
+ end
+ def app; routes; end
+ }
+
+ @app = app
+ app.routes.draw { resource :blogs }
+
+ url = URI("http://example.org/blogs")
+
+ send_request(url, 'GET', nil, '/FOO')
+ assert_equal '/FOO/blogs', app.instance.controller.blogs_path
+
+ send_request(url, 'GET', nil)
+ assert_equal '/blogs', app.instance.controller.blogs_path
+ ensure
+ Rails.logger = original_logger
+ end
+end
diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb
index 8d61af4972..d336a2e6c0 100644
--- a/railties/test/rails_info_controller_test.rb
+++ b/railties/test/rails_info_controller_test.rb
@@ -1,5 +1,4 @@
require 'abstract_unit'
-require 'mocha/setup' # FIXME: stop using mocha
module ActionController
class Base
@@ -15,26 +14,26 @@ class InfoControllerTest < ActionController::TestCase
get '/rails/info/properties' => "rails/info#properties"
get '/rails/info/routes' => "rails/info#routes"
end
- @controller.stubs(:local_request? => true)
@routes = Rails.application.routes
Rails::InfoController.send(:include, @routes.url_helpers)
+
+ @request.env["REMOTE_ADDR"] = "127.0.0.1"
end
test "info controller does not allow remote requests" do
- @controller.stubs(local_request?: false)
+ @request.env["REMOTE_ADDR"] = "example.org"
get :properties
assert_response :forbidden
end
test "info controller renders an error message when request was forbidden" do
- @controller.stubs(local_request?: false)
+ @request.env["REMOTE_ADDR"] = "example.org"
get :properties
assert_select 'p'
end
test "info controller allows requests when all requests are considered local" do
- @controller.stubs(local_request?: true)
get :properties
assert_response :success
end
diff --git a/railties/test/rails_info_test.rb b/railties/test/rails_info_test.rb
index 4bec302ff8..92e4af25b5 100644
--- a/railties/test/rails_info_test.rb
+++ b/railties/test/rails_info_test.rb
@@ -38,21 +38,10 @@ class InfoTest < ActiveSupport::TestCase
end
def test_rails_version
- assert_property 'Rails version',
+ assert_property 'Rails version',
File.read(File.realpath('../../../RAILS_VERSION', __FILE__)).chomp
end
- def test_framework_version
- assert_property 'Active Support version', ActiveSupport.version.to_s
- end
-
- def test_frameworks_exist
- Rails::Info.frameworks.each do |framework|
- dir = File.dirname(__FILE__) + "/../../" + framework.delete('_')
- assert File.directory?(dir), "#{framework.classify} does not exist"
- end
- end
-
def test_html_includes_middleware
Rails::Info.module_eval do
property 'Middleware', ['Rack::Lock', 'Rack::Static']
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index ec64ce5941..4ffcf64275 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -144,6 +144,42 @@ module RailtiesTest
end
end
+ test "dont reverse default railties order" do
+ @api = engine "api" do |plugin|
+ plugin.write "lib/api.rb", <<-RUBY
+ module Api
+ class Engine < ::Rails::Engine; end
+ end
+ RUBY
+ end
+
+ # added last but here is loaded before api engine
+ @core = engine "core" do |plugin|
+ plugin.write "lib/core.rb", <<-RUBY
+ module Core
+ class Engine < ::Rails::Engine; end
+ end
+ RUBY
+ end
+
+ @core.write "db/migrate/1_create_users.rb", <<-RUBY
+ class CreateUsers < ActiveRecord::Migration; end
+ RUBY
+
+ @api.write "db/migrate/2_create_keys.rb", <<-RUBY
+ class CreateKeys < ActiveRecord::Migration; end
+ RUBY
+
+ boot_rails
+
+ Dir.chdir(app_path) do
+ output = `bundle exec rake railties:install:migrations`.split("\n")
+
+ assert_match(/Copied migration \d+_create_users.core_engine.rb from core_engine/, output.first)
+ assert_match(/Copied migration \d+_create_keys.api_engine.rb from api_engine/, output.last)
+ end
+ end
+
test "mountable engine should copy migrations within engine_path" do
@plugin.write "lib/bukkits.rb", <<-RUBY
module Bukkits
@@ -462,17 +498,12 @@ YAML
boot_rails
initializers = Rails.application.initializers.tsort
- index = initializers.index { |i| i.name == "dummy_initializer" }
- selection = initializers[(index-3)..(index)].map(&:name).map(&:to_s)
-
- assert_equal %w(
- load_config_initializers
- load_config_initializers
- engines_blank_point
- dummy_initializer
- ), selection
+ dummy_index = initializers.index { |i| i.name == "dummy_initializer" }
+ config_index = initializers.rindex { |i| i.name == :load_config_initializers }
+ stack_index = initializers.index { |i| i.name == :build_middleware_stack }
- assert index < initializers.index { |i| i.name == :build_middleware_stack }
+ assert config_index < dummy_index
+ assert dummy_index < stack_index
end
class Upcaser
@@ -482,12 +513,12 @@ YAML
def call(env)
response = @app.call(env)
- response[2].each { |b| b.upcase! }
+ response[2].each(&:upcase!)
response
end
end
- test "engine is a rack app and can have his own middleware stack" do
+ test "engine is a rack app and can have its own middleware stack" do
add_to_config("config.action_dispatch.show_exceptions = false")
@plugin.write "lib/bukkits.rb", <<-RUBY
@@ -1174,7 +1205,7 @@ YAML
test "engine can be properly mounted at root" do
add_to_config("config.action_dispatch.show_exceptions = false")
- add_to_config("config.serve_static_assets = false")
+ add_to_config("config.serve_static_files = false")
@plugin.write "lib/bukkits.rb", <<-RUBY
module Bukkits