diff options
Diffstat (limited to 'railties')
277 files changed, 4759 insertions, 4630 deletions
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md index ed3a3e8527..b488e4ed8e 100644 --- a/railties/CHANGELOG.md +++ b/railties/CHANGELOG.md @@ -1,524 +1,67 @@ -## Rails 5.0.0.beta4 (April 27, 2016) ## +* Allow the use of listen's 3.1.x branch -* Add `config/initializers/to_time_preserves_timezone.rb`, which tells - Active Support to preserve the receiver's timezone when calling `to_time`. - This matches the new behavior that will be part of Ruby 2.4. + *Esteban Santana Santana* - Fixes #24617. +* Run `Minitest.after_run` hooks when running `rails test`. - *Andrew White* + *Michael Grosser* -* Make `rails restart` command work with Puma by passing the restart command - which Puma can use to restart rails server. +* Run `before_configuration` callbacks as soon as application constant + inherits from `Rails::Application`. - *Prathamesh Sonpatki* - -* The application generator writes a new file `config/spring.rb`, which tells - Spring to watch additional common files. - - *Xavier Noria* - -* The tasks in the rails task namespace is deprecated in favor of app namespace. - (e.g. `rails:update` and `rails:template` tasks is renamed to `app:update` and `app:template`.) - - *Ryo Hashimoto* - -* Enable HSTS with IncludeSudomains header for new applications. - - *Egor Homakov*, *Prathamesh Sonpatki* - -## Rails 5.0.0.beta3 (February 24, 2016) ## - -* Alias `rake` with `rails_command` in the Rails Application Templates API - following Rails 5 convention of preferring "rails" to "rake" to run tasks. - - *claudiob* - -* Generate applications with an option to log to STDOUT in production - using the environment variable `RAILS_LOG_TO_STDOUT`. - - *Richard Schneeman* - -* Change fail fast of `bin/rails test` interrupts run on error. - - *Yuji Yaginuma* - -* The application generator supports `--skip-listen` to opt-out of features - that depend on the listen gem. As of this writing they are the evented file - system monitor and the async plugin for spring. - -* The Gemfiles of new applications include spring-watcher-listen on Linux and - Mac OS X (unless `--skip-spring`). - - *Xavier Noria* - -* New applications are generated with the evented file system monitor enabled - on Linux and Mac OS X. - - *Xavier Noria* - -* Add dummy files for apple-touch-icon.png and apple-touch-icon.png. - - See #23427. - - *Alexey Zabelin* - -## Rails 5.0.0.beta2 (February 01, 2016) ## - -* Add `after_bundle` callbacks in Rails plugin templates. Useful for allowing - templates to perform actions that are dependent upon `bundle install`. - - *Ryan Manuel* - -* Bring back `TEST=` env for `rake test` task. - - *Yves Senn* - -* Specify log file names or all logs to clear `rake log:clear` - - Specify which logs to clear when using the `rake log:clear` task, e.g. `rake log:clear LOGS=test,staging` - - Clear all logs from log/*.log e.g. `rake log:clear LOGS=all` - - By default `rake log:clear` clears standard environment log files i.e. 'development,test,production' - - *Pramod Shinde* - -* Fix using `add_source` with a block after using `gem` in a custom generator. - - *Will Fisher* - - -## Rails 5.0.0.beta1 (December 18, 2015) ## - -* Newly generated plugins get a `README.md` in Markdown. - - *Yuji Yaginuma* - -* The generated config file for the development environment includes a new - config line, commented out, showing how to enable the evented file watcher. - - *Xavier Noria* - -* `config.debug_exception_response_format` configures the format used - in responses when errors occur in development mode. - - Set `config.debug_exception_response_format` to render an HTML page with - debug info (using the value `:default`) or render debug info preserving - the response format (using the value `:api`). - - *Jorge Bejar* - -* Fix setting exit status code for rake test tasks. The exit status code - was not set when tests were fired with `rake`. Now, it is being set and it matches - behavior of running tests via `rails` command (`rails test`), so no matter if - `rake test` or `rails test` command is used the exit code will be set. - - *Arkadiusz Fal* - -* Add Command infrastructure to replace rake. - - Also move `rake dev:cache` to new infrastructure. You'll need to use - `rails dev:cache` to toggle development caching from now on. - - *Chuck Callebs* - -* Allow use of `minitest-rails` gem with Rails test runner. - - Fixes #22455. - - *Chris Kottom* - -* Add `bin/test` script to rails plugin. - - `bin/test` can use the same API as `bin/rails test`. - - *Yuji Yaginuma* - -* Make `static_index` part of the `config.public_file_server` config and - call it `config.public_file_server.index_name`. - - *Yuki Nishijima* - -* Deprecate `config.serve_static_files` in favor of `config.public_file_server.enabled`. - - Unifies the static asset options under `config.public_file_server`. - - To upgrade, replace occurrences of: - - ``` - config.serve_static_files = # false or true - ``` - - in your environment files, with: - - ``` - config.public_file_server.enabled = # false or true - ``` - - *Kasper Timm Hansen* - -* Deprecate `config.static_cache_control` in favor of - `config.public_file_server.headers`. - - To upgrade, replace occurrences of: - - ``` - config.static_cache_control = 'public, max-age=60' - ``` - - in your environment files, with: - - ``` - config.public_file_server.headers = { - 'Cache-Control' => 'public, max-age=60' - } - ``` - - `config.public_file_server.headers` can set arbitrary headers, sent along when - a response is delivered. - - *Yuki Nishijima* - -* Route generators are now idempotent. - Running generators several times no longer require you to cleanup routes.rb. - - *Thiago Pinto* - -* Allow passing an environment to `config_for`. - - *Simon Eskildsen* - -* Allow `rake stats` to account for rake tasks in lib/tasks. - - *Kevin Deisz* - -* Added javascript to update the URL on mailer previews with the currently - selected email format. Reloading the page now keeps you on your selected - format rather than going back to the default html version. - - *James Kerr* - -* Add fail fast to `bin/rails test`. - - Adding `--fail-fast` or `-f` when running tests will interrupt the run on - the first failure: - - ``` - # Running: - - ................................................S......E - - ArgumentError: Wups! Bet you didn't expect this! - test/models/bunny_test.rb:19:in `block in <class:BunnyTest>' - - bin/rails test test/models/bunny_test.rb:18 - - ....................................F - - This failed - - bin/rails test test/models/bunny_test.rb:14 - - Interrupted. Exiting... - - - Finished in 0.051427s, 1808.3872 runs/s, 1769.4972 assertions/s. - - ``` - - Note that any unexpected errors don't abort the run. - - *Kasper Timm Hansen* - -* Add inline output to `bin/rails test`. - - Any failures or errors (and skips if running in verbose mode) are output - during a test run: - - ``` - # Running: - - .....S..........................................F - - This failed - - bin/rails test test/models/bunny_test.rb:14 - - .................................E - - ArgumentError: Wups! Bet you didn't expect this! - test/models/bunny_test.rb:19:in `block in <class:BunnyTest>' - - bin/rails test test/models/bunny_test.rb:18 - - .................... - - Finished in 0.069708s, 1477.6019 runs/s, 1448.9106 assertions/s. - ``` - - Output can be deferred to after a run with the `--defer-output` option. - - *Kasper Timm Hansen* - -* Fix displaying mailer previews on non local requests when config - `config.action_mailer.show_previews` is set. - - *Wojciech Wnętrzak* - -* `rails server` will now honour the `PORT` environment variable - - *David Cornu* - -* Plugins generated using `rails plugin new` are now generated with the - version number set to 0.1.0. - - *Daniel Morris* - -* `I18n.load_path` is now reloaded under development so there's no need to - restart the server to make new locale files available. Also, I18n will no - longer raise for deleted locale files. - - *Kir Shatrov* - -* Add `bin/update` script to update development environment automatically. - - *Mehmet Emin İNAÇ* - -* Fix STATS_DIRECTORIES already defined warning when running rake from within - the top level directory of an engine that has a test app. - - Fixes #20510. - - *Ersin Akinci* - -* Make enabling or disabling caching in development mode possible with - `rake dev:cache`. - - Running `rake dev:cache` will create or remove tmp/caching-dev.txt. When this - file exists `config.action_controller.perform_caching` will be set to true in - config/environments/development.rb. - - Additionally, a server can be started with either `--dev-caching` or - `--no-dev-caching` included to toggle caching on startup. - - *Jussi Mertanen*, *Chuck Callebs* - -* Add a `--api` option in order to generate plugins that can be added - inside an API application. - - *Robin Dupret* - -* Fix `NoMethodError` when generating a scaffold inside a full engine. + Fixes #19880. *Yuji Yaginuma* -* Adding support for passing a block to the `add_source` action of a custom generator. - - *Mike Dalton*, *Hirofumi Wakasugi* - -* `assert_file` now understands paths with special characters - (eg. `v0.1.4~alpha+nightly`). - - *Diego Carrion* - -* Remove ContentLength middleware from the defaults. If you want it, just - add it as a middleware in your config. - - *Egg McMuffin* - -* Make it possible to customize the executable inside rerun snippets. - - *Yves Senn* - -* Add support for API only apps. - Middleware stack was slimmed down and it has only the needed - middleware for API apps & generators generates the right files, - folders and configurations. - - *Santiago Pastorino*, *Jorge Bejar* - -* Make generated scaffold functional tests work inside engines. - - *Yuji Yaginuma* - -* Generate a `.keep` file in the `tmp` folder by default as many scripts - assume the existence of this folder and most would fail if it is absent. - - See #20299. - - *Yoong Kang Lim*, *Sunny Juneja* - -* `config.static_index` configures directory `index.html` filename - - Set `config.static_index` to serve a static directory index file not named - `index`. E.g. to serve `main.html` instead of `index.html` for directory - requests, set `config.static_index` to `"main"`. - - *Eliot Sykes* - -* `bin/setup` uses built-in rake tasks (`log:clear`, `tmp:clear`). - - *Mohnish Thallavajhula* - -* Fix mailer previews with attachments by using the mail gem's own API to - locate the first part of the correct mime type. - - Fixes #14435. - - *Andrew White* +* A generated app should not include Uglifier with `--skip-javascript` option. -* Remove sqlite support from `rails dbconsole`. + *Ben Pickles* - *Andrew White* +* Set session store to cookie store internally and remove the initializer from + the generated app. -* Rename `railties/bin` to `railties/exe` to match the new Bundler executables - convention. - - *Islam Wazery* - -* Print `bundle install` output in `rails new` as soon as it's available. - - Running `rails new` will now print the output of `bundle install` as - it is available, instead of waiting until all gems finish installing. - - *Max Holder* - -* Respect `pluralize_table_names` when generating fixture file. - - Fixes #19519. - - *Yuji Yaginuma* - -* Add a new-line to the end of route method generated code. - - We need to add a `\n`, because we cannot have two routes - in the same line. - - *arthurnn* - -* Add `rake initializers`. - - This task prints out all defined initializers in the order they are invoked - by Rails. This is helpful for debugging issues related to the initialization - process. - - *Naoto Kaneko* - -* Created rake restart task. Restarts your Rails app by touching the - `tmp/restart.txt`. - - See #18876. - - *Hyonjee Joo* - -* Add `config/initializers/active_record_belongs_to_required_by_default.rb`. - - Newly generated Rails apps have a new initializer called - `active_record_belongs_to_required_by_default.rb` which sets the value of - the configuration option `config.active_record.belongs_to_required_by_default` - to `true` when ActiveRecord is not skipped. - - As a result, new Rails apps require `belongs_to` association on model - to be valid. - - This initializer is *not* added when running `rake rails:update`, so - old apps ported to Rails 5 will work without any change. - - *Josef Šimánek* - -* `delete` operations in configurations are run last in order to eliminate - 'No such middleware' errors when `insert_before` or `insert_after` are added - after the `delete` operation for the middleware being deleted. - - Fixes #16433. - - *Guo Xiang Tan* - -* Newly generated applications get a `README.md` in Markdown. - - *Xavier Noria* - -* Remove the documentation tasks `doc:app`, `doc:rails`, and `doc:guides`. - - *Xavier Noria* - -* Force generated routes to be inserted into `config/routes.rb`. - - *Andrew White* - -* Don't remove all line endings from `config/routes.rb` when revoking scaffold. - - Fixes #15913. - - *Andrew White* - -* Rename `--skip-test-unit` option to `--skip-test` in app generator - - *Melanie Gilman* - -* Add the `method_source` gem to the default Gemfile for apps. - - *Sean Griffin* - -* Drop old test locations from `rake stats`: + *Prathamesh Sonpatki* - - test/functional - - test/unit +* Set the server host using the `HOST` environment variable. - *Ravil Bayramgalin* + *mahnunchik* -* Update `rake stats` to correctly count declarative tests - as methods in `_test.rb` files. +* Add public API to register new folders for `rake notes`: - *Ravil Bayramgalin* + config.annotations.register_directories('spec', 'features') -* Remove deprecated `test:all` and `test:all:db` tasks. + *John Meehan* - *Rafael Mendonça França* +* Display name of the class defining the initializer along with the initializer + name in the output of `rails initializers`. -* Remove deprecated `Rails::Rack::LogTailer`. + Before: + disable_dependency_loading - *Rafael Mendonça França* + After: + DemoApp::Application.disable_dependency_loading -* Remove deprecated `RAILS_CACHE` constant. + *ta1kt0me* - *Rafael Mendonça França* +* Do not run `bundle install` when generating a new plugin. -* Remove deprecated `serve_static_assets` configuration. + Since bundler 1.12.0, the gemspec is validated so the `bundle install` + command will fail just after the gem is created causing confusion to the + users. This change was a bug fix to correctly validate gemspecs. *Rafael Mendonça França* -* Use local variables in `_form.html.erb` partial generated by scaffold. - - *Andrew Kozlov* - -* Add `config/initializers/callback_terminator.rb`. - - Newly generated Rails apps have a new initializer called - `callback_terminator.rb` which sets the value of the configuration option - `ActiveSupport.halt_callback_chains_on_return_false` to `false`. - - As a result, new Rails apps do not halt Active Record and Active Model - callback chains when a callback returns `false`; only when they are - explicitly halted with `throw(:abort)`. - - 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. - - *claudiob* - -* Generated fixtures won't use the id when generated with references attributes. +* Default `config.assets.quiet = true` in the development environment. Suppress + logging of assets requests by default. - *Pablo Olmos de Aguilera Corradini* + *Kevin McPhillips* -* Add `--skip-action-mailer` option to the app generator. +* Ensure `/rails/info` routes match in development for apps with a catch-all globbing route. - *claudiob* + *Nicholas Firth-McCoy* -* Autoload any second level directories called `app/*/concerns`. +* Added a shared section to `config/secrets.yml` that will be loaded for all environments. - *Alex Robbin* + *DHH* -Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/railties/CHANGELOG.md) for previous changes. +Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/railties/CHANGELOG.md) for previous changes. diff --git a/railties/RDOC_MAIN.rdoc b/railties/RDOC_MAIN.rdoc index 26a25ee9dc..ef9bbf3d7e 100644 --- a/railties/RDOC_MAIN.rdoc +++ b/railties/RDOC_MAIN.rdoc @@ -35,17 +35,17 @@ can read more about Action Pack in its {README}[link:files/actionpack/README_rdo 1. Install \Rails at the command prompt if you haven't yet: - gem install rails + $ gem install rails 2. At the command prompt, create a new \Rails application: - rails new myapp + $ rails new myapp where "myapp" is the application name. 3. Change directory to +myapp+ and start the web server: - cd myapp; rails server + $ cd myapp; rails server Run with <tt>--help</tt> or <tt>-h</tt> for options. diff --git a/railties/Rakefile b/railties/Rakefile index 3421d9b464..202644fb26 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -1,12 +1,11 @@ -require 'rake/testtask' +require "rake/testtask" -task :default => :test +task default: :test task :package -task "package:clean" desc "Run all unit tests" -task :test => 'test:isolated' +task test: "test:isolated" namespace :test do task :isolated do @@ -15,8 +14,8 @@ namespace :test do Dir[*test_files].each do |file| next true if file.include?("fixtures") dash_i = [ - 'test', - 'lib', + "test", + "lib", "#{File.dirname(__FILE__)}/../activesupport/lib", "#{File.dirname(__FILE__)}/../actionpack/lib", "#{File.dirname(__FILE__)}/../activemodel/lib" @@ -26,9 +25,9 @@ namespace :test do end end -Rake::TestTask.new('test:regular') do |t| - t.libs << 'test' << "#{File.dirname(__FILE__)}/../activesupport/lib" - t.pattern = 'test/**/*_test.rb' +Rake::TestTask.new("test:regular") do |t| + t.libs << "test" << "#{File.dirname(__FILE__)}/../activesupport/lib" + t.pattern = "test/**/*_test.rb" t.warning = false t.verbose = true t.ruby_opts = ["--dev"] if defined?(JRUBY_VERSION) diff --git a/railties/exe/rails b/railties/exe/rails index 82c17cabce..7e791c1f99 100755 --- a/railties/exe/rails +++ b/railties/exe/rails @@ -1,9 +1,9 @@ #!/usr/bin/env ruby -git_path = File.expand_path('../../../.git', __FILE__) +git_path = File.expand_path("../../../.git", __FILE__) if File.exist?(git_path) - railties_path = File.expand_path('../../lib', __FILE__) + railties_path = File.expand_path("../../lib", __FILE__) $:.unshift(railties_path) end require "rails/cli" diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb index fe789f3c2a..5d862e3fec 100644 --- a/railties/lib/rails.rb +++ b/railties/lib/rails.rb @@ -1,18 +1,18 @@ -require 'rails/ruby_version_check' +require "rails/ruby_version_check" -require 'pathname' +require "pathname" -require 'active_support' -require 'active_support/dependencies/autoload' -require 'active_support/core_ext/kernel/reporting' -require 'active_support/core_ext/module/delegation' -require 'active_support/core_ext/array/extract_options' +require "active_support" +require "active_support/dependencies/autoload" +require "active_support/core_ext/kernel/reporting" +require "active_support/core_ext/module/delegation" +require "active_support/core_ext/array/extract_options" -require 'rails/application' -require 'rails/version' +require "rails/application" +require "rails/version" -require 'active_support/railtie' -require 'action_dispatch/railtie' +require "active_support/railtie" +require "action_dispatch/railtie" # UTF-8 is the default internal and external encoding. silence_warnings do @@ -46,13 +46,13 @@ module Rails def backtrace_cleaner @backtrace_cleaner ||= begin - # Relies on Active Support, so we have to lazy load to postpone definition until AS has been loaded - require 'rails/backtrace_cleaner' + # Relies on Active Support, so we have to lazy load to postpone definition until Active Support has been loaded + require "rails/backtrace_cleaner" Rails::BacktraceCleaner.new end end - # Returns a Pathname object of the current rails project, + # Returns a Pathname object of the current Rails project, # otherwise it returns nil if there is no project: # # Rails.root @@ -77,7 +77,7 @@ module Rails @_env = ActiveSupport::StringInquirer.new(environment) end - # Returns all rails groups for loading based on: + # Returns all Rails groups for loading based on: # # * The Rails environment; # * The environment variable RAILS_GROUPS; @@ -100,7 +100,7 @@ module Rails end # Returns a Pathname object of the public folder of the current - # rails project, otherwise it returns nil if there is no project: + # Rails project, otherwise it returns nil if there is no project: # # Rails.public_path # # => #<Pathname:/Users/someuser/some/path/project/public> diff --git a/railties/lib/rails/all.rb b/railties/lib/rails/all.rb index 1a7f7855f1..7606ea0e46 100644 --- a/railties/lib/rails/all.rb +++ b/railties/lib/rails/all.rb @@ -1,4 +1,4 @@ -require 'rails' +require "rails" %w( active_record/railtie diff --git a/railties/lib/rails/api/task.rb b/railties/lib/rails/api/task.rb index d478bbf9e8..bc670b1d75 100644 --- a/railties/lib/rails/api/task.rb +++ b/railties/lib/rails/api/task.rb @@ -1,33 +1,33 @@ -require 'rdoc/task' +require "rdoc/task" module Rails module API class Task < RDoc::Task RDOC_FILES = { - 'activesupport' => { - :include => %w( + "activesupport" => { + include: %w( README.rdoc lib/active_support/**/*.rb ), - :exclude => 'lib/active_support/vendor/*' + exclude: "lib/active_support/vendor/*" }, - 'activerecord' => { - :include => %w( + "activerecord" => { + include: %w( README.rdoc lib/active_record/**/*.rb ) }, - 'activemodel' => { - :include => %w( + "activemodel" => { + include: %w( README.rdoc lib/active_model/**/*.rb ) }, - 'actionpack' => { - :include => %w( + "actionpack" => { + include: %w( README.rdoc lib/abstract_controller/**/*.rb lib/action_controller/**/*.rb @@ -35,41 +35,41 @@ module Rails ) }, - 'actionview' => { - :include => %w( + "actionview" => { + include: %w( README.rdoc lib/action_view/**/*.rb ), - :exclude => 'lib/action_view/vendor/*' + exclude: "lib/action_view/vendor/*" }, - 'actionmailer' => { - :include => %w( + "actionmailer" => { + include: %w( README.rdoc lib/action_mailer/**/*.rb ) }, - 'activejob' => { - :include => %w( + "activejob" => { + include: %w( README.md lib/active_job/**/*.rb ) }, - 'actioncable' => { - :include => %w( + "actioncable" => { + include: %w( README.md lib/action_cable/**/*.rb ) }, - 'railties' => { - :include => %w( + "railties" => { + include: %w( README.rdoc lib/**/*.rb ), - :exclude => 'lib/rails/generators/rails/**/templates/**/*.rb' + exclude: "lib/rails/generators/rails/**/templates/**/*.rb" } } @@ -92,16 +92,16 @@ module Rails end def load_and_configure_sdoc - require 'sdoc' + require "sdoc" - self.title = 'Ruby on Rails API' + self.title = "Ruby on Rails API" self.rdoc_dir = api_dir - options << '-m' << api_main - options << '-e' << 'UTF-8' + options << "-m" << api_main + options << "-e" << "UTF-8" - options << '-f' << 'sdoc' - options << '-T' << 'rails' + options << "-f" << "sdoc" + options << "-T" << "rails" rescue LoadError $stderr.puts %(Unable to load SDoc, please add\n\n gem 'sdoc', require: false\n\nto the Gemfile.) exit 1 @@ -121,22 +121,35 @@ module Rails rdoc_files.exclude("#{cdr}/#{pattern}") end end + + # Only generate documentation for files that have been + # changed since the API was generated. + if Dir.exist?("doc/rdoc") && !ENV["ALL"] + last_generation = DateTime.rfc2822(File.open("doc/rdoc/created.rid", &:readline)) + + rdoc_files.keep_if do |file| + File.mtime(file).to_datetime > last_generation + end + + # Nothing to do + exit(0) if rdoc_files.empty? + end end def setup_horo_variables - ENV['HORO_PROJECT_NAME'] = 'Ruby on Rails' - ENV['HORO_PROJECT_VERSION'] = rails_version + ENV["HORO_PROJECT_NAME"] = "Ruby on Rails" + ENV["HORO_PROJECT_VERSION"] = rails_version end def api_main - component_root_dir('railties') + '/RDOC_MAIN.rdoc' + component_root_dir("railties") + "/RDOC_MAIN.rdoc" end end class RepoTask < Task def load_and_configure_sdoc super - options << '-g' # link to GitHub, SDoc flag + options << "-g" # link to GitHub, SDoc flag end def component_root_dir(component) @@ -144,7 +157,7 @@ module Rails end def api_dir - 'doc/rdoc' + "doc/rdoc" end end @@ -156,7 +169,7 @@ module Rails class StableTask < RepoTask def rails_version - File.read('RAILS_VERSION').strip + File.read("RAILS_VERSION").strip end end end diff --git a/railties/lib/rails/app_loader.rb b/railties/lib/rails/app_loader.rb index af004d85bf..525d5f0161 100644 --- a/railties/lib/rails/app_loader.rb +++ b/railties/lib/rails/app_loader.rb @@ -1,12 +1,12 @@ -require 'pathname' -require 'rails/version' +require "pathname" +require "rails/version" module Rails module AppLoader # :nodoc: extend self RUBY = Gem.ruby - EXECUTABLES = ['bin/rails', 'script/rails'] + EXECUTABLES = ["bin/rails", "script/rails"] BUNDLER_WARNING = <<EOS Looks like your app's ./bin/rails is a stub that was generated by Bundler. @@ -39,21 +39,21 @@ EOS if contents =~ /(APP|ENGINE)_PATH/ exec RUBY, exe, *ARGV break # non reachable, hack to be able to stub exec in the test suite - elsif exe.end_with?('bin/rails') && contents.include?('This file was generated by Bundler') + elsif exe.end_with?("bin/rails") && contents.include?("This file was generated by Bundler") $stderr.puts(BUNDLER_WARNING) - Object.const_set(:APP_PATH, File.expand_path('config/application', Dir.pwd)) - require File.expand_path('../boot', APP_PATH) - require 'rails/commands' + Object.const_set(:APP_PATH, File.expand_path("config/application", Dir.pwd)) + require File.expand_path("../boot", APP_PATH) + require "rails/commands" break end end # If we exhaust the search there is no executable, this could be a # call to generate a new application, so restore the original cwd. - Dir.chdir(original_cwd) and return if Pathname.new(Dir.pwd).root? + Dir.chdir(original_cwd) && return if Pathname.new(Dir.pwd).root? # Otherwise keep moving upwards in search of an executable. - Dir.chdir('..') + Dir.chdir("..") end end diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index ed106c9918..b01196e3ed 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -1,9 +1,9 @@ -require 'yaml' -require 'active_support/core_ext/hash/keys' -require 'active_support/core_ext/object/blank' -require 'active_support/key_generator' -require 'active_support/message_verifier' -require 'rails/engine' +require "yaml" +require "active_support/core_ext/hash/keys" +require "active_support/core_ext/object/blank" +require "active_support/key_generator" +require "active_support/message_verifier" +require "rails/engine" module Rails # An Engine with the responsibility of coordinating the whole boot process. @@ -75,18 +75,19 @@ module Rails # If you decide to define rake tasks, runners, or initializers in an # application other than +Rails.application+, then you must run them manually. class Application < Engine - autoload :Bootstrap, 'rails/application/bootstrap' - autoload :Configuration, 'rails/application/configuration' - autoload :DefaultMiddlewareStack, 'rails/application/default_middleware_stack' - autoload :Finisher, 'rails/application/finisher' - autoload :Railties, 'rails/engine/railties' - autoload :RoutesReloader, 'rails/application/routes_reloader' + autoload :Bootstrap, "rails/application/bootstrap" + autoload :Configuration, "rails/application/configuration" + autoload :DefaultMiddlewareStack, "rails/application/default_middleware_stack" + autoload :Finisher, "rails/application/finisher" + autoload :Railties, "rails/engine/railties" + autoload :RoutesReloader, "rails/application/routes_reloader" class << self def inherited(base) super Rails.app_class = base add_lib_to_load_path!(find_root(base.called_from)) + ActiveSupport.run_load_hooks(:before_configuration, base) end def instance @@ -146,7 +147,6 @@ module Rails 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| if INITIAL_VARIABLES.include?(variable_name) @@ -317,7 +317,7 @@ module Rails # 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 self.add_lib_to_load_path!(root) #:nodoc: - path = File.join root, 'lib' + path = File.join root, "lib" if File.exist?(path) && !$LOAD_PATH.include?(path) $LOAD_PATH.unshift(path) end @@ -385,11 +385,16 @@ module Rails def secrets @secrets ||= begin secrets = ActiveSupport::OrderedOptions.new - yaml = config.paths["config/secrets"].first + yaml = config.paths["config/secrets"].first + if File.exist?(yaml) require "erb" - all_secrets = YAML.load(ERB.new(IO.read(yaml)).result) || {} - env_secrets = all_secrets[Rails.env] + + all_secrets = YAML.load(ERB.new(IO.read(yaml)).result) || {} + shared_secrets = all_secrets["shared"] + env_secrets = all_secrets[Rails.env] + + secrets.merge!(shared_secrets.symbolize_keys) if shared_secrets secrets.merge!(env_secrets.symbolize_keys) if env_secrets end @@ -517,15 +522,15 @@ module Rails private - def build_request(env) - req = super - env["ORIGINAL_FULLPATH"] = req.fullpath - env["ORIGINAL_SCRIPT_NAME"] = req.script_name - req - end + def build_request(env) + req = super + env["ORIGINAL_FULLPATH"] = req.fullpath + env["ORIGINAL_SCRIPT_NAME"] = req.script_name + req + end - def build_middleware - config.app_middleware + super - end + def build_middleware + config.app_middleware + super + end end end diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb index f615f22b26..11da271501 100644 --- a/railties/lib/rails/application/bootstrap.rb +++ b/railties/lib/rails/application/bootstrap.rb @@ -1,7 +1,7 @@ -require 'fileutils' -require 'active_support/notifications' -require 'active_support/dependencies' -require 'active_support/descendants_tracker' +require "fileutils" +require "active_support/notifications" +require "active_support/dependencies" +require "active_support/descendants_tracker" module Rails class Application @@ -36,7 +36,7 @@ INFO FileUtils.mkdir_p File.dirname path end - f = File.open path, 'a' + f = File.open path, "a" f.binmode f.sync = config.autoflush_log # if true make sure every write flushes diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index f415a20833..810750ed35 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -1,10 +1,10 @@ -require 'active_support/core_ext/kernel/reporting' -require 'active_support/file_update_checker' -require 'rails/engine/configuration' -require 'rails/source_annotation_extractor' +require "active_support/core_ext/kernel/reporting" +require "active_support/file_update_checker" +require "rails/engine/configuration" +require "rails/source_annotation_extractor" -require 'active_support/deprecation' -require 'active_support/core_ext/string/strip' # for strip_heredoc +require "active_support/deprecation" +require "active_support/core_ext/string/strip" # for strip_heredoc module Rails class Application @@ -16,7 +16,7 @@ module Rails :railties_order, :relative_url_root, :secret_key_base, :secret_token, :ssl_options, :public_file_server, :session_options, :time_zone, :reload_classes_only_on_change, - :beginning_of_week, :filter_redirect, :x + :beginning_of_week, :filter_redirect, :x, :enable_dependency_loading attr_writer :log_level attr_reader :encoding, :api_only, :static_cache_control @@ -34,8 +34,7 @@ module Rails @public_file_server.index_name = "index" @force_ssl = false @ssl_options = {} - @session_store = :cookie_store - @session_options = {} + @session_store = nil @time_zone = "UTC" @beginning_of_week = :monday @log_level = nil @@ -54,6 +53,7 @@ module Rails @api_only = false @debug_exception_response_format = nil @x = Custom.new + @enable_dependency_loading = false end def static_cache_control=(value) @@ -134,7 +134,7 @@ module Rails require "yaml" require "erb" YAML.load(ERB.new(yaml.read).result) || {} - elsif ENV['DATABASE_URL'] + elsif ENV["DATABASE_URL"] # Value from ENV['DATABASE_URL'] is set to default database connection # by Active Record. {} @@ -164,29 +164,37 @@ module Rails self.generators.colorize_logging = val end - def session_store(*args) - if args.empty? - case @session_store - when :disabled - nil - when :active_record_store + def session_store(new_session_store = nil, **options) + if new_session_store + if new_session_store == :active_record_store begin ActionDispatch::Session::ActiveRecordStore rescue NameError raise "`ActiveRecord::SessionStore` is extracted out of Rails into a gem. " \ "Please add `activerecord-session_store` to your Gemfile to use it." end + end + + @session_store = new_session_store + @session_options = options || {} + else + case @session_store + when :disabled + nil + when :active_record_store + ActionDispatch::Session::ActiveRecordStore when Symbol ActionDispatch::Session.const_get(@session_store.to_s.camelize) else @session_store end - else - @session_store = args.shift - @session_options = args.shift || {} end end + def session_store? #:nodoc: + @session_store + end + def annotations SourceAnnotationExtractor::Annotation end @@ -205,6 +213,10 @@ module Rails } end end + + def respond_to_missing?(symbol, *) + true + 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 381e548730..14c0a8cbe4 100644 --- a/railties/lib/rails/application/default_middleware_stack.rb +++ b/railties/lib/rails/application/default_middleware_stack.rb @@ -19,7 +19,7 @@ module Rails if config.public_file_server.enabled headers = config.public_file_server.headers || {} - headers['Cache-Control'.freeze] = config.static_cache_control if config.static_cache_control + headers["Cache-Control".freeze] = config.static_cache_control if config.static_cache_control middleware.use ::ActionDispatch::Static, paths["public"].first, index: config.public_file_server.index_name, headers: headers end @@ -76,9 +76,9 @@ module Rails return unless rack_cache begin - require 'rack/cache' + require "rack/cache" rescue LoadError => error - error.message << ' Be sure to add rack-cache to your Gemfile' + error.message << " Be sure to add rack-cache to your Gemfile" raise end diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb index 0aed6c1351..a855e8fab0 100644 --- a/railties/lib/rails/application/finisher.rb +++ b/railties/lib/rails/application/finisher.rb @@ -21,15 +21,26 @@ module Rails initializer :add_builtin_route do |app| if Rails.env.development? + app.routes.prepend do + get "/rails/info/properties" => "rails/info#properties", internal: true + get "/rails/info/routes" => "rails/info#routes", internal: true + get "/rails/info" => "rails/info#index", internal: true + end + app.routes.append do - get '/rails/info/properties' => "rails/info#properties", internal: true - get '/rails/info/routes' => "rails/info#routes", internal: true - get '/rails/info' => "rails/info#index", internal: true - get '/' => "rails/welcome#index", internal: true + get "/" => "rails/welcome#index", internal: true end end end + # Setup default session store if not already set in config/application.rb + initializer :setup_default_session_store, before: :build_middleware_stack do |app| + unless app.config.session_store? + app_name = app.class.name ? app.railtie_name.chomp("_application") : "" + app.config.session_store :cookie_store, key: "_#{app_name}_session" + end + end + initializer :build_middleware_stack do build_middleware_stack end @@ -95,7 +106,7 @@ module Rails elsif config.allow_concurrency == :unsafe # Do nothing, even if we know this is dangerous. This is the - # historical behaviour for true. + # historical behavior for true. else # Default concurrency setting: enabled, but safe @@ -114,7 +125,7 @@ module Rails initializer :set_routes_reloader_hook do |app| reloader = routes_reloader reloader.execute_if_updated - self.reloaders << reloader + reloaders << reloader app.reloader.to_run do # We configure #execute rather than #execute_if_updated because if # autoloaded constants are cleared we need to reload routes also in @@ -150,7 +161,7 @@ module Rails if config.reload_classes_only_on_change reloader = config.file_watcher.new(*watchable_args, &callback) - self.reloaders << reloader + reloaders << reloader # Prepend this callback to have autoloaded constants cleared before # any other possible reloading, in case they need to autoload fresh @@ -173,7 +184,7 @@ module Rails # Disable dependency loading during request cycle initializer :disable_dependency_loading do - if config.eager_load && config.cache_classes + if config.eager_load && config.cache_classes && !config.enable_dependency_loading ActiveSupport::Dependencies.unhook! end end diff --git a/railties/lib/rails/application_controller.rb b/railties/lib/rails/application_controller.rb index 618a09a5b3..f8394b8e0a 100644 --- a/railties/lib/rails/application_controller.rb +++ b/railties/lib/rails/application_controller.rb @@ -1,16 +1,16 @@ class Rails::ApplicationController < ActionController::Base # :nodoc: - self.view_paths = File.expand_path('../templates', __FILE__) - layout 'application' + self.view_paths = File.expand_path("../templates", __FILE__) + layout "application" protected - def require_local! - unless local_request? - render html: '<p>For security purposes, this information is only available to local requests.</p>'.html_safe, status: :forbidden + def require_local! + unless local_request? + render html: "<p>For security purposes, this information is only available to local requests.</p>".html_safe, status: :forbidden + end end - end - def local_request? - Rails.application.config.consider_all_requests_local || request.local? - end + def local_request? + Rails.application.config.consider_all_requests_local || request.local? + end end diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb index 5276eb33c9..5c833e12ba 100644 --- a/railties/lib/rails/backtrace_cleaner.rb +++ b/railties/lib/rails/backtrace_cleaner.rb @@ -1,12 +1,12 @@ -require 'active_support/backtrace_cleaner' +require "active_support/backtrace_cleaner" module Rails class BacktraceCleaner < ActiveSupport::BacktraceCleaner - APP_DIRS_PATTERN = /^\/?(app|config|lib|test)/ + APP_DIRS_PATTERN = /^\/?(app|config|lib|test|\(\w*\))/ RENDER_TEMPLATE_PATTERN = /:in `_render_template_\w*'/ - EMPTY_STRING = ''.freeze - SLASH = '/'.freeze - DOT_SLASH = './'.freeze + EMPTY_STRING = "".freeze + SLASH = "/".freeze + DOT_SLASH = "./".freeze def initialize super diff --git a/railties/lib/rails/cli.rb b/railties/lib/rails/cli.rb index a8794bc0de..973b746068 100644 --- a/railties/lib/rails/cli.rb +++ b/railties/lib/rails/cli.rb @@ -1,15 +1,17 @@ -require 'rails/app_loader' +require "rails/app_loader" # If we are inside a Rails application this method performs an exec and thus # the rest of this script is not run. Rails::AppLoader.exec_app -require 'rails/ruby_version_check' +require "rails/ruby_version_check" Signal.trap("INT") { puts; exit(1) } -if ARGV.first == 'plugin' +require "rails/command" + +if ARGV.first == "plugin" ARGV.shift - require 'rails/commands/plugin' + Rails::Command.invoke :plugin, ARGV else - require 'rails/commands/application' + Rails::Command.invoke :application, ARGV end diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb index 7a8f42fe94..b3d88147a5 100644 --- a/railties/lib/rails/code_statistics.rb +++ b/railties/lib/rails/code_statistics.rb @@ -1,16 +1,15 @@ -require 'rails/code_statistics_calculator' -require 'active_support/core_ext/enumerable' +require "rails/code_statistics_calculator" +require "active_support/core_ext/enumerable" class CodeStatistics #:nodoc: + TEST_TYPES = ["Controller tests", + "Helper tests", + "Model tests", + "Mailer tests", + "Job tests", + "Integration tests"] - TEST_TYPES = ['Controller tests', - 'Helper tests', - 'Model tests', - 'Mailer tests', - 'Job tests', - 'Integration tests'] - - HEADERS = {lines: ' Lines', code_lines: ' LOC', classes: 'Classes', methods: 'Methods'} + HEADERS = { lines: " Lines", code_lines: " LOC", classes: "Classes", methods: "Methods" } def initialize(*pairs) @pairs = pairs @@ -33,7 +32,7 @@ class CodeStatistics #:nodoc: private def calculate_statistics - Hash[@pairs.map{|pair| [pair.first, calculate_directory_statistics(pair.last)]}] + Hash[@pairs.map { |pair| [pair.first, calculate_directory_statistics(pair.last)] }] end def calculate_directory_statistics(directory, pattern = /^(?!\.).*?\.(rb|js|coffee|rake)$/) @@ -71,25 +70,25 @@ class CodeStatistics #:nodoc: end def width_for(label) - [@statistics.values.sum {|s| s.send(label) }.to_s.size, HEADERS[label].length].max + [@statistics.values.sum { |s| s.send(label) }.to_s.size, HEADERS[label].length].max end def print_header print_splitter - print '| Name ' + print "| Name " HEADERS.each do |k, v| print " | #{v.rjust(width_for(k))}" end - puts ' | M/C | LOC/M |' + puts " | M/C | LOC/M |" print_splitter end def print_splitter - print '+----------------------' + print "+----------------------" HEADERS.each_key do |k| print "+#{'-' * (width_for(k) + 2)}" end - puts '+-----+-------+' + puts "+-----+-------+" end def print_line(name, statistics) diff --git a/railties/lib/rails/code_statistics_calculator.rb b/railties/lib/rails/code_statistics_calculator.rb index fad13e8517..d0194af197 100644 --- a/railties/lib/rails/code_statistics_calculator.rb +++ b/railties/lib/rails/code_statistics_calculator.rb @@ -43,7 +43,7 @@ class CodeStatisticsCalculator #:nodoc: def add_by_file_path(file_path) File.open(file_path) do |f| - self.add_by_io(f, file_type(file_path)) + add_by_io(f, file_type(file_path)) end end @@ -77,10 +77,10 @@ class CodeStatisticsCalculator #:nodoc: private def file_type(file_path) - if file_path.end_with? '_test.rb' + if file_path.end_with? "_test.rb" :minitest else - File.extname(file_path).sub(/\A\./, '').downcase.to_sym + File.extname(file_path).sub(/\A\./, "").downcase.to_sym end end end diff --git a/railties/lib/rails/command.rb b/railties/lib/rails/command.rb new file mode 100644 index 0000000000..6065e78fd1 --- /dev/null +++ b/railties/lib/rails/command.rb @@ -0,0 +1,99 @@ +require "active_support" +require "active_support/dependencies/autoload" +require "active_support/core_ext/enumerable" +require "active_support/core_ext/object/blank" +require "active_support/core_ext/hash/transform_values" + +require "thor" + +module Rails + module Command + extend ActiveSupport::Autoload + + autoload :Behavior + autoload :Base + + include Behavior + + class << self + def hidden_commands # :nodoc: + @hidden_commands ||= [] + end + + def environment # :nodoc: + ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development" + end + + # Receives a namespace, arguments and the behavior to invoke the command. + def invoke(namespace, args = [], **config) + namespace = namespace.to_s + namespace = "help" if namespace.blank? || Thor::HELP_MAPPINGS.include?(namespace) + namespace = "version" if %w( -v --version ).include? namespace + + if command = find_by_namespace(namespace) + command.perform(namespace, args, config) + else + find_by_namespace("rake").perform(namespace, args, config) + end + end + + # Rails finds namespaces similar to thor, it only adds one rule: + # + # Command names must end with "_command.rb". This is required because Rails + # looks in load paths and loads the command just before it's going to be used. + # + # find_by_namespace :webrat, :rails, :integration + # + # Will search for the following commands: + # + # "rails:webrat", "webrat:integration", "webrat" + # + # Notice that "rails:commands:webrat" could be loaded as well, what + # Rails looks for is the first and last parts of the namespace. + def find_by_namespace(name) # :nodoc: + lookups = [ name, "rails:#{name}" ] + + lookup(lookups) + + namespaces = subclasses.index_by(&:namespace) + namespaces[(lookups & namespaces.keys).first] + end + + # Returns the root of the Rails engine or app running the command. + def root + if defined?(ENGINE_ROOT) + Pathname.new(ENGINE_ROOT) + elsif defined?(APP_PATH) + Pathname.new(File.expand_path("../..", APP_PATH)) + end + end + + def print_commands # :nodoc: + sorted_groups.each { |b, n| print_list(b, n) } + end + + def sorted_groups # :nodoc: + lookup! + + groups = (subclasses - hidden_commands).group_by { |c| c.namespace.split(":").first } + groups.transform_values! { |commands| commands.flat_map(&:printing_commands).sort } + + rails = groups.delete("rails") + [[ "rails", rails ]] + groups.sort.to_a + end + + protected + def command_type + @command_type ||= "command" + end + + def lookup_paths + @lookup_paths ||= %w( rails/commands commands ) + end + + def file_lookup_paths + @file_lookup_paths ||= [ "{#{lookup_paths.join(',')}}", "**", "*_command.rb" ] + end + end + end +end diff --git a/railties/lib/rails/command/actions.rb b/railties/lib/rails/command/actions.rb new file mode 100644 index 0000000000..31b656ec31 --- /dev/null +++ b/railties/lib/rails/command/actions.rb @@ -0,0 +1,42 @@ +module Rails + module Command + module Actions + # Change to the application's path if there is no config.ru file in current directory. + # This allows us to run `rails server` from other directories, but still get + # the main config.ru and properly set the tmp directory. + def set_application_directory! + Dir.chdir(File.expand_path("../../", APP_PATH)) unless File.exist?(File.expand_path("config.ru")) + end + + if defined?(ENGINE_PATH) + def require_application_and_environment! + require ENGINE_PATH + end + + def load_tasks + Rake.application.init("rails") + Rake.application.load_rakefile + end + + def load_generators + engine = ::Rails::Engine.find(ENGINE_ROOT) + Rails::Generators.namespace = engine.railtie_namespace + engine.load_generators + end + else + def require_application_and_environment! + require APP_PATH + Rails.application.require_environment! + end + + def load_tasks + Rails.application.load_tasks + end + + def load_generators + Rails.application.load_generators + end + end + end + end +end diff --git a/railties/lib/rails/command/base.rb b/railties/lib/rails/command/base.rb new file mode 100644 index 0000000000..1efcd69e63 --- /dev/null +++ b/railties/lib/rails/command/base.rb @@ -0,0 +1,135 @@ +require "thor" +require "erb" + +require "active_support/core_ext/string/filters" +require "active_support/core_ext/string/inflections" + +require "rails/command/actions" + +module Rails + module Command + class Base < Thor + class Error < Thor::Error # :nodoc: + end + + include Actions + + class << self + # Returns true when the app is a Rails engine. + def engine? + defined?(ENGINE_ROOT) + end + + # Tries to get the description from a USAGE file one folder above the command + # root. + def desc(usage = nil, description = nil) + if usage + super + else + @desc ||= ERB.new(File.read(usage_path)).result(binding) if usage_path + end + end + + # Convenience method to get the namespace from the class name. It's the + # same as Thor default except that the Command at the end of the class + # is removed. + def namespace(name = nil) + if name + super + else + @namespace ||= super.chomp("_command").sub(/:command:/, ":") + end + end + + # Convenience method to hide this command from the available ones when + # running rails command. + def hide_command! + Rails::Command.hidden_commands << self + end + + def inherited(base) #:nodoc: + super + + if base.name && base.name !~ /Base$/ + Rails::Command.subclasses << base + end + end + + def perform(command, args, config) # :nodoc: + command = nil if Thor::HELP_MAPPINGS.include?(args.first) + + dispatch(command, args.dup, nil, config) + end + + def printing_commands + namespace.sub(/^rails:/, "") + end + + def executable + "bin/rails #{command_name}" + end + + # Use Rails' default banner. + def banner(*) + "#{executable} #{arguments.map(&:usage).join(' ')} [options]".squish! + end + + # Sets the base_name taking into account the current class namespace. + # + # Rails::Command::TestCommand.base_name # => 'rails' + def base_name + @base_name ||= begin + if base = name.to_s.split("::").first + base.underscore + end + end + end + + # Return command name without namespaces. + # + # Rails::Command::TestCommand.command_name # => 'test' + def command_name + @command_name ||= begin + if command = name.to_s.split("::").last + command.chomp!("Command") + command.underscore + end + end + end + + # Path to lookup a USAGE description in a file. + def usage_path + if default_command_root + path = File.join(default_command_root, "USAGE") + path if File.exist?(path) + end + end + + # Default file root to place extra files a command might need, placed + # one folder above the command file. + # + # For a `Rails::Command::TestCommand` placed in `rails/command/test_command.rb` + # would return `rails/test`. + def default_command_root + path = File.expand_path(File.join("../commands", command_name), __dir__) + path if File.exist?(path) + end + + private + # Allow the command method to be called perform. + def create_command(meth) + if meth == "perform" + alias_method command_name, meth + else + # Prevent exception about command without usage. + # Some commands define their documentation differently. + @usage ||= "" + @desc ||= "" + + super + end + end + end + end + end +end diff --git a/railties/lib/rails/command/behavior.rb b/railties/lib/rails/command/behavior.rb new file mode 100644 index 0000000000..ce994746a4 --- /dev/null +++ b/railties/lib/rails/command/behavior.rb @@ -0,0 +1,123 @@ +require "active_support" + +module Rails + module Command + module Behavior #:nodoc: + extend ActiveSupport::Concern + + class_methods do + # Remove the color from output. + def no_color! + Thor::Base.shell = Thor::Shell::Basic + end + + # Track all command subclasses. + def subclasses + @subclasses ||= [] + end + + protected + + # This code is based directly on the Text gem implementation. + # Copyright (c) 2006-2013 Paul Battley, Michael Neumann, Tim Fletcher. + # + # Returns a value representing the "cost" of transforming str1 into str2. + def levenshtein_distance(str1, str2) + s = str1 + t = str2 + n = s.length + m = t.length + + return m if (0 == n) + return n if (0 == m) + + d = (0..m).to_a + x = nil + + # avoid duplicating an enumerable object in the loop + str2_codepoint_enumerable = str2.each_codepoint + + str1.each_codepoint.with_index do |char1, i| + e = i+1 + + str2_codepoint_enumerable.with_index do |char2, j| + cost = (char1 == char2) ? 0 : 1 + x = [ + d[j+1] + 1, # insertion + e + 1, # deletion + d[j] + cost # substitution + ].min + d[j] = e + e = x + end + + d[m] = x + end + + x + end + + # Prints a list of generators. + def print_list(base, namespaces) #:nodoc: + return if namespaces.empty? + puts "#{base.camelize}:" + + namespaces.each do |namespace| + puts(" #{namespace}") + end + + puts + end + + # Receives namespaces in an array and tries to find matching generators + # in the load path. + def lookup(namespaces) #:nodoc: + paths = namespaces_to_paths(namespaces) + + paths.each do |raw_path| + lookup_paths.each do |base| + path = "#{base}/#{raw_path}_#{command_type}" + + begin + require path + return + rescue LoadError => e + raise unless e.message =~ /#{Regexp.escape(path)}$/ + rescue Exception => e + warn "[WARNING] Could not load #{command_type} #{path.inspect}. Error: #{e.message}.\n#{e.backtrace.join("\n")}" + end + end + end + end + + # This will try to load any command in the load path to show in help. + def lookup! #:nodoc: + $LOAD_PATH.each do |base| + Dir[File.join(base, *file_lookup_paths)].each do |path| + begin + path = path.sub("#{base}/", "") + require path + rescue Exception + # No problem + end + end + end + end + + # Convert namespaces to paths by replacing ":" for "/" and adding + # an extra lookup. For example, "rails:model" should be searched + # in both: "rails/model/model_generator" and "rails/model_generator". + def namespaces_to_paths(namespaces) #:nodoc: + paths = [] + namespaces.each do |namespace| + pieces = namespace.split(":") + paths << pieces.dup.push(pieces.last).join("/") + paths << pieces.join("/") + end + paths.uniq! + paths + end + end + end + end +end diff --git a/railties/lib/rails/command/environment_argument.rb b/railties/lib/rails/command/environment_argument.rb new file mode 100644 index 0000000000..05eac34155 --- /dev/null +++ b/railties/lib/rails/command/environment_argument.rb @@ -0,0 +1,34 @@ +require "active_support" + +module Rails + module Command + module EnvironmentArgument #:nodoc: + extend ActiveSupport::Concern + + included do + argument :environment, optional: true, banner: "environment" + end + + private + def extract_environment_option_from_argument + if environment + self.options = options.merge(environment: acceptable_environment(environment)) + elsif !options[:environment] + self.options = options.merge(environment: Rails::Command.environment) + end + end + + def acceptable_environment(env = nil) + if available_environments.include? env + env + else + %w( production development test ).detect { |e| e =~ /^#{env}/ } || env + end + end + + def available_environments + Dir["config/environments/*.rb"].map { |fname| File.basename(fname, ".*") } + end + end + end +end diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb index 5a66b78a92..fff0119c65 100644 --- a/railties/lib/rails/commands.rb +++ b/railties/lib/rails/commands.rb @@ -1,4 +1,4 @@ -ARGV << '--help' if ARGV.empty? +require "rails/command" aliases = { "g" => "generate", @@ -13,6 +13,4 @@ aliases = { command = ARGV.shift command = aliases[command] || command -require 'rails/commands/commands_tasks' - -Rails::CommandsTasks.new(ARGV).run_command!(command) +Rails::Command.invoke command, ARGV diff --git a/railties/lib/rails/commands/application.rb b/railties/lib/rails/commands/application.rb deleted file mode 100644 index c998e6b6a8..0000000000 --- a/railties/lib/rails/commands/application.rb +++ /dev/null @@ -1,17 +0,0 @@ -require 'rails/generators' -require 'rails/generators/rails/app/app_generator' - -module Rails - module Generators - class AppGenerator # :nodoc: - # We want to exit on failure to be kind to other libraries - # This is only when accessing via CLI - def self.exit_on_failure? - true - end - end - end -end - -args = Rails::Generators::ARGVScrubber.new(ARGV).prepare! -Rails::Generators::AppGenerator.start args diff --git a/railties/lib/rails/commands/application/application_command.rb b/railties/lib/rails/commands/application/application_command.rb new file mode 100644 index 0000000000..7e3a2b011d --- /dev/null +++ b/railties/lib/rails/commands/application/application_command.rb @@ -0,0 +1,29 @@ +require "rails/generators" +require "rails/generators/rails/app/app_generator" + +module Rails + module Generators + class AppGenerator # :nodoc: + # We want to exit on failure to be kind to other libraries + # This is only when accessing via CLI + def self.exit_on_failure? + true + end + end + end + + module Command + class ApplicationCommand < Base + hide_command! + + def help + perform # Punt help output to the generator. + end + + def perform(*args) + Rails::Generators::AppGenerator.start \ + Rails::Generators::ARGVScrubber.new(args).prepare! + end + end + end +end diff --git a/railties/lib/rails/commands/commands_tasks.rb b/railties/lib/rails/commands/commands_tasks.rb deleted file mode 100644 index da3b9452d5..0000000000 --- a/railties/lib/rails/commands/commands_tasks.rb +++ /dev/null @@ -1,180 +0,0 @@ -require 'rails/commands/rake_proxy' - -module Rails - # This is a class which takes in a rails command and initiates the appropriate - # initiation sequence. - # - # Warning: This class mutates ARGV because some commands require manipulating - # it before they are run. - class CommandsTasks # :nodoc: - include Rails::RakeProxy - - attr_reader :argv - - HELP_MESSAGE = <<-EOT -Usage: rails COMMAND [ARGS] - -The most common rails commands are: - generate Generate new code (short-cut alias: "g") - console Start the Rails console (short-cut alias: "c") - server Start the Rails server (short-cut alias: "s") - test Run tests (short-cut alias: "t") - dbconsole Start a console for the database specified in config/database.yml - (short-cut alias: "db") - new Create a new Rails application. "rails new my_app" creates a - new application called MyApp in "./my_app" - -All commands can be run with -h (or --help) for more information. - -In addition to those commands, there are: -EOT - - ADDITIONAL_COMMANDS = [ - [ 'destroy', 'Undo code generated with "generate" (short-cut alias: "d")' ], - [ 'plugin new', 'Generates skeleton for developing a Rails plugin' ], - [ 'runner', - 'Run a piece of code in the application environment (short-cut alias: "r")' ] - ] - - COMMAND_WHITELIST = %w(plugin generate destroy console server dbconsole runner new version help test) - - def initialize(argv) - @argv = argv - end - - def run_command!(command) - command = parse_command(command) - - if COMMAND_WHITELIST.include?(command) - send(command) - else - run_rake_task(command) - end - end - - def plugin - require_command!("plugin") - end - - def generate - generate_or_destroy(:generate) - end - - def destroy - generate_or_destroy(:destroy) - end - - def console - require_command!("console") - options = Rails::Console.parse_arguments(argv) - - # RAILS_ENV needs to be set before config/application is required - ENV['RAILS_ENV'] = options[:environment] if options[:environment] - - # shift ARGV so IRB doesn't freak - shift_argv! - - require_application_and_environment! - Rails::Console.start(Rails.application, options) - end - - def server - set_application_directory! - require_command!("server") - - Rails::Server.new.tap do |server| - # We need to require application after the server sets environment, - # otherwise the --environment option given to the server won't propagate. - require APP_PATH - Dir.chdir(Rails.application.root) - server.start - end - end - - def test - require_command!("test") - end - - def dbconsole - require_command!("dbconsole") - Rails::DBConsole.start - end - - def runner - require_command!("runner") - end - - def new - if %w(-h --help).include?(argv.first) - require_command!("application") - else - exit_with_initialization_warning! - end - end - - def version - argv.unshift '--version' - require_command!("application") - end - - def help - write_help_message - write_commands ADDITIONAL_COMMANDS + formatted_rake_tasks - end - - private - - def exit_with_initialization_warning! - puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n" - puts "Type 'rails' for help." - exit(1) - end - - def shift_argv! - argv.shift if argv.first && argv.first[0] != '-' - end - - def require_command!(command) - require "rails/commands/#{command}" - end - - def generate_or_destroy(command) - require 'rails/generators' - require_application_and_environment! - Rails.application.load_generators - require_command!(command) - end - - # Change to the application's path if there is no config.ru file in current directory. - # This allows us to run `rails server` from other directories, but still get - # the main config.ru and properly set the tmp directory. - def set_application_directory! - Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exist?(File.expand_path("config.ru")) - end - - def require_application_and_environment! - require APP_PATH - Rails.application.require_environment! - end - - def write_help_message - puts HELP_MESSAGE - end - - def write_commands(commands) - width = commands.map { |name, _| name.size }.max || 10 - commands.each { |command| printf(" %-#{width}s %s\n", *command) } - end - - def parse_command(command) - case command - when '--version', '-v' - 'version' - when '--help', '-h' - 'help' - else - command - end - end - end -end diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb deleted file mode 100644 index ea5d20ea24..0000000000 --- a/railties/lib/rails/commands/console.rb +++ /dev/null @@ -1,68 +0,0 @@ -require 'optparse' -require 'irb' -require 'irb/completion' -require 'rails/commands/console_helper' - -module Rails - class Console - include ConsoleHelper - - class << self - def parse_arguments(arguments) - options = {} - - OptionParser.new do |opt| - opt.banner = "Usage: rails console [environment] [options]" - opt.on('-s', '--sandbox', 'Rollback database modifications on exit.') { |v| options[:sandbox] = v } - 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.parse!(arguments) - end - - set_options_env(arguments, options) - end - end - - attr_reader :options, :app, :console - - def initialize(app, options={}) - @app = app - @options = options - - app.sandbox = sandbox? - app.load_console - - @console = app.config.console || IRB - end - - def sandbox? - options[:sandbox] - end - - def environment - options[:environment] ||= super - end - alias_method :environment?, :environment - - def set_environment! - Rails.env = environment - end - - def start - set_environment! if environment? - - if sandbox? - puts "Loading #{Rails.env} environment in sandbox (Rails #{Rails.version})" - puts "Any modifications you make will be rolled back on exit" - else - puts "Loading #{Rails.env} environment (Rails #{Rails.version})" - end - - if defined?(console::ExtendCommandBundle) - console::ExtendCommandBundle.include(Rails::ConsoleMethods) - end - console.start - end - end -end diff --git a/railties/lib/rails/commands/console/console_command.rb b/railties/lib/rails/commands/console/console_command.rb new file mode 100644 index 0000000000..617066f575 --- /dev/null +++ b/railties/lib/rails/commands/console/console_command.rb @@ -0,0 +1,89 @@ +require "irb" +require "irb/completion" + +require "rails/command/environment_argument" + +module Rails + class Console + module BacktraceCleaner + def filter_backtrace(bt) + if result = super + Rails.backtrace_cleaner.filter([result]).first + end + end + end + + def self.start(*args) + new(*args).start + end + + attr_reader :options, :app, :console + + def initialize(app, options = {}) + @app = app + @options = options + + app.sandbox = sandbox? + app.load_console + + @console = app.config.console || IRB + + if @console == IRB + IRB::WorkSpace.prepend(BacktraceCleaner) + end + end + + def sandbox? + options[:sandbox] + end + + def environment + options[:environment] + end + alias_method :environment?, :environment + + def set_environment! + Rails.env = environment + end + + def start + set_environment! if environment? + + if sandbox? + puts "Loading #{Rails.env} environment in sandbox (Rails #{Rails.version})" + puts "Any modifications you make will be rolled back on exit" + else + puts "Loading #{Rails.env} environment (Rails #{Rails.version})" + end + + if defined?(console::ExtendCommandBundle) + console::ExtendCommandBundle.include(Rails::ConsoleMethods) + end + console.start + end + end + + module Command + class ConsoleCommand < Base + include EnvironmentArgument + + class_option :sandbox, aliases: "-s", type: :boolean, default: false, + desc: "Rollback database modifications on exit." + + class_option :environment, aliases: "-e", type: :string, + desc: "Specifies the environment to run this console under (test/development/production)." + + def perform + extract_environment_option_from_argument + + # RAILS_ENV needs to be set before config/application is required. + ENV["RAILS_ENV"] = options[:environment] + + ARGV.clear # Clear ARGV so IRB doesn't freak. + + require_application_and_environment! + Rails::Console.start(Rails.application, options) + end + end + end +end diff --git a/railties/lib/rails/commands/console_helper.rb b/railties/lib/rails/commands/console_helper.rb deleted file mode 100644 index 8ee0b60012..0000000000 --- a/railties/lib/rails/commands/console_helper.rb +++ /dev/null @@ -1,34 +0,0 @@ -require 'active_support/concern' - -module Rails - module ConsoleHelper # :nodoc: - extend ActiveSupport::Concern - - module ClassMethods - def start(*args) - new(*args).start - end - - private - def set_options_env(arguments, options) - if arguments.first && arguments.first[0] != '-' - env = arguments.first - if available_environments.include? env - options[:environment] = env - else - options[:environment] = %w(production development test).detect { |e| e =~ /^#{env}/ } || env - end - end - options - end - - def available_environments - Dir['config/environments/*.rb'].map { |fname| File.basename(fname, '.*') } - end - end - - def environment - ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development" - end - end -end
\ No newline at end of file diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb deleted file mode 100644 index 2c36edfa3f..0000000000 --- a/railties/lib/rails/commands/dbconsole.rb +++ /dev/null @@ -1,173 +0,0 @@ -require 'erb' -require 'yaml' -require 'optparse' -require 'rails/commands/console_helper' - -module Rails - class DBConsole - include ConsoleHelper - - attr_reader :arguments - - class << self - def parse_arguments(arguments) - options = {} - - OptionParser.new do |opt| - opt.banner = "Usage: rails dbconsole [environment] [options]" - opt.on("-p", "--include-password", "Automatically provide the password from database.yml") do |v| - options['include_password'] = true - end - - opt.on("--mode [MODE]", ['html', 'list', 'line', 'column'], - "Automatically put the sqlite3 database in the specified mode (html, list, line, column).") do |mode| - options['mode'] = mode - end - - opt.on("--header") do |h| - options['header'] = h - end - - opt.on("-h", "--help", "Show this help message.") do - puts opt - exit - end - - 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.parse!(arguments) - abort opt.to_s unless (0..1).include?(arguments.size) - end - - set_options_env(arguments, options) - end - end - - def initialize(arguments = ARGV) - @arguments = arguments - end - - def start - options = self.class.parse_arguments(arguments) - ENV['RAILS_ENV'] = options[:environment] || environment - - case config["adapter"] - when /^(jdbc)?mysql/ - args = { - 'host' => '--host', - 'port' => '--port', - 'socket' => '--socket', - 'username' => '--user', - 'encoding' => '--default-character-set', - 'sslca' => '--ssl-ca', - 'sslcert' => '--ssl-cert', - 'sslcapath' => '--ssl-capath', - 'sslcipher' => '--ssl-cipher', - 'sslkey' => '--ssl-key' - }.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact - - if config['password'] && options['include_password'] - args << "--password=#{config['password']}" - elsif config['password'] && !config['password'].to_s.empty? - args << "-p" - end - - args << config['database'] - - find_cmd_and_exec(['mysql', 'mysql5'], *args) - - 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"] - ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && options['include_password'] - find_cmd_and_exec('psql', config["database"]) - - when "sqlite3" - args = [] - - args << "-#{options['mode']}" if options['mode'] - args << "-header" if options['header'] - args << File.expand_path(config['database'], Rails.respond_to?(:root) ? Rails.root : nil) - - find_cmd_and_exec('sqlite3', *args) - - when "oracle", "oracle_enhanced" - logon = "" - - if config['username'] - logon = config['username'] - logon << "/#{config['password']}" if config['password'] && options['include_password'] - logon << "@#{config['database']}" if config['database'] - end - - 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']}." - end - end - - def config - @config ||= begin - if configurations[environment].blank? - raise ActiveRecord::AdapterNotSpecified, "'#{environment}' database is not configured. Available configuration: #{configurations.inspect}" - else - configurations[environment] - end - end - end - - def environment - Rails.respond_to?(:env) ? Rails.env : super - end - - protected - def configurations - require APP_PATH - ActiveRecord::Base.configurations = Rails.application.config.database_configuration - ActiveRecord::Base.configurations - end - - def find_cmd_and_exec(commands, *args) - commands = Array(commands) - - dirs_on_path = ENV['PATH'].to_s.split(File::PATH_SEPARATOR) - unless (ext = RbConfig::CONFIG['EXEEXT']).empty? - commands = commands.map{|cmd| "#{cmd}#{ext}"} - end - - full_path_command = nil - found = commands.detect do |cmd| - dirs_on_path.detect do |path| - full_path_command = File.join(path, cmd) - File.file?(full_path_command) && File.executable?(full_path_command) - end - end - - if found - exec full_path_command, *args - else - abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.") - end - end - end -end diff --git a/railties/lib/rails/commands/dbconsole/dbconsole_command.rb b/railties/lib/rails/commands/dbconsole/dbconsole_command.rb new file mode 100644 index 0000000000..d3c80da89b --- /dev/null +++ b/railties/lib/rails/commands/dbconsole/dbconsole_command.rb @@ -0,0 +1,158 @@ +require "erb" +require "yaml" + +require "rails/command/environment_argument" + +module Rails + class DBConsole + def self.start(*args) + new(*args).start + end + + def initialize(options = {}) + @options = options + end + + def start + ENV["RAILS_ENV"] = @options[:environment] || environment + + case config["adapter"] + when /^(jdbc)?mysql/ + args = { + "host" => "--host", + "port" => "--port", + "socket" => "--socket", + "username" => "--user", + "encoding" => "--default-character-set", + "sslca" => "--ssl-ca", + "sslcert" => "--ssl-cert", + "sslcapath" => "--ssl-capath", + "sslcipher" => "--ssl-cipher", + "sslkey" => "--ssl-key" + }.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact + + if config["password"] && @options["include_password"] + args << "--password=#{config['password']}" + elsif config["password"] && !config["password"].to_s.empty? + args << "-p" + end + + args << config["database"] + + find_cmd_and_exec(["mysql", "mysql5"], *args) + + 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"] + ENV["PGPASSWORD"] = config["password"].to_s if config["password"] && @options["include_password"] + find_cmd_and_exec("psql", config["database"]) + + when "sqlite3" + args = [] + + args << "-#{@options['mode']}" if @options["mode"] + args << "-header" if @options["header"] + args << File.expand_path(config["database"], Rails.respond_to?(:root) ? Rails.root : nil) + + find_cmd_and_exec("sqlite3", *args) + + when "oracle", "oracle_enhanced" + logon = "" + + if config["username"] + logon = config["username"] + logon << "/#{config['password']}" if config["password"] && @options["include_password"] + logon << "@#{config['database']}" if config["database"] + end + + 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']}." + end + end + + def config + @config ||= begin + if configurations[environment].blank? + raise ActiveRecord::AdapterNotSpecified, "'#{environment}' database is not configured. Available configuration: #{configurations.inspect}" + else + configurations[environment] + end + end + end + + def environment + Rails.respond_to?(:env) ? Rails.env : Rails::Command.environment + end + + protected + def configurations + require APP_PATH + ActiveRecord::Base.configurations = Rails.application.config.database_configuration + ActiveRecord::Base.configurations + end + + def find_cmd_and_exec(commands, *args) + commands = Array(commands) + + dirs_on_path = ENV["PATH"].to_s.split(File::PATH_SEPARATOR) + unless (ext = RbConfig::CONFIG["EXEEXT"]).empty? + commands = commands.map { |cmd| "#{cmd}#{ext}" } + end + + full_path_command = nil + found = commands.detect do |cmd| + dirs_on_path.detect do |path| + full_path_command = File.join(path, cmd) + File.file?(full_path_command) && File.executable?(full_path_command) + end + end + + if found + exec full_path_command, *args + else + abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.") + end + end + end + + module Command + class DbconsoleCommand < Base + include EnvironmentArgument + + class_option :include_password, aliases: "-p", type: :boolean, + desc: "Automatically provide the password from database.yml" + + class_option :mode, enum: %w( html list line column ), type: :string, + desc: "Automatically put the sqlite3 database in the specified mode (html, list, line, column)." + + class_option :header, type: :string + + class_option :environment, aliases: "-e", type: :string, + desc: "Specifies the environment to run this console under (test/development/production)." + + def perform + extract_environment_option_from_argument + + Rails::DBConsole.start(options) + end + end + end +end diff --git a/railties/lib/rails/commands/destroy.rb b/railties/lib/rails/commands/destroy.rb deleted file mode 100644 index ce26cc3fde..0000000000 --- a/railties/lib/rails/commands/destroy.rb +++ /dev/null @@ -1,11 +0,0 @@ -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 -end - -name = ARGV.shift -Rails::Generators.invoke name, ARGV, behavior: :revoke, destination_root: Rails.root diff --git a/railties/lib/rails/commands/destroy/destroy_command.rb b/railties/lib/rails/commands/destroy/destroy_command.rb new file mode 100644 index 0000000000..5e6b7f9371 --- /dev/null +++ b/railties/lib/rails/commands/destroy/destroy_command.rb @@ -0,0 +1,21 @@ +require "rails/generators" + +module Rails + module Command + class DestroyCommand < Base + def help # :nodoc: + Rails::Generators.help self.class.command_name + end + + def perform(*) + generator = args.shift + return help unless generator + + require_application_and_environment! + Rails.application.load_generators + + Rails::Generators.invoke generator, args, behavior: :revoke, destination_root: Rails.root + end + end + end +end diff --git a/railties/lib/rails/commands/generate.rb b/railties/lib/rails/commands/generate.rb deleted file mode 100644 index 926c36b967..0000000000 --- a/railties/lib/rails/commands/generate.rb +++ /dev/null @@ -1,13 +0,0 @@ -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 -end - -name = ARGV.shift - -root = defined?(ENGINE_ROOT) ? ENGINE_ROOT : Rails.root -Rails::Generators.invoke name, ARGV, behavior: :invoke, destination_root: root diff --git a/railties/lib/rails/commands/generate/generate_command.rb b/railties/lib/rails/commands/generate/generate_command.rb new file mode 100644 index 0000000000..b381ca85b9 --- /dev/null +++ b/railties/lib/rails/commands/generate/generate_command.rb @@ -0,0 +1,21 @@ +require "rails/generators" + +module Rails + module Command + class GenerateCommand < Base + def help # :nodoc: + Rails::Generators.help self.class.command_name + end + + def perform(*) + generator = args.shift + return help unless generator + + require_application_and_environment! + load_generators + + Rails::Generators.invoke generator, args, behavior: :invoke, destination_root: Rails::Command.root + end + end + end +end diff --git a/railties/lib/rails/commands/help/USAGE b/railties/lib/rails/commands/help/USAGE new file mode 100644 index 0000000000..348f41861f --- /dev/null +++ b/railties/lib/rails/commands/help/USAGE @@ -0,0 +1,27 @@ +Usage: bin/rails COMMAND [args] [options] +<% if engine? %> +The common Rails commands available for engines are: + generate Generate new code (short-cut alias: "g") + destroy Undo code generated with "generate" (short-cut alias: "d") + test Run tests (short-cut alias: "t") + +All commands can be run with -h for more information. + +If you want to run any commands that need to be run in context +of the application, like `bin/rails server` or `bin/rails console`, +you should do it from the application's directory (typically test/dummy). +<% else %> +The most common rails commands are: + generate Generate new code (short-cut alias: "g") + console Start the Rails console (short-cut alias: "c") + server Start the Rails server (short-cut alias: "s") + test Run tests (short-cut alias: "t") + dbconsole Start a console for the database specified in config/database.yml + (short-cut alias: "db") + new Create a new Rails application. "rails new my_app" creates a + new application called MyApp in "./my_app" + +All commands can be run with -h (or --help) for more information. +<% end %> +In addition to those commands, there are: + diff --git a/railties/lib/rails/commands/help/help_command.rb b/railties/lib/rails/commands/help/help_command.rb new file mode 100644 index 0000000000..5bcc4c8eee --- /dev/null +++ b/railties/lib/rails/commands/help/help_command.rb @@ -0,0 +1,13 @@ +module Rails + module Command + class HelpCommand < Base + hide_command! + + def help(*) + puts self.class.desc + + Rails::Command.print_commands + end + end + end +end diff --git a/railties/lib/rails/commands/new/new_command.rb b/railties/lib/rails/commands/new/new_command.rb new file mode 100644 index 0000000000..13eedfc479 --- /dev/null +++ b/railties/lib/rails/commands/new/new_command.rb @@ -0,0 +1,15 @@ +module Rails + module Command + class NewCommand < Base + def help + Rails::Command.invoke :application, [ "--help" ] + end + + def perform(*) + puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n" + puts "Type 'rails' for help." + exit 1 + end + end + end +end diff --git a/railties/lib/rails/commands/plugin.rb b/railties/lib/rails/commands/plugin.rb deleted file mode 100644 index 52d8966ead..0000000000 --- a/railties/lib/rails/commands/plugin.rb +++ /dev/null @@ -1,23 +0,0 @@ -if ARGV.first != "new" - ARGV[0] = "--help" -else - ARGV.shift - unless ARGV.delete("--no-rc") - customrc = ARGV.index{ |x| x.include?("--rc=") } - railsrc = if customrc - File.expand_path(ARGV.delete_at(customrc).gsub(/--rc=/, "")) - else - File.join(File.expand_path("~"), '.railsrc') - end - if File.exist?(railsrc) - extra_args_string = File.read(railsrc) - extra_args = extra_args_string.split(/\n+/).flat_map(&:split) - puts "Using #{extra_args.join(" ")} from #{railsrc}" - ARGV.insert(1, *extra_args) - end - end -end - -require 'rails/generators' -require 'rails/generators/rails/plugin/plugin_generator' -Rails::Generators::PluginGenerator.start diff --git a/railties/lib/rails/commands/plugin/plugin_command.rb b/railties/lib/rails/commands/plugin/plugin_command.rb new file mode 100644 index 0000000000..d6d9fe4400 --- /dev/null +++ b/railties/lib/rails/commands/plugin/plugin_command.rb @@ -0,0 +1,43 @@ +module Rails + module Command + class PluginCommand < Base + hide_command! + + def help + run_plugin_generator %w( --help ) + end + + def self.banner(*) # :nodoc: + "#{executable} new [options]" + end + + class_option :rc, type: :boolean, default: File.join("~", ".railsrc"), + desc: "Initialize the plugin command with previous defaults. Uses .railsrc in your home directory by default." + + class_option :no_rc, desc: "Skip evaluating .railsrc." + + def perform(type = nil, *plugin_args) + plugin_args << "--help" unless type == "new" + + unless options.key?("no_rc") # Thor's not so indifferent access hash. + railsrc = File.expand_path(options[:rc]) + + if File.exist?(railsrc) + extra_args = File.read(railsrc).split(/\n+/).flat_map(&:split) + puts "Using #{extra_args.join(" ")} from #{railsrc}" + plugin_args.insert(1, *extra_args) + end + end + + run_plugin_generator plugin_args + end + + private + def run_plugin_generator(plugin_args) + require "rails/generators" + require "rails/generators/rails/plugin/plugin_generator" + Rails::Generators::PluginGenerator.start plugin_args + end + end + end +end diff --git a/railties/lib/rails/commands/rake/rake_command.rb b/railties/lib/rails/commands/rake/rake_command.rb new file mode 100644 index 0000000000..a43c884170 --- /dev/null +++ b/railties/lib/rails/commands/rake/rake_command.rb @@ -0,0 +1,51 @@ +module Rails + module Command + class RakeCommand < Base + extend Rails::Command::Actions + + namespace "rake" + + class << self + def printing_commands + formatted_rake_tasks.map(&:first) + end + + def perform(task, *) + require_rake + + ARGV.unshift(task) # Prepend the task, so Rake knows how to run it. + + Rake.application.standard_exception_handling do + Rake.application.init("rails") + Rake.application.load_rakefile + Rake.application.top_level + end + end + + private + def rake_tasks + require_rake + + return @rake_tasks if defined?(@rake_tasks) + + ActiveSupport::Deprecation.silence do + require_application_and_environment! + end + + Rake::TaskManager.record_task_metadata = true + Rake.application.instance_variable_set(:@name, "rails") + load_tasks + @rake_tasks = Rake.application.tasks.select(&:comment) + end + + def formatted_rake_tasks + rake_tasks.map { |t| [ t.name_with_args, t.comment ] } + end + + def require_rake + require "rake" # Defer booting Rake until we know it's needed. + end + end + end + end +end diff --git a/railties/lib/rails/commands/rake_proxy.rb b/railties/lib/rails/commands/rake_proxy.rb deleted file mode 100644 index f7d5df6b2f..0000000000 --- a/railties/lib/rails/commands/rake_proxy.rb +++ /dev/null @@ -1,34 +0,0 @@ -require 'rake' -require 'active_support' - -module Rails - module RakeProxy #:nodoc: - private - def run_rake_task(command) - ARGV.unshift(command) # Prepend the command, so Rake knows how to run it. - - Rake.application.standard_exception_handling do - Rake.application.init('rails') - Rake.application.load_rakefile - Rake.application.top_level - end - end - - def rake_tasks - return @rake_tasks if defined?(@rake_tasks) - - ActiveSupport::Deprecation.silence do - require_application_and_environment! - end - - Rake::TaskManager.record_task_metadata = true - Rake.application.instance_variable_set(:@name, 'rails') - Rails.application.load_tasks - @rake_tasks = Rake.application.tasks.select(&:comment) - end - - def formatted_rake_tasks - rake_tasks.map { |t| [ t.name_with_args, t.comment ] } - end - end -end diff --git a/railties/lib/rails/commands/runner.rb b/railties/lib/rails/commands/runner.rb deleted file mode 100644 index f9c183ac86..0000000000 --- a/railties/lib/rails/commands/runner.rb +++ /dev/null @@ -1,69 +0,0 @@ -require 'optparse' - -options = { environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup } -code_or_file = nil -command = 'bin/rails runner' - -if ARGV.first.nil? - ARGV.push "-h" -end - -ARGV.clone.options do |opts| - opts.banner = "Usage: rails runner [options] [<'Some.ruby(code)'> | <filename.rb>]" - - opts.separator "" - - opts.on("-e", "--environment=name", String, - "Specifies the environment for the runner to operate under (test/development/production).", - "Default: development") { |v| options[:environment] = v } - - opts.separator "" - - opts.on("-h", "--help", - "Show this help message.") { $stdout.puts opts; exit } - - opts.separator "" - opts.separator "Examples: " - - opts.separator " rails runner 'puts Rails.env'" - opts.separator " This runs the code `puts Rails.env` after loading the app" - opts.separator "" - opts.separator " rails runner path/to/filename.rb" - opts.separator " This runs the Ruby file located at `path/to/filename.rb` after loading the app" - - if RbConfig::CONFIG['host_os'] !~ /mswin|mingw/ - opts.separator "" - opts.separator "You can also use runner as a shebang line for your executables:" - opts.separator " -------------------------------------------------------------" - opts.separator " #!/usr/bin/env #{File.expand_path(command)}" - opts.separator "" - opts.separator " Product.all.each { |p| p.price *= 2 ; p.save! }" - opts.separator " -------------------------------------------------------------" - end - - opts.order! { |o| code_or_file ||= o } rescue retry -end - -ARGV.delete(code_or_file) - -ENV["RAILS_ENV"] = options[:environment] - -require APP_PATH -Rails.application.require_environment! -Rails.application.load_runner - -if code_or_file.nil? - $stderr.puts "Run '#{command} -h' for help." - exit 1 -elsif File.exist?(code_or_file) - $0 = code_or_file - Kernel.load code_or_file -else - begin - eval(code_or_file, binding, __FILE__, __LINE__) - rescue SyntaxError, NameError - $stderr.puts "Please specify a valid ruby command or the path of a script to run." - $stderr.puts "Run '#{command} -h' for help." - exit 1 - end -end diff --git a/railties/lib/rails/commands/runner/USAGE b/railties/lib/rails/commands/runner/USAGE new file mode 100644 index 0000000000..dc47a35ff3 --- /dev/null +++ b/railties/lib/rails/commands/runner/USAGE @@ -0,0 +1,17 @@ +Examples: + +Run `puts Rails.env` after loading the app: + + <%= executable %> 'puts Rails.env' + +Run the Ruby file located at `path/to/filename.rb` after loading the app: + + <%= executable %> path/to/filename.rb + +<% if RbConfig::CONFIG['host_os'] !~ /mswin|mingw/ %> +You can also use the runner command as a shebang line for your executables: + + #!/usr/bin/env <%= File.expand_path(executable) %> + + Product.all.each { |p| p.price *= 2 ; p.save! } +<% end %> diff --git a/railties/lib/rails/commands/runner/runner_command.rb b/railties/lib/rails/commands/runner/runner_command.rb new file mode 100644 index 0000000000..8db6da8759 --- /dev/null +++ b/railties/lib/rails/commands/runner/runner_command.rb @@ -0,0 +1,45 @@ +module Rails + module Command + class RunnerCommand < Base + class_option :environment, aliases: "-e", type: :string, + default: Rails::Command.environment.dup, + desc: "The environment for the runner to operate under (test/development/production)" + + def help + super + puts self.class.desc + end + + def self.banner(*) + "#{super} [<'Some.ruby(code)'> | <filename.rb>]" + end + + def perform(code_or_file = nil) + unless code_or_file + help + exit 1 + end + + ENV["RAILS_ENV"] = options[:environment] + + require_application_and_environment! + Rails.application.load_runner + + if File.exist?(code_or_file) + $0 = code_or_file + Kernel.load code_or_file + else + begin + eval(code_or_file, binding, __FILE__, __LINE__) + rescue SyntaxError, NameError => error + $stderr.puts "Please specify a valid ruby command or the path of a script to run." + $stderr.puts "Run '#{self.class.executable} -h' for help." + $stderr.puts + $stderr.puts error + exit 1 + end + end + end + end + end +end diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server/server_command.rb index 7418dff18b..14cf72f483 100644 --- a/railties/lib/rails/commands/server.rb +++ b/railties/lib/rails/commands/server/server_command.rb @@ -1,8 +1,8 @@ -require 'fileutils' -require 'optparse' -require 'action_dispatch' -require 'rails' -require 'rails/dev_caching' +require "fileutils" +require "optparse" +require "action_dispatch" +require "rails" +require "rails/dev_caching" module Rails class Server < ::Rack::Server @@ -19,11 +19,13 @@ module Rails options end - private - - def option_parser(options) + def option_parser(options) # :nodoc: OptionParser.new do |opts| - opts.banner = "Usage: rails server [mongrel, thin etc] [options]" + opts.banner = "Usage: rails server [puma, thin etc] [options]" + + opts.separator "" + opts.separator "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, @@ -80,7 +82,7 @@ module Rails ensure # The '-h' option calls exit before @options is set. # If we call 'options' with it unset, we get double help banners. - puts 'Exiting' unless @options && options[:daemonize] + puts "Exiting" unless @options && options[:daemonize] end def middleware @@ -88,19 +90,18 @@ module Rails end def default_options - super.merge({ - Port: ENV.fetch('PORT', 3000).to_i, + super.merge( + Port: ENV.fetch("PORT", 3000).to_i, + Host: ENV.fetch("HOST", "localhost").dup, DoNotReverseLookup: true, - environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup, + environment: (ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development").dup, daemonize: false, caching: nil, pid: Options::DEFAULT_PID_PATH, - restart_cmd: restart_command - }) + restart_cmd: restart_command) end private - def setup_dev_caching if options[:environment] == "development" Rails::DevCaching.enable_by_argument(options[:caching]) @@ -116,7 +117,7 @@ module Rails def create_tmp_directories %w(cache pids sockets).each do |dir_to_make| - FileUtils.mkdir_p(File.join(Rails.root, 'tmp', dir_to_make)) + FileUtils.mkdir_p(File.join(Rails.root, "tmp", dir_to_make)) end end @@ -136,4 +137,24 @@ module Rails "bin/rails server #{ARGV.join(' ')}" end end + + module Command + class ServerCommand < Base + def help # :nodoc: + puts Rails::Server::Options.new.option_parser(Hash.new) + end + + def perform + set_application_directory! + + Rails::Server.new.tap do |server| + # Require application after server sets environment to propagate + # the --environment option. + require APP_PATH + Dir.chdir(Rails.application.root) + server.start + end + end + end + end end diff --git a/railties/lib/rails/commands/test.rb b/railties/lib/rails/commands/test.rb deleted file mode 100644 index dd069f081f..0000000000 --- a/railties/lib/rails/commands/test.rb +++ /dev/null @@ -1,9 +0,0 @@ -require "rails/test_unit/minitest_plugin" - -if defined?(ENGINE_ROOT) - $: << File.expand_path('test', ENGINE_ROOT) -else - $: << File.expand_path('../../test', APP_PATH) -end - -exit Minitest.run(ARGV) diff --git a/railties/lib/rails/commands/test/test_command.rb b/railties/lib/rails/commands/test/test_command.rb new file mode 100644 index 0000000000..1b2e3af9cc --- /dev/null +++ b/railties/lib/rails/commands/test/test_command.rb @@ -0,0 +1,20 @@ +require "rails/command" +require "rails/test_unit/minitest_plugin" + +module Rails + module Command + class TestCommand < Base + def help # :nodoc: + perform # Hand over help printing to minitest. + end + + def perform(*) + $LOAD_PATH << Rails::Command.root.join("test") + + Minitest.run_via[:rails] = true + + require "active_support/testing/autorun" + end + end + end +end diff --git a/railties/lib/rails/commands/version/version_command.rb b/railties/lib/rails/commands/version/version_command.rb new file mode 100644 index 0000000000..4f3fbfca1b --- /dev/null +++ b/railties/lib/rails/commands/version/version_command.rb @@ -0,0 +1,9 @@ +module Rails + module Command + class VersionCommand < Base + def perform + Rails::Command.invoke :application, [ "--version" ] + end + end + end +end diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb index 30eafd59f2..7dfab969e8 100644 --- a/railties/lib/rails/configuration.rb +++ b/railties/lib/rails/configuration.rb @@ -1,7 +1,7 @@ -require 'active_support/ordered_options' -require 'active_support/core_ext/object' -require 'rails/paths' -require 'rails/rack' +require "active_support/ordered_options" +require "active_support/core_ext/object" +require "rails/paths" +require "rails/rack" module Rails module Configuration @@ -112,7 +112,7 @@ module Rails end def method_missing(method, *args) - method = method.to_s.sub(/=$/, '').to_sym + method = method.to_s.sub(/=$/, "").to_sym return @options[method] if args.empty? diff --git a/railties/lib/rails/console/app.rb b/railties/lib/rails/console/app.rb index 9ad77e0a80..541d5e3dad 100644 --- a/railties/lib/rails/console/app.rb +++ b/railties/lib/rails/console/app.rb @@ -1,5 +1,5 @@ -require 'active_support/all' -require 'action_controller' +require "active_support/all" +require "action_controller" module Rails module ConsoleMethods diff --git a/railties/lib/rails/dev_caching.rb b/railties/lib/rails/dev_caching.rb index f2a53d6417..f69275a34a 100644 --- a/railties/lib/rails/dev_caching.rb +++ b/railties/lib/rails/dev_caching.rb @@ -1,27 +1,27 @@ -require 'fileutils' +require "fileutils" module Rails module DevCaching # :nodoc: class << self - FILE = 'tmp/caching-dev.txt' + FILE = "tmp/caching-dev.txt" def enable_by_file - FileUtils.mkdir_p('tmp') + FileUtils.mkdir_p("tmp") if File.exist?(FILE) delete_cache_file - puts 'Development mode is no longer being cached.' + puts "Development mode is no longer being cached." else create_cache_file - puts 'Development mode is now being cached.' + puts "Development mode is now being cached." end - FileUtils.touch 'tmp/restart.txt' - FileUtils.rm_f('tmp/pids/server.pid') + FileUtils.touch "tmp/restart.txt" + FileUtils.rm_f("tmp/pids/server.pid") end def enable_by_argument(caching) - FileUtils.mkdir_p('tmp') + FileUtils.mkdir_p("tmp") if caching create_cache_file diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index 5757d235d2..90e7c04d7c 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -1,8 +1,8 @@ -require 'rails/railtie' -require 'rails/engine/railties' -require 'active_support/core_ext/module/delegation' -require 'pathname' -require 'thread' +require "rails/railtie" +require "rails/engine/railties" +require "active_support/core_ext/module/delegation" +require "pathname" +require "thread" module Rails # <tt>Rails::Engine</tt> allows you to wrap a specific Rails application or subset of @@ -219,7 +219,7 @@ module Rails # The next thing that changes in isolated engines is the behavior of routes. # Normally, when you namespace your controllers, you also need to namespace # the related routes. With an isolated engine, the engine's namespace is - # automatically applied, so you don't need to specify it explicity in your + # automatically applied, so you don't need to specify it explicitly in your # routes: # # MyEngine::Engine.routes.draw do @@ -337,7 +337,7 @@ module Rails # == Loading priority # # In order to change engine's priority you can use +config.railties_order+ in the main application. - # It will affect the priority of loading views, helpers, assets and all the other files + # It will affect the priority of loading views, helpers, assets, and all the other files # related to engine or application. # # # load Blog::Engine with highest priority, followed by application and other railties @@ -402,7 +402,7 @@ module Rails end unless mod.respond_to?(:railtie_routes_url_helpers) - define_method(:railtie_routes_url_helpers) {|include_path_helpers = true| railtie.routes.url_helpers(include_path_helpers) } + define_method(:railtie_routes_url_helpers) { |include_path_helpers = true| railtie.routes.url_helpers(include_path_helpers) } end end end @@ -590,8 +590,8 @@ module Rails initializer :add_view_paths do views = paths["app/views"].existent unless views.empty? - ActiveSupport.on_load(:action_controller){ prepend_view_path(views) if respond_to?(:prepend_view_path) } - ActiveSupport.on_load(:action_mailer){ prepend_view_path(views) } + ActiveSupport.on_load(:action_controller) { prepend_view_path(views) if respond_to?(:prepend_view_path) } + ActiveSupport.on_load(:action_mailer) { prepend_view_path(views) } end end @@ -619,7 +619,7 @@ module Rails end rake_tasks do - next if self.is_a?(Rails::Application) + next if is_a?(Rails::Application) next unless has_migrations? namespace railtie_name do @@ -643,62 +643,62 @@ module Rails protected - def load_config_initializer(initializer) - ActiveSupport::Notifications.instrument('load_config_initializer.railties', initializer: initializer) do - load(initializer) + def load_config_initializer(initializer) + ActiveSupport::Notifications.instrument("load_config_initializer.railties", initializer: initializer) do + load(initializer) + end end - end - def run_tasks_blocks(*) #:nodoc: - super - paths["lib/tasks"].existent.sort.each { |ext| load(ext) } - end + def run_tasks_blocks(*) #:nodoc: + super + paths["lib/tasks"].existent.sort.each { |ext| load(ext) } + end - def has_migrations? #:nodoc: - paths["db/migrate"].existent.any? - end + def has_migrations? #:nodoc: + paths["db/migrate"].existent.any? + end - def self.find_root_with_flag(flag, root_path, default=nil) #:nodoc: + 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) - root_path = parent != root_path && parent - end + while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}") + parent = File.dirname(root_path) + root_path = parent != root_path && parent + end - root = File.exist?("#{root_path}/#{flag}") ? root_path : default - raise "Could not find root path for #{self}" unless root + root = File.exist?("#{root_path}/#{flag}") ? root_path : default + raise "Could not find root path for #{self}" unless root - Pathname.new File.realpath root - end + Pathname.new File.realpath root + end - def default_middleware_stack #:nodoc: - ActionDispatch::MiddlewareStack.new - end + def default_middleware_stack #:nodoc: + ActionDispatch::MiddlewareStack.new + end - def _all_autoload_once_paths #:nodoc: - config.autoload_once_paths - end + def _all_autoload_once_paths #:nodoc: + config.autoload_once_paths + end - def _all_autoload_paths #:nodoc: - @_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq - end + def _all_autoload_paths #:nodoc: + @_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq + end - def _all_load_paths #:nodoc: - @_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq - end + def _all_load_paths #:nodoc: + @_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq + end private - def build_request(env) - env.merge!(env_config) - req = ActionDispatch::Request.new env - req.routes = routes - req.engine_script_name = req.script_name - req - end + def build_request(env) + env.merge!(env_config) + req = ActionDispatch::Request.new env + req.routes = routes + req.engine_script_name = req.script_name + req + end - def build_middleware - config.middleware - end + def build_middleware + config.middleware + end end end diff --git a/railties/lib/rails/engine/commands.rb b/railties/lib/rails/engine/commands.rb index 7bbd9ef744..a23ae44b0b 100644 --- a/railties/lib/rails/engine/commands.rb +++ b/railties/lib/rails/engine/commands.rb @@ -1,6 +1,4 @@ -require 'rails/engine/commands_tasks' - -ARGV << '--help' if ARGV.empty? +require "rails/command" aliases = { "g" => "generate", @@ -11,4 +9,4 @@ aliases = { command = ARGV.shift command = aliases[command] || command -Rails::Engine::CommandsTasks.new(ARGV).run_command!(command) +Rails::Command.invoke command, ARGV diff --git a/railties/lib/rails/engine/commands_tasks.rb b/railties/lib/rails/engine/commands_tasks.rb deleted file mode 100644 index fa3ee59b7d..0000000000 --- a/railties/lib/rails/engine/commands_tasks.rb +++ /dev/null @@ -1,116 +0,0 @@ -require 'rails/commands/rake_proxy' - -module Rails - class Engine - class CommandsTasks # :nodoc: - include Rails::RakeProxy - - attr_reader :argv - - HELP_MESSAGE = <<-EOT -Usage: rails COMMAND [ARGS] - -The common Rails commands available for engines are: - generate Generate new code (short-cut alias: "g") - destroy Undo code generated with "generate" (short-cut alias: "d") - test Run tests (short-cut alias: "t") - -All commands can be run with -h for more information. - -If you want to run any commands that need to be run in context -of the application, like `rails server` or `rails console`, -you should do it from application's directory (typically test/dummy). - -In addition to those commands, there are: - EOT - - COMMAND_WHITELIST = %w(generate destroy version help test) - - def initialize(argv) - @argv = argv - end - - def run_command!(command) - command = parse_command(command) - - if COMMAND_WHITELIST.include?(command) - send(command) - else - run_rake_task(command) - end - end - - def generate - generate_or_destroy(:generate) - end - - def destroy - generate_or_destroy(:destroy) - end - - def test - require_command!("test") - end - - def version - argv.unshift '--version' - require_command!("application") - end - - def help - write_help_message - write_commands(formatted_rake_tasks) - end - - private - - def require_command!(command) - require "rails/commands/#{command}" - end - - def generate_or_destroy(command) - load_generators - require_command!(command) - end - - def load_generators - require 'rails/generators' - require ENGINE_PATH - - engine = ::Rails::Engine.find(ENGINE_ROOT) - Rails::Generators.namespace = engine.railtie_namespace - engine.load_generators - end - - def write_help_message - puts HELP_MESSAGE - end - - def write_commands(commands) - width = commands.map { |name, _| name.size }.max || 10 - commands.each { |command| printf(" %-#{width}s %s\n", *command) } - end - - def parse_command(command) - case command - when '--version', '-v' - 'version' - when '--help', '-h' - 'help' - else - command - end - end - - def rake_tasks - return @rake_tasks if defined?(@rake_tasks) - - load_generators - Rake::TaskManager.record_task_metadata = true - Rake.application.init('rails') - Rake.application.load_rakefile - @rake_tasks = Rake.application.tasks.select(&:comment) - end - end - end -end diff --git a/railties/lib/rails/engine/configuration.rb b/railties/lib/rails/engine/configuration.rb index 294d07446f..147b904679 100644 --- a/railties/lib/rails/engine/configuration.rb +++ b/railties/lib/rails/engine/configuration.rb @@ -1,4 +1,4 @@ -require 'rails/railtie/configuration' +require "rails/railtie/configuration" module Rails class Engine diff --git a/railties/lib/rails/gem_version.rb b/railties/lib/rails/gem_version.rb index 08a331bff2..9c49e0655a 100644 --- a/railties/lib/rails/gem_version.rb +++ b/railties/lib/rails/gem_version.rb @@ -6,9 +6,9 @@ module Rails module VERSION MAJOR = 5 - MINOR = 0 + MINOR = 1 TINY = 0 - PRE = "beta4" + PRE = "alpha" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index 330bd7ec5d..dd16b44786 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -1,45 +1,48 @@ -activesupport_path = File.expand_path('../../../../activesupport/lib', __FILE__) +activesupport_path = File.expand_path("../../../../activesupport/lib", __FILE__) $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path) -require 'thor/group' +require "thor/group" +require "rails/command" -require 'active_support' -require 'active_support/core_ext/object/blank' -require 'active_support/core_ext/kernel/singleton_class' -require 'active_support/core_ext/array/extract_options' -require 'active_support/core_ext/hash/deep_merge' -require 'active_support/core_ext/module/attribute_accessors' -require 'active_support/core_ext/string/inflections' +require "active_support" +require "active_support/core_ext/object/blank" +require "active_support/core_ext/kernel/singleton_class" +require "active_support/core_ext/array/extract_options" +require "active_support/core_ext/hash/deep_merge" +require "active_support/core_ext/module/attribute_accessors" +require "active_support/core_ext/string/inflections" module Rails module Generators - autoload :Actions, 'rails/generators/actions' - autoload :ActiveModel, 'rails/generators/active_model' - autoload :Base, 'rails/generators/base' - autoload :Migration, 'rails/generators/migration' - autoload :NamedBase, 'rails/generators/named_base' - autoload :ResourceHelpers, 'rails/generators/resource_helpers' - autoload :TestCase, 'rails/generators/test_case' + include Rails::Command::Behavior + + autoload :Actions, "rails/generators/actions" + autoload :ActiveModel, "rails/generators/active_model" + autoload :Base, "rails/generators/base" + autoload :Migration, "rails/generators/migration" + autoload :NamedBase, "rails/generators/named_base" + autoload :ResourceHelpers, "rails/generators/resource_helpers" + autoload :TestCase, "rails/generators/test_case" mattr_accessor :namespace DEFAULT_ALIASES = { rails: { - actions: '-a', - orm: '-o', - javascripts: '-j', - javascript_engine: '-je', - resource_controller: '-c', - scaffold_controller: '-c', - stylesheets: '-y', - stylesheet_engine: '-se', - scaffold_stylesheet: '-ss', - template_engine: '-e', - test_framework: '-t' + actions: "-a", + orm: "-o", + javascripts: "-j", + javascript_engine: "-je", + resource_controller: "-c", + scaffold_controller: "-c", + stylesheets: "-y", + stylesheet_engine: "-se", + scaffold_stylesheet: "-ss", + template_engine: "-e", + test_framework: "-t" }, test_unit: { - fixture_replacement: '-r', + fixture_replacement: "-r", } } @@ -117,7 +120,7 @@ module Rails template_engine: nil ) - if ARGV.first == 'mailer' + if ARGV.first == "mailer" options[:rails].merge!(template_engine: :erb) end end @@ -127,67 +130,6 @@ module Rails Thor::Base.shell = Thor::Shell::Basic end - # Track all generators subclasses. - def self.subclasses - @subclasses ||= [] - end - - # Rails finds namespaces similar to thor, it only adds one rule: - # - # Generators names must end with "_generator.rb". This is required because Rails - # looks in load paths and loads the generator just before it's going to be used. - # - # find_by_namespace :webrat, :rails, :integration - # - # Will search for the following generators: - # - # "rails:webrat", "webrat:integration", "webrat" - # - # Notice that "rails:generators:webrat" could be loaded as well, what - # Rails looks for is the first and last parts of the namespace. - def self.find_by_namespace(name, base=nil, context=nil) #:nodoc: - lookups = [] - lookups << "#{base}:#{name}" if base - lookups << "#{name}:#{context}" if context - - unless base || context - unless name.to_s.include?(?:) - lookups << "#{name}:#{name}" - lookups << "rails:#{name}" - end - lookups << "#{name}" - end - - lookup(lookups) - - namespaces = Hash[subclasses.map { |klass| [klass.namespace, klass] }] - - lookups.each do |namespace| - klass = namespaces[namespace] - return klass if klass - end - - invoke_fallbacks_for(name, base) || invoke_fallbacks_for(context, name) - end - - # Receives a namespace, arguments and the behavior to invoke the generator. - # It's used as the default entry point for generate, destroy and update - # commands. - 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?(&:required?) - klass.start(args, config) - else - options = sorted_groups.flat_map(&:last) - suggestions = options.sort_by {|suggested| levenshtein_distance(namespace.to_s, suggested) }.first(3) - msg = "Could not find generator '#{namespace}'. " - msg << "Maybe you meant #{ suggestions.map {|s| "'#{s}'"}.to_sentence(last_word_connector: " or ", locale: :en) }\n" - msg << "Run `rails generate --help` for more options." - puts msg - end - end - # Returns an array of generator namespaces that are hidden. # Generator namespaces may be hidden for a variety of reasons. # Some are aliased such as "rails:migration" and can be @@ -232,7 +174,7 @@ module Rails end # Show help message with available generators. - def self.help(command = 'generate') + def self.help(command = "generate") puts "Usage: rails #{command} GENERATOR [args] [options]" puts puts "General options:" @@ -260,74 +202,83 @@ module Rails def self.sorted_groups namespaces = public_namespaces namespaces.sort! + groups = Hash.new { |h,k| h[k] = [] } namespaces.each do |namespace| - base = namespace.split(':').first + base = namespace.split(":").first groups[base] << namespace end + rails = groups.delete("rails") - rails.map! { |n| n.sub(/^rails:/, '') } + rails.map! { |n| n.sub(/^rails:/, "") } rails.delete("app") rails.delete("plugin") hidden_namespaces.each { |n| groups.delete(n.to_s) } - [["rails", rails]] + groups.sort.to_a + [[ "rails", rails ]] + groups.sort.to_a end - protected + # Rails finds namespaces similar to thor, it only adds one rule: + # + # Generators names must end with "_generator.rb". This is required because Rails + # looks in load paths and loads the generator just before it's going to be used. + # + # find_by_namespace :webrat, :rails, :integration + # + # Will search for the following generators: + # + # "rails:webrat", "webrat:integration", "webrat" + # + # Notice that "rails:generators:webrat" could be loaded as well, what + # Rails looks for is the first and last parts of the namespace. + def self.find_by_namespace(name, base = nil, context = nil) #:nodoc: + lookups = [] + lookups << "#{base}:#{name}" if base + lookups << "#{name}:#{context}" if context - # This code is based directly on the Text gem implementation - # Returns a value representing the "cost" of transforming str1 into str2 - def self.levenshtein_distance str1, str2 - s = str1 - t = str2 - n = s.length - m = t.length - - return m if (0 == n) - return n if (0 == m) - - d = (0..m).to_a - x = nil - - # avoid duplicating an enumerable object in the loop - str2_codepoint_enumerable = str2.each_codepoint - - str1.each_codepoint.with_index do |char1, i| - e = i+1 - - str2_codepoint_enumerable.with_index do |char2, j| - cost = (char1 == char2) ? 0 : 1 - x = [ - d[j+1] + 1, # insertion - e + 1, # deletion - d[j] + cost # substitution - ].min - d[j] = e - e = x - end - - d[m] = x + unless base || context + unless name.to_s.include?(?:) + lookups << "#{name}:#{name}" + lookups << "rails:#{name}" end - - x + lookups << "#{name}" end - # Prints a list of generators. - def self.print_list(base, namespaces) #:nodoc: - namespaces = namespaces.reject do |n| - hidden_namespaces.include?(n) - end + lookup(lookups) - return if namespaces.empty? - puts "#{base.camelize}:" + namespaces = Hash[subclasses.map { |klass| [klass.namespace, klass] }] + lookups.each do |namespace| - namespaces.each do |namespace| - puts(" #{namespace}") - end + klass = namespaces[namespace] + return klass if klass + end + + invoke_fallbacks_for(name, base) || invoke_fallbacks_for(context, name) + end - puts + # Receives a namespace, arguments and the behavior to invoke the generator. + # It's used as the default entry point for generate, destroy and update + # commands. + 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?(&:required?) + klass.start(args, config) + else + options = sorted_groups.flat_map(&:last) + suggestions = options.sort_by { |suggested| levenshtein_distance(namespace.to_s, suggested) }.first(3) + msg = "Could not find generator '#{namespace}'. " + msg << "Maybe you meant #{ suggestions.map { |s| "'#{s}'" }.to_sentence(last_word_connector: " or ", locale: :en) }\n" + msg << "Run `rails generate --help` for more options." + puts msg + end + end + + protected + def self.print_list(base, namespaces) + namespaces = namespaces.reject { |n| hidden_namespaces.include?(n) } + super end # Try fallbacks for the given base. @@ -346,53 +297,16 @@ module Rails nil end - # Receives namespaces in an array and tries to find matching generators - # in the load path. - def self.lookup(namespaces) #:nodoc: - paths = namespaces_to_paths(namespaces) - - paths.each do |raw_path| - ["rails/generators", "generators"].each do |base| - path = "#{base}/#{raw_path}_generator" - - begin - require path - return - rescue LoadError => e - raise unless e.message =~ /#{Regexp.escape(path)}$/ - rescue Exception => e - warn "[WARNING] Could not load generator #{path.inspect}. Error: #{e.message}.\n#{e.backtrace.join("\n")}" - end - end - end + def self.command_type + @command_type ||= "generator" end - # This will try to load any generator in the load path to show in help. - def self.lookup! #:nodoc: - $LOAD_PATH.each do |base| - Dir[File.join(base, "{rails/generators,generators}", "**", "*_generator.rb")].each do |path| - begin - path = path.sub("#{base}/", "") - require path - rescue Exception - # No problem - end - end - end + def self.lookup_paths + @lookup_paths ||= %w( rails/generators generators ) end - # Convert namespaces to paths by replacing ":" for "/" and adding - # an extra lookup. For example, "rails:model" should be searched - # in both: "rails/model/model_generator" and "rails/model_generator". - def self.namespaces_to_paths(namespaces) #:nodoc: - paths = [] - namespaces.each do |namespace| - pieces = namespace.split(":") - paths << pieces.dup.push(pieces.last).join("/") - paths << pieces.join("/") - end - paths.uniq! - paths + def self.file_lookup_paths + @file_lookup_paths ||= [ "{#{lookup_paths.join(',')}}", "**", "*_generator.rb" ] end end end diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb index c947c062fa..ab9dc019e2 100644 --- a/railties/lib/rails/generators/actions.rb +++ b/railties/lib/rails/generators/actions.rb @@ -103,7 +103,7 @@ module Rails in_root do if options[:env].nil? - inject_into_file 'config/application.rb', "\n #{data}", after: sentinel, verbose: false + inject_into_file "config/application.rb", "\n #{data}", after: sentinel, verbose: false else Array(options[:env]).each do |env| inject_into_file "config/environments/#{env}.rb", "\n #{data}", after: env_file_sentinel, verbose: false @@ -239,7 +239,7 @@ module Rails sentinel = /\.routes\.draw do\s*\n/m in_root do - inject_into_file 'config/routes.rb', " #{routing_code}\n", { after: sentinel, verbose: false, force: false } + inject_into_file "config/routes.rb", " #{routing_code}\n", after: sentinel, verbose: false, force: false end end @@ -274,19 +274,18 @@ module Rails end end - # Runs the supplied command using either "rake ..." or "rails ..." # based on the executor parameter provided. def execute_command(executor, command, options={}) log executor, command - env = options[:env] || ENV["RAILS_ENV"] || 'development' - sudo = options[:sudo] && RbConfig::CONFIG['host_os'] !~ /mswin|mingw/ ? 'sudo ' : '' + env = options[:env] || ENV["RAILS_ENV"] || "development" + sudo = options[:sudo] && RbConfig::CONFIG["host_os"] !~ /mswin|mingw/ ? "sudo " : "" in_root { run("#{sudo}#{extify(executor)} #{command} RAILS_ENV=#{env}", verbose: false) } end # Add an extension to the given name based on the platform. def extify(name) - if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ + if RbConfig::CONFIG["host_os"] =~ /mswin|mingw/ "#{name}.bat" else name diff --git a/railties/lib/rails/generators/actions/create_migration.rb b/railties/lib/rails/generators/actions/create_migration.rb index 6c5b55466d..587c61fd42 100644 --- a/railties/lib/rails/generators/actions/create_migration.rb +++ b/railties/lib/rails/generators/actions/create_migration.rb @@ -1,11 +1,10 @@ -require 'fileutils' -require 'thor/actions' +require "fileutils" +require "thor/actions" module Rails module Generators module Actions class CreateMigration < Thor::Actions::CreateFile #:nodoc: - def migration_dir File.dirname(@destination) end @@ -40,30 +39,30 @@ module Rails protected - def on_conflict_behavior - options = base.options.merge(config) - if identical? - say_status :identical, :blue, relative_existing_migration - elsif options[:force] - say_status :remove, :green, relative_existing_migration - say_status :create, :green - unless pretend? - ::FileUtils.rm_rf(existing_migration) - yield + def on_conflict_behavior + options = base.options.merge(config) + if identical? + say_status :identical, :blue, relative_existing_migration + elsif options[:force] + say_status :remove, :green, relative_existing_migration + say_status :create, :green + unless pretend? + ::FileUtils.rm_rf(existing_migration) + yield + end + elsif options[:skip] + say_status :skip, :yellow + else + say_status :conflict, :red + raise Error, "Another migration is already named #{migration_file_name}: " + + "#{existing_migration}. Use --force to replace this migration " + + "or --skip to ignore conflicted file." end - elsif options[:skip] - say_status :skip, :yellow - else - say_status :conflict, :red - raise Error, "Another migration is already named #{migration_file_name}: " + - "#{existing_migration}. Use --force to replace this migration " + - "or --skip to ignore conflicted file." end - end - def say_status(status, color, message = relative_destination) - base.shell.say_status(status, message, color) if config[:verbose] - end + def say_status(status, color, message = relative_destination) + base.shell.say_status(status, message, color) if config[:verbose] + end end end end diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index 151bf9a879..91342c592c 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -1,16 +1,16 @@ -require 'fileutils' -require 'digest/md5' -require 'active_support/core_ext/string/strip' -require 'rails/version' unless defined?(Rails::VERSION) -require 'open-uri' -require 'uri' -require 'rails/generators' -require 'active_support/core_ext/array/extract_options' +require "fileutils" +require "digest/md5" +require "active_support/core_ext/string/strip" +require "rails/version" unless defined?(Rails::VERSION) +require "open-uri" +require "uri" +require "rails/generators" +require "active_support/core_ext/array/extract_options" module Rails module Generators class AppBase < Base # :nodoc: - DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db sqlserver ) + DATABASES = %w( mysql postgresql sqlite3 oracle frontbase ibm_db sqlserver ) JDBC_DATABASES = %w( jdbcmysql jdbcsqlite3 jdbcpostgresql jdbc ) DATABASES.concat(JDBC_DATABASES) @@ -24,42 +24,42 @@ module Rails end def self.add_shared_options_for(name) - class_option :template, type: :string, aliases: '-m', + class_option :template, type: :string, aliases: "-m", desc: "Path to some #{name} template (can be a filesystem path or URL)" - class_option :database, type: :string, aliases: '-d', default: 'sqlite3', + class_option :database, type: :string, aliases: "-d", default: "sqlite3", desc: "Preconfigure for selected database (options: #{DATABASES.join('/')})" - class_option :javascript, type: :string, aliases: '-j', default: 'jquery', - desc: 'Preconfigure for selected JavaScript library' + class_option :javascript, type: :string, aliases: "-j", default: "jquery", + desc: "Preconfigure for selected JavaScript library" class_option :skip_gemfile, type: :boolean, default: false, desc: "Don't create a Gemfile" - class_option :skip_bundle, type: :boolean, aliases: '-B', default: false, + class_option :skip_bundle, type: :boolean, aliases: "-B", default: false, desc: "Don't run bundle install" - class_option :skip_git, type: :boolean, aliases: '-G', default: false, - desc: 'Skip .gitignore file' + class_option :skip_git, type: :boolean, aliases: "-G", default: false, + desc: "Skip .gitignore file" class_option :skip_keeps, type: :boolean, default: false, - desc: 'Skip source control .keep files' + 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_active_record, type: :boolean, aliases: "-O", default: false, + desc: "Skip Active Record files" - class_option :skip_puma, type: :boolean, aliases: '-P', default: false, - desc: 'Skip Puma related files' + class_option :skip_puma, type: :boolean, aliases: "-P", default: false, + desc: "Skip Puma related files" - class_option :skip_action_cable, type: :boolean, aliases: '-C', default: false, - desc: 'Skip Action Cable files' + class_option :skip_action_cable, type: :boolean, aliases: "-C", default: false, + desc: "Skip Action Cable files" - class_option :skip_sprockets, type: :boolean, aliases: '-S', default: false, - desc: 'Skip Sprockets files' + class_option :skip_sprockets, type: :boolean, aliases: "-S", default: false, + desc: "Skip Sprockets files" class_option :skip_spring, type: :boolean, default: false, desc: "Don't install Spring application preloader" @@ -67,14 +67,14 @@ module Rails class_option :skip_listen, type: :boolean, default: false, desc: "Don't generate configuration that depends on the listen gem" - class_option :skip_javascript, type: :boolean, aliases: '-J', default: false, - desc: 'Skip JavaScript files' + class_option :skip_javascript, type: :boolean, aliases: "-J", default: false, + desc: "Skip JavaScript files" class_option :skip_turbolinks, type: :boolean, default: false, - desc: 'Skip turbolinks gem' + desc: "Skip turbolinks gem" - class_option :skip_test, type: :boolean, aliases: '-T', default: false, - desc: 'Skip test files' + class_option :skip_test, type: :boolean, aliases: "-T", default: false, + desc: "Skip test files" class_option :dev, type: :boolean, default: false, desc: "Setup the #{name} with Gemfile pointing to your Rails checkout" @@ -86,10 +86,10 @@ module Rails desc: "Path to file containing extra configuration options for rails command" class_option :no_rc, type: :boolean, default: false, - desc: 'Skip loading of extra configuration options from .railsrc file' + desc: "Skip loading of extra configuration options from .railsrc file" - class_option :help, type: :boolean, aliases: '-h', group: :rails, - desc: 'Show this help message and quit' + class_option :help, type: :boolean, aliases: "-h", group: :rails, + desc: "Show this help message and quit" end def initialize(*args) @@ -150,7 +150,7 @@ module Rails def create_root valid_const? - empty_directory '.' + empty_directory "." FileUtils.cd(destination_root) unless options[:pretend] end @@ -162,14 +162,15 @@ module Rails def set_default_accessors! self.destination_root = File.expand_path(app_path, destination_root) - self.rails_template = case options[:template] + self.rails_template = \ + case options[:template] when /^https?:\/\// options[:template] when String File.expand_path(options[:template], Dir.pwd) else options[:template] - end + end end def database_gemfile_entry @@ -181,8 +182,8 @@ module Rails def webserver_gemfile_entry return [] if options[:skip_puma] - comment = 'Use Puma as the app server' - GemfileEntry.new('puma', '~> 3.0', comment) + comment = "Use Puma as the app server" + GemfileEntry.new("puma", "~> 3.0", comment) end def include_all_railties? @@ -190,7 +191,7 @@ module Rails end def comment_if(value) - options[value] ? '# ' : '' + options[value] ? "# " : "" end def keeps? @@ -198,7 +199,7 @@ module Rails end def sqlite3? - !options[:skip_active_record] && options[:database] == 'sqlite3' + !options[:skip_active_record] && options[:database] == "sqlite3" end class GemfileEntry < Struct.new(:name, :version, :comment, :options, :commented_out) @@ -238,14 +239,14 @@ module Rails ] if options.dev? [ - GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH) + GemfileEntry.path("rails", Rails::Generators::RAILS_DEV_PATH) ] + dev_edge_common elsif options.edge? [ - GemfileEntry.github('rails', 'rails/rails') + GemfileEntry.github("rails", "rails/rails") ] + dev_edge_common else - [GemfileEntry.version('rails', + [GemfileEntry.version("rails", rails_version_specifier, "Bundle edge Rails instead: gem 'rails', github: 'rails/rails'")] end @@ -266,12 +267,12 @@ module Rails end def gem_for_database - # %w( mysql oracle postgresql sqlite3 frontbase ibm_db sqlserver jdbcmysql jdbcsqlite3 jdbcpostgresql ) + # %w( mysql postgresql sqlite3 oracle frontbase ibm_db sqlserver jdbcmysql jdbcsqlite3 jdbcpostgresql ) case options[:database] - when "oracle" then ["ruby-oci8", nil] + when "mysql" then ["mysql2", [">= 0.3.18", "< 0.5"]] when "postgresql" then ["pg", ["~> 0.18"]] + when "oracle" then ["ruby-oci8", nil] when "frontbase" then ["ruby-frontbase", nil] - when "mysql" then ["mysql2", [">= 0.3.18", "< 0.5"]] when "sqlserver" then ["activerecord-sqlserver-adapter", nil] when "jdbcmysql" then ["activerecord-jdbcmysql-adapter", nil] when "jdbcsqlite3" then ["activerecord-jdbcsqlite3-adapter", nil] @@ -284,9 +285,9 @@ module Rails def convert_database_option_for_jruby if defined?(JRUBY_VERSION) case options[:database] - when "oracle" then options[:database].replace "jdbc" when "postgresql" then options[:database].replace "jdbcpostgresql" when "mysql" then options[:database].replace "jdbcmysql" + when "oracle" then options[:database].replace "jdbc" when "sqlite3" then options[:database].replace "jdbcsqlite3" end end @@ -296,23 +297,25 @@ module Rails return [] if options[:skip_sprockets] gems = [] - gems << GemfileEntry.version('sass-rails', '~> 5.0', - 'Use SCSS for stylesheets') + gems << GemfileEntry.github("sass-rails", "rails/sass-rails", nil, + "Use SCSS for stylesheets") - gems << GemfileEntry.version('uglifier', - '>= 1.3.0', - 'Use Uglifier as compressor for JavaScript assets') + if !options[:skip_javascript] + gems << GemfileEntry.version("uglifier", + ">= 1.3.0", + "Use Uglifier as compressor for JavaScript assets") + end gems end def jbuilder_gemfile_entry - comment = 'Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder' - GemfileEntry.new 'jbuilder', '~> 2.0', comment, {}, options[:api] + comment = "Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder" + GemfileEntry.new "jbuilder", "~> 2.5", comment, {}, options[:api] end def coffee_gemfile_entry - GemfileEntry.version 'coffee-rails', '~> 4.1.0', 'Use CoffeeScript for .coffee assets and views' + GemfileEntry.version "coffee-rails", "~> 4.2", "Use CoffeeScript for .coffee assets and views" end def javascript_gemfile_entry @@ -324,7 +327,7 @@ module Rails "Use #{options[:javascript]} as the JavaScript library") unless options[:skip_turbolinks] - gems << GemfileEntry.version("turbolinks", "~> 5.x", + gems << GemfileEntry.version("turbolinks", "~> 5", "Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks") end @@ -333,27 +336,27 @@ module Rails end def javascript_runtime_gemfile_entry - comment = 'See https://github.com/rails/execjs#readme for more supported runtimes' + comment = "See https://github.com/rails/execjs#readme for more supported runtimes" if defined?(JRUBY_VERSION) - GemfileEntry.version 'therubyrhino', nil, comment + GemfileEntry.version "therubyrhino", nil, comment else - GemfileEntry.new 'therubyracer', nil, comment, { platforms: :ruby }, true + GemfileEntry.new "therubyracer", nil, comment, { platforms: :ruby }, true end end def psych_gemfile_entry return [] unless defined?(Rubinius) - comment = 'Use Psych as the YAML engine, instead of Syck, so serialized ' \ - 'data can be read safely from different rubies (see http://git.io/uuLVag)' - GemfileEntry.new('psych', '~> 2.0', comment, platforms: :rbx) + comment = "Use Psych as the YAML engine, instead of Syck, so serialized " \ + "data can be read safely from different rubies (see http://git.io/uuLVag)" + GemfileEntry.new("psych", "~> 2.0", comment, platforms: :rbx) end def cable_gemfile_entry return [] if options[:skip_action_cable] - comment = 'Use Redis adapter to run Action Cable in production' + comment = "Use Redis adapter to run Action Cable in production" gems = [] - gems << GemfileEntry.new("redis", '~> 3.0', comment, {}, true) + gems << GemfileEntry.new("redis", "~> 3.0", comment, {}, true) gems end @@ -368,9 +371,9 @@ module Rails # We unset temporary bundler variables to load proper bundler and Gemfile. # # Thanks to James Tucker for the Gem tricks involved in this call. - _bundle_command = Gem.bin_path('bundler', 'bundle') + _bundle_command = Gem.bin_path("bundler", "bundle") - require 'bundler' + require "bundler" Bundler.with_clean_env do full_command = %Q["#{Gem.ruby}" "#{_bundle_command}" #{command}] if options[:quiet] @@ -394,11 +397,11 @@ module Rails end def os_supports_listen_out_of_the_box? - RbConfig::CONFIG['host_os'] =~ /darwin|linux/ + RbConfig::CONFIG["host_os"] =~ /darwin|linux/ end def run_bundle - bundle_command('install') if bundle_install? + bundle_command("install") if bundle_install? end def generate_spring_binstubs diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb index c72ec400a0..1a0420c769 100644 --- a/railties/lib/rails/generators/base.rb +++ b/railties/lib/rails/generators/base.rb @@ -1,5 +1,5 @@ begin - require 'thor/group' + require "thor/group" rescue LoadError puts "Thor is not available.\nIf you ran this command from a git checkout " \ "of Rails, please make sure thor is installed,\nand run this command " \ @@ -42,13 +42,13 @@ module Rails # is removed. def self.namespace(name=nil) return super if name - @namespace ||= super.sub(/_generator$/, '').sub(/:generators:/, ':') + @namespace ||= super.sub(/_generator$/, "").sub(/:generators:/, ":") end # Convenience method to hide this generator from the available ones when # running rails generator command. def self.hide! - Rails::Generators.hide_namespace self.namespace + Rails::Generators.hide_namespace(namespace) end # Invoke a generator based on the value supplied by the user to the @@ -168,7 +168,7 @@ module Rails names.each do |name| unless class_options.key?(name) defaults = if options[:type] == :boolean - { } + {} elsif [true, false].include?(default_value_for_option(name, options)) { banner: "" } else @@ -208,7 +208,7 @@ module Rails def self.default_source_root return unless base_name && generator_name return unless default_generator_root - path = File.join(default_generator_root, 'templates') + path = File.join(default_generator_root, "templates") path if File.exist?(path) end @@ -230,7 +230,7 @@ module Rails Rails::Generators.subclasses << base Rails::Generators.templates_path.each do |path| - if base.name.include?('::') + if base.name.include?("::") base.source_paths << File.join(path, base.base_name, base.generator_name) else base.source_paths << File.join(path, base.generator_name) @@ -251,7 +251,7 @@ module Rails next if class_name.strip.empty? # Split the class from its module nesting - nesting = class_name.split('::') + nesting = class_name.split("::") last_name = nesting.pop last = extract_last_module(nesting) @@ -273,13 +273,13 @@ module Rails # Use Rails default banner. def self.banner - "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map(&:usage).join(' ')} [options]".gsub(/\s+/, ' ') + "rails generate #{namespace.sub(/^rails:/,'')} #{arguments.map(&:usage).join(' ')} [options]".gsub(/\s+/, " ") end # Sets the base_name taking into account the current class namespace. def self.base_name @base_name ||= begin - if base = name.to_s.split('::').first + if base = name.to_s.split("::").first base.underscore end end @@ -289,8 +289,8 @@ module Rails # Rails::Generators::ModelGenerator will return "model" as generator name. def self.generator_name @generator_name ||= begin - if generator = name.to_s.split('::').last - generator.sub!(/Generator$/, '') + if generator = name.to_s.split("::").last + generator.sub!(/Generator$/, "") generator.underscore end end @@ -310,9 +310,9 @@ module Rails # Returns default for the option name given doing a lookup in config. def self.default_for_option(config, name, options, default) - if generator_name and c = config[generator_name.to_sym] and c.key?(name) + if generator_name && (c = config[generator_name.to_sym]) && c.key?(name) c[name] - elsif base_name and c = config[base_name.to_sym] and c.key?(name) + elsif base_name && (c = config[base_name.to_sym]) && c.key?(name) c[name] elsif config[:rails].key?(name) config[:rails][name] @@ -373,7 +373,6 @@ module Rails path = File.expand_path(File.join(base_name, generator_name), base_root) path if File.exist?(path) end - end end end diff --git a/railties/lib/rails/generators/css/assets/assets_generator.rb b/railties/lib/rails/generators/css/assets/assets_generator.rb index e4a305f4b3..20baf31a34 100644 --- a/railties/lib/rails/generators/css/assets/assets_generator.rb +++ b/railties/lib/rails/generators/css/assets/assets_generator.rb @@ -6,7 +6,7 @@ module Css # :nodoc: source_root File.expand_path("../templates", __FILE__) def copy_stylesheet - copy_file "stylesheet.css", File.join('app/assets/stylesheets', class_path, "#{file_name}.css") + copy_file "stylesheet.css", File.join("app/assets/stylesheets", class_path, "#{file_name}.css") end end end diff --git a/railties/lib/rails/generators/erb.rb b/railties/lib/rails/generators/erb.rb index 0755ac335c..d01502002f 100644 --- a/railties/lib/rails/generators/erb.rb +++ b/railties/lib/rails/generators/erb.rb @@ -1,25 +1,25 @@ -require 'rails/generators/named_base' +require "rails/generators/named_base" module Erb # :nodoc: module Generators # :nodoc: class Base < Rails::Generators::NamedBase #:nodoc: protected - def formats - [format] - end + def formats + [format] + end - def format - :html - end + def format + :html + end - def handler - :erb - end + def handler + :erb + end - def filename_with_extensions(name, format = self.format) - [name, format, handler].compact.join(".") - end + def filename_with_extensions(name, format = self.format) + [name, format, handler].compact.join(".") + end end end end diff --git a/railties/lib/rails/generators/erb/controller/controller_generator.rb b/railties/lib/rails/generators/erb/controller/controller_generator.rb index 94c1b835d1..36ecfea09b 100644 --- a/railties/lib/rails/generators/erb/controller/controller_generator.rb +++ b/railties/lib/rails/generators/erb/controller/controller_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/erb' +require "rails/generators/erb" module Erb # :nodoc: module Generators # :nodoc: diff --git a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb index 7f00943d80..f150240908 100644 --- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/erb' +require "rails/generators/erb" module Erb # :nodoc: module Generators # :nodoc: @@ -6,9 +6,16 @@ module Erb # :nodoc: argument :actions, type: :array, default: [], banner: "method method" def copy_view_files - view_base_path = File.join("app/views", class_path, file_name + '_mailer') + view_base_path = File.join("app/views", class_path, file_name + "_mailer") empty_directory view_base_path + if self.behavior == :invoke + formats.each do |format| + layout_path = File.join("app/views/layouts", class_path, filename_with_extensions("mailer", format)) + template filename_with_extensions(:layout, format), layout_path + end + end + actions.each do |action| @action = action @@ -21,13 +28,13 @@ module Erb # :nodoc: protected - def formats - [:text, :html] - end + def formats + [:text, :html] + end - def file_name - @_file_name ||= super.gsub(/_mailer/i, '') - end + def file_name + @_file_name ||= super.gsub(/_mailer/i, "") + end end end end diff --git a/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb.tt b/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb.tt new file mode 100644 index 0000000000..55f3675d49 --- /dev/null +++ b/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb.tt @@ -0,0 +1,13 @@ +<!DOCTYPE html> +<html> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> + <style> + /* Email styles need to be inline */ + </style> + </head> + + <body> + <%%= yield %> + </body> +</html> diff --git a/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb.tt b/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb.tt new file mode 100644 index 0000000000..6363733e6e --- /dev/null +++ b/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb.tt @@ -0,0 +1 @@ +<%%= yield %> diff --git a/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb index c94829a0ae..154d85f381 100644 --- a/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb +++ b/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb @@ -1,5 +1,5 @@ -require 'rails/generators/erb' -require 'rails/generators/resource_helpers' +require "rails/generators/erb" +require "rails/generators/resource_helpers" module Erb # :nodoc: module Generators # :nodoc: diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb index 7e437e7344..61181b7b97 100644 --- a/railties/lib/rails/generators/generated_attribute.rb +++ b/railties/lib/rails/generators/generated_attribute.rb @@ -1,4 +1,4 @@ -require 'active_support/time' +require "active_support/time" module Rails module Generators @@ -12,7 +12,7 @@ module Rails class << self def parse(column_definition) - name, type, has_index = column_definition.split(':') + name, type, has_index = column_definition.split(":") # if user provided "name:index" instead of "name:string:index" # type should be set blank so GeneratedAttribute's constructor @@ -66,40 +66,40 @@ module Rails def field_type @field_type ||= case type - when :integer then :number_field - when :float, :decimal then :text_field - when :time then :time_select - when :datetime, :timestamp then :datetime_select - when :date then :date_select - when :text then :text_area - when :boolean then :check_box + when :integer then :number_field + when :float, :decimal then :text_field + when :time then :time_select + when :datetime, :timestamp then :datetime_select + when :date then :date_select + when :text then :text_area + when :boolean then :check_box else - :text_field + :text_field end end def default @default ||= case type - when :integer then 1 - when :float then 1.5 - when :decimal then "9.99" - when :datetime, :timestamp, :time then Time.now.to_s(:db) - when :date then Date.today.to_s(:db) - when :string then name == "type" ? "" : "MyString" - when :text then "MyText" - when :boolean then false - when :references, :belongs_to then nil + when :integer then 1 + when :float then 1.5 + when :decimal then "9.99" + when :datetime, :timestamp, :time then Time.now.to_s(:db) + when :date then Date.today.to_s(:db) + when :string then name == "type" ? "" : "MyString" + when :text then "MyText" + when :boolean then false + when :references, :belongs_to then nil else - "" + "" end end def plural_name - name.sub(/_id$/, '').pluralize + name.sub(/_id$/, "").pluralize end def singular_name - name.sub(/_id$/, '').singularize + name.sub(/_id$/, "").singularize end def human_name @@ -127,11 +127,11 @@ module Rails end def polymorphic? - self.attr_options[:polymorphic] + attr_options[:polymorphic] end def required? - self.attr_options[:required] + attr_options[:required] end def has_index? @@ -143,7 +143,7 @@ module Rails end def password_digest? - name == 'password' && type == :digest + name == "password" && type == :digest end def token? diff --git a/railties/lib/rails/generators/js/assets/assets_generator.rb b/railties/lib/rails/generators/js/assets/assets_generator.rb index 1e925b2cd2..64d706ec91 100644 --- a/railties/lib/rails/generators/js/assets/assets_generator.rb +++ b/railties/lib/rails/generators/js/assets/assets_generator.rb @@ -6,7 +6,7 @@ module Js # :nodoc: source_root File.expand_path("../templates", __FILE__) def copy_javascript - copy_file "javascript.js", File.join('app/assets/javascripts', class_path, "#{file_name}.js") + copy_file "javascript.js", File.join("app/assets/javascripts", class_path, "#{file_name}.js") end end end diff --git a/railties/lib/rails/generators/migration.rb b/railties/lib/rails/generators/migration.rb index 87f2e1d42b..7290e235a1 100644 --- a/railties/lib/rails/generators/migration.rb +++ b/railties/lib/rails/generators/migration.rb @@ -1,5 +1,5 @@ -require 'active_support/concern' -require 'rails/generators/actions/create_migration' +require "active_support/concern" +require "rails/generators/actions/create_migration" module Rails module Generators @@ -39,7 +39,7 @@ module Rails migration_dir = File.dirname(destination) @migration_number = self.class.next_migration_number(migration_dir) - @migration_file_name = File.basename(destination, '.rb') + @migration_file_name = File.basename(destination, ".rb") @migration_class_name = @migration_file_name.camelize end @@ -55,13 +55,13 @@ module Rails source = File.expand_path(find_in_source_paths(source.to_s)) set_migration_assigns!(destination) - context = instance_eval('binding') + context = instance_eval("binding") dir, base = File.split(destination) - numbered_destination = File.join(dir, ["%migration_number%", base].join('_')) + numbered_destination = File.join(dir, ["%migration_number%", base].join("_")) create_migration numbered_destination, nil, config do - ERB.new(::File.binread(source), nil, '-', '@output_buffer').result(context) + ERB.new(::File.binread(source), nil, "-", "@output_buffer").result(context) end end end diff --git a/railties/lib/rails/generators/model_helpers.rb b/railties/lib/rails/generators/model_helpers.rb index 42c646543e..6f87a18660 100644 --- a/railties/lib/rails/generators/model_helpers.rb +++ b/railties/lib/rails/generators/model_helpers.rb @@ -1,4 +1,4 @@ -require 'rails/generators/active_model' +require "rails/generators/active_model" module Rails module Generators @@ -8,7 +8,7 @@ module Rails mattr_accessor :skip_warn def self.included(base) #:nodoc: - base.class_option :force_plural, type: :boolean, default: false, desc: 'Forces the use of the given model name' + base.class_option :force_plural, type: :boolean, default: false, desc: "Forces the use of the given model name" end def initialize(args, *_options) diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb index efbf51ddfb..c39ea24935 100644 --- a/railties/lib/rails/generators/named_base.rb +++ b/railties/lib/rails/generators/named_base.rb @@ -1,6 +1,6 @@ -require 'active_support/core_ext/module/introspection' -require 'rails/generators/base' -require 'rails/generators/generated_attribute' +require "active_support/core_ext/module/introspection" +require "rails/generators/base" +require "rails/generators/generated_attribute" module Rails module Generators @@ -14,7 +14,7 @@ module Rails # Unfreeze name in case it's given as a frozen string args[0] = args[0].dup if args[0].is_a?(String) && args[0].frozen? super - assign_names!(self.name) + assign_names!(name) parse_attributes! if respond_to?(:attributes) end @@ -26,6 +26,10 @@ module Rails super end end + + def js_template(source, destination) + template(source + ".js", destination + ".js") + end end protected @@ -47,7 +51,7 @@ module Rails def indent(content, multiplier = 2) spaces = " " * multiplier - content.each_line.map {|line| line.blank? ? line : "#{spaces}#{line}" }.join + content.each_line.map { |line| line.blank? ? line : "#{spaces}#{line}" }.join end def wrap_with_namespace(content) @@ -75,7 +79,7 @@ module Rails end def file_path - @file_path ||= (class_path + [file_name]).join('/') + @file_path ||= (class_path + [file_name]).join("/") end def class_path @@ -99,7 +103,7 @@ module Rails end def class_name - (class_path + [file_name]).map!(&:camelize).join('::') + (class_path + [file_name]).map!(&:camelize).join("::") end def human_name @@ -111,13 +115,13 @@ module Rails end def i18n_scope - @i18n_scope ||= file_path.tr('/', '.') + @i18n_scope ||= file_path.tr("/", ".") end def table_name @table_name ||= begin base = pluralize_table_names? ? plural_name : singular_name - (class_path + [base]).join('_') + (class_path + [base]).join("_") end end @@ -158,24 +162,24 @@ module Rails end def route_url - @route_url ||= class_path.collect {|dname| "/" + dname }.join + "/" + plural_file_name + @route_url ||= class_path.collect { |dname| "/" + dname }.join + "/" + plural_file_name end def url_helper_prefix - @url_helper_prefix ||= (class_path + [file_name]).join('_') + @url_helper_prefix ||= (class_path + [file_name]).join("_") end # 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 + Rails.application.class.name.split("::").first.underscore else "application" end end def assign_names!(name) #:nodoc: - @class_path = name.include?('/') ? name.split('/') : name.split('::') + @class_path = name.include?("/") ? name.split("/") : name.split("::") @class_path.map!(&:underscore) @file_name = @class_path.pop end @@ -190,7 +194,7 @@ module Rails def attributes_names @attributes_names ||= attributes.each_with_object([]) do |a, names| names << a.column_name - names << 'password_confirmation' if a.password_digest? + names << "password_confirmation" if a.password_digest? names << "#{a.name}_type" if a.polymorphic? end end diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index 4d5bb364b2..9f9c50ca10 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/app_base' +require "rails/generators/app_base" module Rails module ActionMethods # :nodoc: @@ -54,13 +54,13 @@ module Rails end def app - directory 'app' + directory "app" - keep_file 'app/assets/images' - empty_directory_with_keep_file 'app/assets/javascripts/channels' unless options[:skip_action_cable] + keep_file "app/assets/images" + empty_directory_with_keep_file "app/assets/javascripts/channels" unless options[:skip_action_cable] - keep_file 'app/controllers/concerns' - keep_file 'app/models/concerns' + keep_file "app/controllers/concerns" + keep_file "app/models/concerns" end def bin @@ -89,44 +89,24 @@ module Rails end 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') - active_record_belongs_to_required_by_default_config_exist = File.exist?('config/initializers/active_record_belongs_to_required_by_default.rb') - to_time_preserves_timezone_config_exist = File.exist?('config/initializers/to_time_preserves_timezone.rb') - action_cable_config_exist = File.exist?('config/cable.yml') - ssl_options_exist = File.exist?('config/initializers/ssl_options.rb') - rack_cors_config_exist = File.exist?('config/initializers/cors.rb') + cookie_serializer_config_exist = File.exist?("config/initializers/cookies_serializer.rb") + action_cable_config_exist = File.exist?("config/cable.yml") + rack_cors_config_exist = File.exist?("config/initializers/cors.rb") config - gsub_file 'config/environments/development.rb', /^(\s+)config\.file_watcher/, '\1# config.file_watcher' - - unless callback_terminator_config_exist - remove_file 'config/initializers/callback_terminator.rb' - end + gsub_file "config/environments/development.rb", /^(\s+)config\.file_watcher/, '\1# config.file_watcher' unless cookie_serializer_config_exist - gsub_file 'config/initializers/cookies_serializer.rb', /json(?!,)/, 'marshal' - end - - unless active_record_belongs_to_required_by_default_config_exist - remove_file 'config/initializers/active_record_belongs_to_required_by_default.rb' - end - - unless to_time_preserves_timezone_config_exist - remove_file 'config/initializers/to_time_preserves_timezone.rb' + gsub_file "config/initializers/cookies_serializer.rb", /json(?!,)/, "marshal" end unless action_cable_config_exist - template 'config/cable.yml' - end - - unless ssl_options_exist - remove_file 'config/initializers/ssl_options.rb' + template "config/cable.yml" end unless rack_cors_config_exist - remove_file 'config/initializers/cors.rb' + remove_file "config/initializers/cors.rb" end end @@ -139,13 +119,13 @@ module Rails end def lib - empty_directory 'lib' - empty_directory_with_keep_file 'lib/tasks' - empty_directory_with_keep_file 'lib/assets' + empty_directory "lib" + empty_directory_with_keep_file "lib/tasks" + empty_directory_with_keep_file "lib/assets" end def log - empty_directory_with_keep_file 'log' + empty_directory_with_keep_file "log" end def public_directory @@ -153,15 +133,15 @@ module Rails end def test - empty_directory_with_keep_file 'test/fixtures' - empty_directory_with_keep_file 'test/fixtures/files' - empty_directory_with_keep_file 'test/controllers' - empty_directory_with_keep_file 'test/mailers' - empty_directory_with_keep_file 'test/models' - empty_directory_with_keep_file 'test/helpers' - empty_directory_with_keep_file 'test/integration' - - template 'test/test_helper.rb' + empty_directory_with_keep_file "test/fixtures" + empty_directory_with_keep_file "test/fixtures/files" + empty_directory_with_keep_file "test/controllers" + empty_directory_with_keep_file "test/mailers" + empty_directory_with_keep_file "test/models" + empty_directory_with_keep_file "test/helpers" + empty_directory_with_keep_file "test/integration" + + template "test/test_helper.rb" end def tmp @@ -177,12 +157,12 @@ module Rails def vendor_javascripts unless options[:skip_javascript] - empty_directory_with_keep_file 'vendor/assets/javascripts' + empty_directory_with_keep_file "vendor/assets/javascripts" end end def vendor_stylesheets - empty_directory_with_keep_file 'vendor/assets/stylesheets' + empty_directory_with_keep_file "vendor/assets/stylesheets" end end @@ -246,6 +226,11 @@ module Rails end remove_task :update_config_files + def display_upgrade_guide_info + say "\nAfter this, check Rails upgrade guide at http://guides.rubyonrails.org/upgrading_ruby_on_rails.html for more details about upgrading your app." + end + remove_task :display_upgrade_guide_info + def create_boot_file template "config/boot.rb" end @@ -285,78 +270,82 @@ module Rails def delete_app_assets_if_api_option if options[:api] - remove_dir 'app/assets' - remove_dir 'lib/assets' - remove_dir 'tmp/cache/assets' - remove_dir 'vendor/assets' + remove_dir "app/assets" + remove_dir "lib/assets" + remove_dir "tmp/cache/assets" + remove_dir "vendor/assets" end end def delete_app_helpers_if_api_option if options[:api] - remove_dir 'app/helpers' - remove_dir 'test/helpers' + remove_dir "app/helpers" + remove_dir "test/helpers" end end def delete_application_layout_file_if_api_option if options[:api] - remove_file 'app/views/layouts/application.html.erb' + remove_file "app/views/layouts/application.html.erb" + end + end + + def delete_public_files_if_api_option + if options[:api] + remove_file "public/404.html" + remove_file "public/422.html" + remove_file "public/500.html" + remove_file "public/apple-touch-icon-precomposed.png" + remove_file "public/apple-touch-icon.png" + remove_file "public/favicon.ico" end end def delete_js_folder_skipping_javascript if options[:skip_javascript] - remove_dir 'app/assets/javascripts' + remove_dir "app/assets/javascripts" end end def delete_assets_initializer_skipping_sprockets if options[:skip_sprockets] - remove_file 'config/initializers/assets.rb' + remove_file "config/initializers/assets.rb" end end def delete_application_record_skipping_active_record if options[:skip_active_record] - remove_file 'app/models/application_record.rb' + remove_file "app/models/application_record.rb" end end def delete_action_mailer_files_skipping_action_mailer if options[:skip_action_mailer] - remove_file 'app/mailers/application_mailer.rb' - remove_file 'app/views/layouts/mailer.html.erb' - remove_file 'app/views/layouts/mailer.text.erb' - end - end - - def delete_active_record_initializers_skipping_active_record - if options[:skip_active_record] - remove_file 'config/initializers/active_record_belongs_to_required_by_default.rb' + remove_file "app/mailers/application_mailer.rb" + remove_file "app/views/layouts/mailer.html.erb" + remove_file "app/views/layouts/mailer.text.erb" + remove_dir "app/mailers" + remove_dir "test/mailers" end end def delete_action_cable_files_skipping_action_cable if options[:skip_action_cable] - remove_file 'config/cable.yml' - remove_file 'app/assets/javascripts/cable.js' - remove_dir 'app/channels' + remove_file "config/cable.yml" + remove_file "app/assets/javascripts/cable.js" + remove_dir "app/channels" end end def delete_non_api_initializers_if_api_option if options[:api] - remove_file 'config/initializers/session_store.rb' - remove_file 'config/initializers/cookies_serializer.rb' - remove_file 'config/initializers/request_forgery_protection.rb' - remove_file 'config/initializers/per_form_csrf_tokens.rb' + remove_file "config/initializers/cookies_serializer.rb" end end def delete_api_initializers unless options[:api] - remove_file 'config/initializers/cors.rb' + remove_file "config/initializers/cors.rb" end end @@ -374,7 +363,7 @@ module Rails protected def self.banner - "rails new #{self.arguments.map(&:usage).join(' ')} [options]" + "rails new #{arguments.map(&:usage).join(' ')} [options]" end # Define file as an alias to create_file for backwards compatibility. @@ -383,7 +372,7 @@ module Rails end def app_name - @app_name ||= (defined_app_const_base? ? defined_app_name : File.basename(destination_root)).tr('\\', '').tr(". ", "_") + @app_name ||= (defined_app_const_base? ? defined_app_name : File.basename(destination_root)).tr('\\', "").tr(". ", "_") end def defined_app_name @@ -398,7 +387,7 @@ module Rails alias :defined_app_const_base? :defined_app_const_base def app_const_base - @app_const_base ||= defined_app_const_base || app_name.gsub(/\W/, '_').squeeze('_').camelize + @app_const_base ||= defined_app_const_base || app_name.gsub(/\W/, "_").squeeze("_").camelize end alias :camelized :app_const_base @@ -433,7 +422,7 @@ module Rails "/opt/local/var/run/mysql4/mysqld.sock", # mac + darwinports + mysql4 "/opt/local/var/run/mysql5/mysqld.sock", # mac + darwinports + mysql5 "/opt/lampp/var/mysql/mysql.sock" # xampp for linux - ].find { |f| File.exist?(f) } unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ + ].find { |f| File.exist?(f) } unless RbConfig::CONFIG["host_os"] =~ /mswin|mingw/ end def get_builder_class @@ -461,14 +450,14 @@ module Rails end def self.default_rc_file - File.expand_path('~/.railsrc') + File.expand_path("~/.railsrc") end private def handle_version_request!(argument) - if ['--version', '-v'].include?(argument) - require 'rails/version' + if ["--version", "-v"].include?(argument) + require "rails/version" puts "Rails #{Rails::VERSION::STRING}" exit(0) end @@ -478,20 +467,20 @@ module Rails if argument == "new" yield else - ['--help'] + argv.drop(1) + ["--help"] + argv.drop(1) end end def handle_rails_rc!(argv) - if argv.find { |arg| arg == '--no-rc' } - argv.reject { |arg| arg == '--no-rc' } + if argv.find { |arg| arg == "--no-rc" } + argv.reject { |arg| arg == "--no-rc" } else railsrc(argv) { |rc_argv, rc| insert_railsrc_into_argv!(rc_argv, rc) } end end def railsrc(argv) - if (customrc = argv.index{ |x| x.include?("--rc=") }) + if (customrc = argv.index { |x| x.include?("--rc=") }) fname = File.expand_path(argv[customrc].gsub(/--rc=/, "")) yield(argv.take(customrc) + argv.drop(customrc + 1), fname) else diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile index 86143ca1f1..422217286c 100644 --- a/railties/lib/rails/generators/rails/app/templates/Gemfile +++ b/railties/lib/rails/generators/rails/app/templates/Gemfile @@ -35,11 +35,11 @@ group :development do <%- if options.dev? || options.edge? -%> gem 'web-console', github: 'rails/web-console' <%- else -%> - gem 'web-console' + gem 'web-console', '>= 3.3.0' <%- end -%> <%- end -%> <% if depend_on_listen? -%> - gem 'listen', '~> 3.0.5' + gem 'listen', '>= 3.0.5', '< 3.2' <% end -%> <% if spring_install? -%> # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt b/railties/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt index f4ee1409af..70b579d10e 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt +++ b/railties/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt @@ -1,6 +1,4 @@ -<% unless options.api? -%> //= link_tree ../images -<% end -%> <% unless options.skip_javascript -%> //= link_directory ../javascripts .js <% end -%> diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.js b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.js index 71ee1e66de..739aa5f022 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.js +++ b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.js @@ -1,5 +1,5 @@ // Action Cable provides the framework to deal with WebSockets in Rails. -// You can generate new channels where WebSocket features live using the rails generate channel command. +// You can generate new channels where WebSocket features live using the `rails generate channel` command. // //= require action_cable //= require_self diff --git a/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb b/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb index d56fa30f4d..d672697283 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb +++ b/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb @@ -1,4 +1,3 @@ -# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. module ApplicationCable class Channel < ActionCable::Channel::Base end diff --git a/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb b/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb index b4f41389ad..0ff5442f47 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb +++ b/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb @@ -1,4 +1,3 @@ -# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. module ApplicationCable class Connection < ActionCable::Connection::Base end diff --git a/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt b/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt index f726fd6305..413354186d 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt @@ -1,7 +1,5 @@ class ApplicationController < ActionController::<%= options[:api] ? "API" : "Base" %> <%- unless options[:api] -%> - # Prevent CSRF attacks by raising an exception. - # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception <%- end -%> end diff --git a/railties/lib/rails/generators/rails/app/templates/config/cable.yml b/railties/lib/rails/generators/rails/app/templates/config/cable.yml index aa4e832748..0bbde6f74f 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/cable.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/cable.yml @@ -1,10 +1,9 @@ -# Action Cable uses Redis by default to administer connections, channels, and sending/receiving messages over the WebSocket. -production: - adapter: redis - url: redis://localhost:6379/1 - development: adapter: async test: adapter: async + +production: + adapter: redis + url: redis://localhost:6379/1 diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml index 34fc0e3465..917b52e535 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml @@ -8,6 +8,7 @@ # default: &default adapter: frontbase + pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> host: localhost username: <%= app_name %> password: '' diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml index 187ff01bac..d40117a27f 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml @@ -34,6 +34,7 @@ # default: &default adapter: ibm_db + pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> username: db2inst1 password: #schema: db2inst1 diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbc.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbc.yml index db0a429753..563be77710 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbc.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbc.yml @@ -38,6 +38,7 @@ default: &default adapter: jdbc + pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> username: <%= app_name %> password: driver: diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml index f2c4922e7d..a2b2a64ba6 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml @@ -11,6 +11,7 @@ # default: &default adapter: mysql + pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> username: root password: host: localhost diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml index 80ceb9df92..70df04079d 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml @@ -6,6 +6,7 @@ default: &default adapter: postgresql encoding: unicode + pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> development: <<: *default diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml index 28c36eb82f..371415e6a8 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml @@ -6,6 +6,7 @@ # default: &default adapter: sqlite3 + pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> development: <<: *default 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 193423e84a..d987cf303b 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 @@ -12,7 +12,7 @@ default: &default adapter: mysql2 encoding: utf8 - pool: 5 + pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> username: root password: <% if mysql_socket -%> diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml index 9aedcc15cb..d2499ea4fb 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml @@ -18,6 +18,7 @@ # default: &default adapter: oracle + pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> username: <%= app_name %> password: diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml index bd5c0b10f6..145cfb7f74 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml @@ -17,7 +17,7 @@ default: &default adapter: postgresql encoding: unicode - # For details on connection pooling, see rails configuration guide + # For details on connection pooling, see Rails configuration guide # http://guides.rubyonrails.org/configuring.html#database-pooling pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml index 1c1a37ca8d..9510568124 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml @@ -6,7 +6,7 @@ # default: &default adapter: sqlite3 - pool: 5 + pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> timeout: 5000 development: diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml index 30b0df34a8..c223d6bc62 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml @@ -25,6 +25,7 @@ default: &default adapter: sqlserver encoding: utf8 + pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> reconnect: false username: <%= app_name %> password: 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 7a537610e9..511b4a82eb 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 @@ -18,7 +18,7 @@ Rails.application.configure do config.cache_store = :memory_store config.public_file_server.headers = { - 'Cache-Control' => 'public, max-age=172800' + 'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}" } else config.action_controller.perform_caching = false @@ -46,6 +46,9 @@ Rails.application.configure do # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true + + # Suppress logger output for asset requests. + config.assets.quiet = true <%- end -%> # Raises error for missing translations 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 6bd5e42251..7deab5dbb1 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 @@ -19,8 +19,12 @@ Rails.application.configure do config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? <%- unless options.skip_sprockets? -%> + <%- if options.skip_javascript? -%> + # Compress CSS. + <%- else -%> # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier + <%- end -%> # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. @@ -37,12 +41,10 @@ Rails.application.configure do # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX <%- unless options[:skip_action_cable] -%> - # Action Cable endpoint configuration + # Mount Action Cable outside main process or domain + # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] - - # Don't mount Action Cable in the main server process. - # config.action_cable.mount_path = nil <%- end -%> # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 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 42fee3b036..56416b3075 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 @@ -15,7 +15,7 @@ Rails.application.configure do # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { - 'Cache-Control' => 'public, max-age=3600' + 'Cache-Control' => "public, max-age=#{1.hour.seconds.to_i}" } # Show full error reports and disable caching. diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/active_record_belongs_to_required_by_default.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/active_record_belongs_to_required_by_default.rb deleted file mode 100644 index f613b40f80..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/active_record_belongs_to_required_by_default.rb +++ /dev/null @@ -1,6 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Require `belongs_to` associations by default. This is a new Rails 5.0 -# default, so it is introduced as a configuration option to ensure that apps -# made on earlier versions of Rails are not affected when upgrading. -Rails.application.config.active_record.belongs_to_required_by_default = true 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 01ef3e6630..2318cf59ff 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 @@ -7,5 +7,6 @@ Rails.application.config.assets.version = '1.0' # 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 ) +# application.js, application.css, and all non-JS/CSS in the app/assets +# folder are already added. +# Rails.application.config.assets.precompile += %w( admin.js admin.css ) 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 deleted file mode 100644 index 649e82280e..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb +++ /dev/null @@ -1,6 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Do not halt callback chains when a callback returns false. This is a new -# Rails 5.0 default, so it is introduced as a configuration option to ensure -# that apps made with earlier versions of Rails are not affected when upgrading. -ActiveSupport.halt_callback_chains_on_return_false = false diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults.rb.tt new file mode 100644 index 0000000000..5ad18cc5ad --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults.rb.tt @@ -0,0 +1,38 @@ +# Be sure to restart your server when you modify this file. +# +# This file contains migration options to ease your Rails 5.0 upgrade. +# +<%- if options[:update] -%> +# Once upgraded flip defaults one by one to migrate to the new default. +# +<%- end -%> +# Read the Guide for Upgrading Ruby on Rails for more info on each option. +<%- unless options[:api] -%> + +# Enable per-form CSRF tokens. Previous versions had false. +Rails.application.config.action_controller.per_form_csrf_tokens = <%= options[:update] ? false : true %> + +# Enable origin-checking CSRF mitigation. Previous versions had false. +Rails.application.config.action_controller.forgery_protection_origin_check = <%= options[:update] ? false : true %> +<%- end -%> + +# Make Ruby 2.4 preserve the timezone of the receiver when calling `to_time`. +# Previous versions had false. +ActiveSupport.to_time_preserves_timezone = <%= options[:update] ? false : true %> +<%- unless options[:skip_active_record] -%> + +# Require `belongs_to` associations by default. Previous versions had false. +Rails.application.config.active_record.belongs_to_required_by_default = <%= options[:update] ? false : true %> +<%- end -%> + +# Do not halt callback chains when a callback returns false. Previous versions had true. +ActiveSupport.halt_callback_chains_on_return_false = <%= options[:update] ? true : false %> +<%- unless options[:update] -%> + +# Configure SSL options to enable HSTS with subdomains. Previous versions had false. +Rails.application.config.ssl_options = { hsts: { subdomains: true } } +<%- end -%> + +# Unknown asset fallback will return the path passed in when the given +# asset is not present in the asset pipeline. +Rails.application.config.assets.unknown_asset_fallback = <%= options[:update] ? true : false %> diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/per_form_csrf_tokens.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/per_form_csrf_tokens.rb deleted file mode 100644 index 1f569dedfd..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/per_form_csrf_tokens.rb +++ /dev/null @@ -1,4 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Enable per-form CSRF tokens. -Rails.application.config.action_controller.per_form_csrf_tokens = true diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/request_forgery_protection.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/request_forgery_protection.rb deleted file mode 100644 index 3eab78a885..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/request_forgery_protection.rb +++ /dev/null @@ -1,4 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Enable origin-checking CSRF mitigation. -Rails.application.config.action_controller.forgery_protection_origin_check = true diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt deleted file mode 100644 index 2bb9b82c61..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt +++ /dev/null @@ -1,3 +0,0 @@ -# Be sure to restart your server when you modify this file. - -Rails.application.config.session_store :cookie_store, key: <%= "'_#{app_name}_session'" %> diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/ssl_options.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/ssl_options.rb deleted file mode 100644 index 1775dea1e7..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/ssl_options.rb +++ /dev/null @@ -1,4 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Configure SSL options to enable HSTS with subdomains. -Rails.application.config.ssl_options = { hsts: { subdomains: true } } diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/to_time_preserves_timezone.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/to_time_preserves_timezone.rb deleted file mode 100644 index 8674be3227..0000000000 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/to_time_preserves_timezone.rb +++ /dev/null @@ -1,10 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Preserve the timezone of the receiver when calling to `to_time`. -# Ruby 2.4 will change the behavior of `to_time` to preserve the timezone -# when converting to an instance of `Time` instead of the previous behavior -# of converting to the local system timezone. -# -# Rails 5.0 introduced this config option so that apps made with earlier -# versions of Rails are not affected when upgrading. -ActiveSupport.to_time_preserves_timezone = true diff --git a/railties/lib/rails/generators/rails/app/templates/config/puma.rb b/railties/lib/rails/generators/rails/app/templates/config/puma.rb index c7f311f811..7ee948002e 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/puma.rb +++ b/railties/lib/rails/generators/rails/app/templates/config/puma.rb @@ -4,7 +4,7 @@ # the maximum value specified for Puma. Default is set to 5 threads for minimum # and maximum, this matches the default thread size of Active Record. # -threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i +threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } threads threads_count, threads_count # Specifies the `port` that Puma will listen on to receive requests, default is 3000. @@ -32,6 +32,14 @@ environment ENV.fetch("RAILS_ENV") { "development" } # # preload_app! +# If you are preloading your application and using Active Record, it's +# recommended that you close any connections to the database before workers +# are forked to prevent connection leakage. +# +# before_fork do +# ActiveRecord::Base.connection_pool.disconnect! if defined?(ActiveRecord) +# end + # The code in the `on_worker_boot` will be called if you are using # clustered mode by specifying a number of `workers`. After each worker # process is booted this block will be run, if you are using `preload_app!` @@ -42,6 +50,7 @@ environment ENV.fetch("RAILS_ENV") { "development" } # on_worker_boot do # ActiveRecord::Base.establish_connection if defined?(ActiveRecord) # end +# # Allow puma to be restarted by `rails restart` command. plugin :tmp_restart diff --git a/railties/lib/rails/generators/rails/app/templates/config/secrets.yml b/railties/lib/rails/generators/rails/app/templates/config/secrets.yml index cdea2fd060..8e995a5df1 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/secrets.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/secrets.yml @@ -10,6 +10,13 @@ # Make sure the secrets in this file are kept private # if you're sharing your code publicly. +# Shared secrets are available across all environments. + +shared: + api_key: 123 + +# Environmental secrets are only available for that specific environment. + development: secret_key_base: <%= app_secret %> @@ -18,5 +25,6 @@ test: # Do not keep production secrets in the repository, # instead read values from the environment. + production: secret_key_base: <%%= ENV["SECRET_KEY_BASE"] %> diff --git a/railties/lib/rails/generators/rails/app/templates/public/robots.txt b/railties/lib/rails/generators/rails/app/templates/public/robots.txt index 3c9c7c01f3..37b576a4a0 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/robots.txt +++ b/railties/lib/rails/generators/rails/app/templates/public/robots.txt @@ -1,5 +1 @@ # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file -# -# To ban all spiders from the entire site uncomment the next two lines: -# User-agent: * -# Disallow: / diff --git a/railties/lib/rails/generators/rails/app/templates/test/test_helper.rb b/railties/lib/rails/generators/rails/app/templates/test/test_helper.rb index 87b8fe3516..2f92168eef 100644 --- a/railties/lib/rails/generators/rails/app/templates/test/test_helper.rb +++ b/railties/lib/rails/generators/rails/app/templates/test/test_helper.rb @@ -1,4 +1,3 @@ -ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' diff --git a/railties/lib/rails/generators/rails/assets/assets_generator.rb b/railties/lib/rails/generators/rails/assets/assets_generator.rb index 6f4b86e708..265dada2ca 100644 --- a/railties/lib/rails/generators/rails/assets/assets_generator.rb +++ b/railties/lib/rails/generators/rails/assets/assets_generator.rb @@ -9,17 +9,17 @@ module Rails protected - def asset_name - file_name - end + def asset_name + file_name + end - hook_for :javascript_engine do |javascript_engine| - invoke javascript_engine, [name] if options[:javascripts] - end + hook_for :javascript_engine do |javascript_engine| + invoke javascript_engine, [name] if options[:javascripts] + end - hook_for :stylesheet_engine do |stylesheet_engine| - invoke stylesheet_engine, [name] if options[:stylesheets] - end + hook_for :stylesheet_engine do |stylesheet_engine| + invoke stylesheet_engine, [name] if options[:stylesheets] + end end end end diff --git a/railties/lib/rails/generators/rails/controller/controller_generator.rb b/railties/lib/rails/generators/rails/controller/controller_generator.rb index 0a4c509a31..213de37cce 100644 --- a/railties/lib/rails/generators/rails/controller/controller_generator.rb +++ b/railties/lib/rails/generators/rails/controller/controller_generator.rb @@ -7,7 +7,7 @@ module Rails check_class_collision suffix: "Controller" def create_controller_files - template 'controller.rb', File.join('app/controllers', class_path, "#{file_name}_controller.rb") + template "controller.rb", File.join("app/controllers", class_path, "#{file_name}_controller.rb") end def add_routes @@ -19,8 +19,7 @@ module Rails end end - hook_for :template_engine, :test_framework - hook_for :helper, :assets, hide: true + hook_for :template_engine, :test_framework, :helper, :assets private diff --git a/railties/lib/rails/generators/rails/generator/generator_generator.rb b/railties/lib/rails/generators/rails/generator/generator_generator.rb index 15d88f06ac..8040ec5e7b 100644 --- a/railties/lib/rails/generators/rails/generator/generator_generator.rb +++ b/railties/lib/rails/generators/rails/generator/generator_generator.rb @@ -7,7 +7,7 @@ module Rails desc: "Namespace generator under lib/generators/name" def create_generator_files - directory '.', generator_dir + directory ".", generator_dir end hook_for :test_framework @@ -21,7 +21,6 @@ module Rails File.join("lib", "generators", regular_class_path) end end - end end end diff --git a/railties/lib/rails/generators/rails/helper/helper_generator.rb b/railties/lib/rails/generators/rails/helper/helper_generator.rb index 5ff38e4111..e48b1b6fb3 100644 --- a/railties/lib/rails/generators/rails/helper/helper_generator.rb +++ b/railties/lib/rails/generators/rails/helper/helper_generator.rb @@ -4,7 +4,7 @@ module Rails check_class_collision suffix: "Helper" def create_helper_files - template 'helper.rb', File.join('app/helpers', class_path, "#{file_name}_helper.rb") + template "helper.rb", File.join("app/helpers", class_path, "#{file_name}_helper.rb") end hook_for :test_framework diff --git a/railties/lib/rails/generators/rails/model/model_generator.rb b/railties/lib/rails/generators/rails/model/model_generator.rb index ec78fd855d..c32a8a079a 100644 --- a/railties/lib/rails/generators/rails/model/model_generator.rb +++ b/railties/lib/rails/generators/rails/model/model_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/model_helpers' +require "rails/generators/model_helpers" module Rails module Generators diff --git a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb index 56efd35a95..9ffeab4fbe 100644 --- a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb +++ b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb @@ -1,6 +1,6 @@ -require 'active_support/core_ext/hash/slice' +require "active_support/core_ext/hash/slice" require "rails/generators/rails/app/app_generator" -require 'date' +require "date" module Rails # The plugin builder allows you to override elements of the plugin @@ -18,20 +18,20 @@ module Rails def app if mountable? if api? - directory 'app', exclude_pattern: %r{app/(views|helpers)} + directory "app", exclude_pattern: %r{app/(views|helpers)} else - directory 'app' + directory "app" empty_directory_with_keep_file "app/assets/images/#{namespaced_name}" end elsif full? - empty_directory_with_keep_file 'app/models' - empty_directory_with_keep_file 'app/controllers' - empty_directory_with_keep_file 'app/mailers' + empty_directory_with_keep_file "app/models" + empty_directory_with_keep_file "app/controllers" + empty_directory_with_keep_file "app/mailers" unless api? empty_directory_with_keep_file "app/assets/images/#{namespaced_name}" - empty_directory_with_keep_file 'app/helpers' - empty_directory_with_keep_file 'app/views' + empty_directory_with_keep_file "app/helpers" + empty_directory_with_keep_file "app/views" end end end @@ -149,7 +149,7 @@ task default: :test end def bin(force = false) - bin_file = engine? ? 'bin/rails.tt' : 'bin/test.tt' + bin_file = engine? ? "bin/rails.tt" : "bin/test.tt" template bin_file, force: force do |content| "#{shebang}\n" + content end @@ -258,7 +258,7 @@ task default: :test build(:leftovers) end - public_task :apply_rails_template, :run_bundle + public_task :apply_rails_template def run_after_bundle_callbacks @after_bundle_callbacks.each do |callback| @@ -283,7 +283,7 @@ task default: :test end def namespaced_name - @namespaced_name ||= name.gsub('-', '/') + @namespaced_name ||= name.gsub("-", "/") end protected @@ -320,7 +320,7 @@ task default: :test end def with_dummy_app? - options[:skip_test].blank? || options[:dummy_path] != 'test/dummy' + options[:skip_test].blank? || options[:dummy_path] != "test/dummy" end def api? @@ -328,7 +328,7 @@ task default: :test end def self.banner - "rails plugin new #{self.arguments.map(&:usage).join(' ')} [options]" + "rails plugin new #{arguments.map(&:usage).join(' ')} [options]" end def original_name @@ -340,7 +340,7 @@ task default: :test end def wrap_in_modules(unwrapped_code) - unwrapped_code = "#{unwrapped_code}".strip.gsub(/\s$\n/, '') + unwrapped_code = "#{unwrapped_code}".strip.gsub(/\s$\n/, "") modules.reverse.inject(unwrapped_code) do |content, mod| str = "module #{mod}\n" str += content.lines.map { |line| " #{line}" }.join @@ -357,7 +357,7 @@ task default: :test end def camelized - @camelized ||= name.gsub(/\W/, '_').squeeze('_').camelize + @camelized ||= name.gsub(/\W/, "_").squeeze("_").camelize end def author @@ -442,7 +442,7 @@ end def relative_path return unless inside_application? - app_path.sub(/^#{rails_app_path}\//, '') + app_path.sub(/^#{rails_app_path}\//, "") end end end diff --git a/railties/lib/rails/generators/rails/plugin/templates/bin/test.tt b/railties/lib/rails/generators/rails/plugin/templates/bin/test.tt index 62b94618fd..c0fbb84a93 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/bin/test.tt +++ b/railties/lib/rails/generators/rails/plugin/templates/bin/test.tt @@ -5,4 +5,6 @@ require 'rails/test_unit/minitest_plugin' Rails::TestUnitReporter.executable = 'bin/test' -exit Minitest.run(ARGV) +Minitest.run_via[:rails] = true + +require "active_support/testing/autorun" 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 a5eebcb19f..e84e403018 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,6 +1,3 @@ -# Configure Rails Environment -ENV["RAILS_ENV"] = "test" - 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__)] diff --git a/railties/lib/rails/generators/rails/resource/resource_generator.rb b/railties/lib/rails/generators/rails/resource/resource_generator.rb index 3acf21df13..5ac5164af0 100644 --- a/railties/lib/rails/generators/rails/resource/resource_generator.rb +++ b/railties/lib/rails/generators/rails/resource/resource_generator.rb @@ -1,5 +1,5 @@ -require 'rails/generators/resource_helpers' -require 'rails/generators/rails/model/model_generator' +require "rails/generators/resource_helpers" +require "rails/generators/rails/model/model_generator" module Rails module Generators diff --git a/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb index 17c32bfdb3..ed6bf7f7d7 100644 --- a/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb +++ b/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/rails/resource/resource_generator' +require "rails/generators/rails/resource/resource_generator" module Rails module Generators diff --git a/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css b/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css index 79f8b7f96f..cd4f3de38d 100644 --- a/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css +++ b/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css @@ -1,13 +1,13 @@ body { background-color: #fff; color: #333; + margin: 33px; } body, p, ol, ul, td { font-family: verdana, arial, helvetica, sans-serif; font-size: 13px; line-height: 18px; - margin: 33px; } pre { @@ -34,9 +34,7 @@ th { } td { - padding-bottom: 7px; - padding-left: 5px; - padding-right: 5px; + padding: 0 5px 7px; } div.field, @@ -57,8 +55,7 @@ div.actions { #error_explanation { width: 450px; border: 2px solid red; - padding: 7px; - padding-bottom: 0; + padding: 7px 7px 0; margin-bottom: 20px; background-color: #f0f0f0; } @@ -68,8 +65,7 @@ div.actions { font-weight: bold; padding: 5px 5px 5px 15px; font-size: 12px; - margin: -7px; - margin-bottom: 0; + margin: -7px -7px 0; background-color: #c00; color: #fff; } 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 d0b8cad896..e4f3161ffd 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 @@ -1,4 +1,4 @@ -require 'rails/generators/resource_helpers' +require "rails/generators/resource_helpers" module Rails module Generators @@ -17,7 +17,7 @@ module Rails def create_controller_files template_file = options.api? ? "api_controller.rb" : "controller.rb" - template template_file, File.join('app/controllers', controller_class_path, "#{controller_file_name}_controller.rb") + template template_file, File.join("app/controllers", controller_class_path, "#{controller_file_name}_controller.rb") end hook_for :template_engine, :test_framework, as: :scaffold diff --git a/railties/lib/rails/generators/rails/task/task_generator.rb b/railties/lib/rails/generators/rails/task/task_generator.rb index 754824ca0c..bb96bdf0dd 100644 --- a/railties/lib/rails/generators/rails/task/task_generator.rb +++ b/railties/lib/rails/generators/rails/task/task_generator.rb @@ -4,9 +4,8 @@ module Rails argument :actions, type: :array, default: [], banner: "action action" def create_task_files - template 'task.rb', File.join('lib/tasks', "#{file_name}.rake") + template "task.rb", File.join("lib/tasks", "#{file_name}.rake") end - end end end diff --git a/railties/lib/rails/generators/resource_helpers.rb b/railties/lib/rails/generators/resource_helpers.rb index 9c2037783e..6d80003271 100644 --- a/railties/lib/rails/generators/resource_helpers.rb +++ b/railties/lib/rails/generators/resource_helpers.rb @@ -1,12 +1,11 @@ -require 'rails/generators/active_model' -require 'rails/generators/model_helpers' +require "rails/generators/active_model" +require "rails/generators/model_helpers" module Rails module Generators # Deal with controller names on scaffold and add some helpers to deal with # ActiveModel. module ResourceHelpers # :nodoc: - def self.included(base) #:nodoc: base.include(Rails::Generators::ModelHelpers) base.class_option :model_name, type: :string, desc: "ModelName to be used" @@ -18,7 +17,7 @@ module Rails controller_name = name if options[:model_name] self.name = options[:model_name] - assign_names!(self.name) + assign_names!(name) end assign_controller_names!(controller_name.pluralize) @@ -38,21 +37,21 @@ module Rails def assign_controller_names!(name) @controller_name = name - @controller_class_path = name.include?('/') ? name.split('/') : name.split('::') + @controller_class_path = name.include?("/") ? name.split("/") : name.split("::") @controller_class_path.map!(&:underscore) @controller_file_name = @controller_class_path.pop end def controller_file_path - @controller_file_path ||= (controller_class_path + [controller_file_name]).join('/') + @controller_file_path ||= (controller_class_path + [controller_file_name]).join("/") end def controller_class_name - (controller_class_path + [controller_file_name]).map!(&:camelize).join('::') + (controller_class_path + [controller_file_name]).map!(&:camelize).join("::") end def controller_i18n_scope - @controller_i18n_scope ||= controller_file_path.tr('/', '.') + @controller_i18n_scope ||= controller_file_path.tr("/", ".") end # Loads the ORM::Generators::ActiveModel class. This class is responsible diff --git a/railties/lib/rails/generators/test_case.rb b/railties/lib/rails/generators/test_case.rb index 58592b4f8e..3eec929aeb 100644 --- a/railties/lib/rails/generators/test_case.rb +++ b/railties/lib/rails/generators/test_case.rb @@ -1,8 +1,8 @@ -require 'rails/generators' -require 'rails/generators/testing/behaviour' -require 'rails/generators/testing/setup_and_teardown' -require 'rails/generators/testing/assertions' -require 'fileutils' +require "rails/generators" +require "rails/generators/testing/behaviour" +require "rails/generators/testing/setup_and_teardown" +require "rails/generators/testing/assertions" +require "fileutils" module Rails module Generators @@ -30,7 +30,6 @@ module Rails include Rails::Generators::Testing::SetupAndTeardown include Rails::Generators::Testing::Assertions include FileUtils - end end end diff --git a/railties/lib/rails/generators/test_unit.rb b/railties/lib/rails/generators/test_unit.rb index fe45c9e15d..722efcf492 100644 --- a/railties/lib/rails/generators/test_unit.rb +++ b/railties/lib/rails/generators/test_unit.rb @@ -1,4 +1,4 @@ -require 'rails/generators/named_base' +require "rails/generators/named_base" module TestUnit # :nodoc: module Generators # :nodoc: diff --git a/railties/lib/rails/generators/test_unit/controller/controller_generator.rb b/railties/lib/rails/generators/test_unit/controller/controller_generator.rb index b5aa581769..ac528d94f1 100644 --- a/railties/lib/rails/generators/test_unit/controller/controller_generator.rb +++ b/railties/lib/rails/generators/test_unit/controller/controller_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: @@ -7,8 +7,8 @@ module TestUnit # :nodoc: check_class_collision suffix: "ControllerTest" def create_test_files - template 'functional_test.rb', - File.join('test/controllers', class_path, "#{file_name}_controller_test.rb") + template "functional_test.rb", + File.join("test/controllers", class_path, "#{file_name}_controller_test.rb") end end end diff --git a/railties/lib/rails/generators/test_unit/generator/generator_generator.rb b/railties/lib/rails/generators/test_unit/generator/generator_generator.rb index d7307398ce..59f8d40343 100644 --- a/railties/lib/rails/generators/test_unit/generator/generator_generator.rb +++ b/railties/lib/rails/generators/test_unit/generator/generator_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: @@ -9,7 +9,7 @@ module TestUnit # :nodoc: desc: "Namespace generator under lib/generators/name" def create_generator_files - template 'generator_test.rb', File.join('test/lib/generators', class_path, "#{file_name}_generator_test.rb") + template "generator_test.rb", File.join("test/lib/generators", class_path, "#{file_name}_generator_test.rb") end protected 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 bde4e88915..6674a15fa3 100644 --- a/railties/lib/rails/generators/test_unit/helper/helper_generator.rb +++ b/railties/lib/rails/generators/test_unit/helper/helper_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: diff --git a/railties/lib/rails/generators/test_unit/integration/integration_generator.rb b/railties/lib/rails/generators/test_unit/integration/integration_generator.rb index e004835bd5..9d065c1297 100644 --- a/railties/lib/rails/generators/test_unit/integration/integration_generator.rb +++ b/railties/lib/rails/generators/test_unit/integration/integration_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: @@ -6,7 +6,7 @@ module TestUnit # :nodoc: check_class_collision suffix: "Test" def create_test_files - template 'integration_test.rb', File.join('test/integration', class_path, "#{file_name}_test.rb") + template "integration_test.rb", File.join("test/integration", class_path, "#{file_name}_test.rb") end 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 index 566b61ca66..6975252b99 100644 --- a/railties/lib/rails/generators/test_unit/job/job_generator.rb +++ b/railties/lib/rails/generators/test_unit/job/job_generator.rb @@ -1,12 +1,12 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: class JobGenerator < Base # :nodoc: - check_class_collision suffix: 'JobTest' + 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") + template "unit_test.rb.erb", File.join("test/jobs", class_path, "#{file_name}_job_test.rb") end end end diff --git a/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb b/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb index 76a0b79654..806279788e 100644 --- a/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: @@ -10,16 +10,16 @@ module TestUnit # :nodoc: end def create_test_files - template "functional_test.rb", File.join('test/mailers', class_path, "#{file_name}_mailer_test.rb") + template "functional_test.rb", File.join("test/mailers", class_path, "#{file_name}_mailer_test.rb") end def create_preview_files - template "preview.rb", File.join('test/mailers/previews', class_path, "#{file_name}_mailer_preview.rb") + template "preview.rb", File.join("test/mailers/previews", class_path, "#{file_name}_mailer_preview.rb") end protected def file_name - @_file_name ||= super.gsub(/_mailer/i, '') + @_file_name ||= super.gsub(/_mailer/i, "") end end end diff --git a/railties/lib/rails/generators/test_unit/model/model_generator.rb b/railties/lib/rails/generators/test_unit/model/model_generator.rb index 086588750e..99495d5247 100644 --- a/railties/lib/rails/generators/test_unit/model/model_generator.rb +++ b/railties/lib/rails/generators/test_unit/model/model_generator.rb @@ -1,9 +1,8 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: class ModelGenerator < Base # :nodoc: - RESERVED_YAML_KEYWORDS = %w(y yes n no true false on off null) argument :attributes, type: :array, default: [], banner: "field:type field:type" @@ -12,14 +11,14 @@ module TestUnit # :nodoc: check_class_collision suffix: "Test" def create_test_file - template 'unit_test.rb', File.join('test/models', class_path, "#{file_name}_test.rb") + template "unit_test.rb", File.join("test/models", class_path, "#{file_name}_test.rb") end hook_for :fixture_replacement def create_fixture_file if options[:fixture] && options[:fixture_replacement].nil? - template 'fixtures.yml', File.join('test/fixtures', class_path, "#{fixture_file_name}.yml") + template "fixtures.yml", File.join("test/fixtures", class_path, "#{fixture_file_name}.yml") end end diff --git a/railties/lib/rails/generators/test_unit/plugin/plugin_generator.rb b/railties/lib/rails/generators/test_unit/plugin/plugin_generator.rb index b5d4f38444..f1c9b6da5b 100644 --- a/railties/lib/rails/generators/test_unit/plugin/plugin_generator.rb +++ b/railties/lib/rails/generators/test_unit/plugin/plugin_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/test_unit' +require "rails/generators/test_unit" module TestUnit # :nodoc: module Generators # :nodoc: @@ -6,7 +6,7 @@ module TestUnit # :nodoc: check_class_collision suffix: "Test" def create_test_files - directory '.', 'test' + directory ".", "test" end end end diff --git a/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb index 0171da7cc7..8840a86d0d 100644 --- a/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb +++ b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb @@ -1,5 +1,5 @@ -require 'rails/generators/test_unit' -require 'rails/generators/resource_helpers' +require "rails/generators/test_unit" +require "rails/generators/resource_helpers" module TestUnit # :nodoc: module Generators # :nodoc: @@ -39,7 +39,7 @@ module TestUnit # :nodoc: else "#{name}: @#{singular_table_name}.#{name}" end - end.sort.join(', ') + end.sort.join(", ") end end end diff --git a/railties/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb b/railties/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb index 0d18478043..c469c188e6 100644 --- a/railties/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb +++ b/railties/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb @@ -11,31 +11,31 @@ class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTe end test "should get index" do - get <%= index_helper %>_url + get <%= index_helper %>_url, as: :json assert_response :success end test "should create <%= singular_table_name %>" do assert_difference('<%= class_name %>.count') do - post <%= index_helper %>_url, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> } + post <%= index_helper %>_url, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> }, as: :json end assert_response 201 end test "should show <%= singular_table_name %>" do - get <%= show_helper %> + get <%= show_helper %>, as: :json assert_response :success end test "should update <%= singular_table_name %>" do - patch <%= show_helper %>, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> } + patch <%= show_helper %>, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> }, as: :json assert_response 200 end test "should destroy <%= singular_table_name %>" do assert_difference('<%= class_name %>.count', -1) do - delete <%= show_helper %> + delete <%= show_helper %>, as: :json end assert_response 204 diff --git a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb index 0e6bef12fc..c33375b7b4 100644 --- a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb +++ b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb @@ -25,7 +25,7 @@ class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTe post <%= index_helper %>_url, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> } end - assert_redirected_to <%= singular_table_name %>_path(<%= class_name %>.last) + assert_redirected_to <%= singular_table_name %>_url(<%= class_name %>.last) end test "should show <%= singular_table_name %>" do @@ -40,7 +40,7 @@ class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTe test "should update <%= singular_table_name %>" do patch <%= show_helper %>, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> } - assert_redirected_to <%= singular_table_name %>_path(<%= "@#{singular_table_name}" %>) + assert_redirected_to <%= singular_table_name %>_url(<%= "@#{singular_table_name}" %>) end test "should destroy <%= singular_table_name %>" do @@ -48,7 +48,7 @@ class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTe delete <%= show_helper %> end - assert_redirected_to <%= index_helper %>_path + assert_redirected_to <%= index_helper %>_url end end <% end -%> diff --git a/railties/lib/rails/generators/testing/assertions.rb b/railties/lib/rails/generators/testing/assertions.rb index 76758df86d..1cabf4e28c 100644 --- a/railties/lib/rails/generators/testing/assertions.rb +++ b/railties/lib/rails/generators/testing/assertions.rb @@ -29,10 +29,10 @@ module Rails contents.each do |content| case content - when String - assert_equal content, read - when Regexp - assert_match content, read + when String + assert_equal content, read + when Regexp + assert_match content, read end end end diff --git a/railties/lib/rails/generators/testing/behaviour.rb b/railties/lib/rails/generators/testing/behaviour.rb index 94b5e52224..a1e5a233b9 100644 --- a/railties/lib/rails/generators/testing/behaviour.rb +++ b/railties/lib/rails/generators/testing/behaviour.rb @@ -1,10 +1,10 @@ -require 'active_support/core_ext/class/attribute' -require 'active_support/core_ext/module/delegation' -require 'active_support/core_ext/hash/reverse_merge' -require 'active_support/core_ext/kernel/reporting' -require 'active_support/testing/stream' -require 'active_support/concern' -require 'rails/generators' +require "active_support/core_ext/class/attribute" +require "active_support/core_ext/module/delegation" +require "active_support/core_ext/hash/reverse_merge" +require "active_support/core_ext/kernel/reporting" +require "active_support/testing/stream" +require "active_support/concern" +require "rails/generators" module Rails module Generators @@ -62,24 +62,24 @@ module Rails # # You can provide a configuration hash as second argument. This method returns the output # printed by the generator. - def run_generator(args=self.default_arguments, config={}) + def run_generator(args = default_arguments, config = {}) capture(:stdout) do - args += ['--skip-bundle'] unless args.include? '--dev' - self.generator_class.start(args, config.reverse_merge(destination_root: destination_root)) + args += ["--skip-bundle"] unless args.include? "--dev" + generator_class.start(args, config.reverse_merge(destination_root: destination_root)) end end # Instantiate the generator. - def generator(args=self.default_arguments, options={}, config={}) - @generator ||= self.generator_class.new(args, options, config.reverse_merge(destination_root: destination_root)) + def generator(args = default_arguments, options = {}, config = {}) + @generator ||= generator_class.new(args, options, config.reverse_merge(destination_root: destination_root)) end # Create a Rails::Generators::GeneratedAttribute by supplying the # attribute type and, optionally, the attribute name: # # create_generated_attribute(:string, 'name') - def create_generated_attribute(attribute_type, name = 'test', index = nil) - Rails::Generators::GeneratedAttribute.parse([name, attribute_type, index].compact.join(':')) + def create_generated_attribute(attribute_type, name = "test", index = nil) + Rails::Generators::GeneratedAttribute.parse([name, attribute_type, index].compact.join(":")) end protected @@ -100,10 +100,9 @@ module Rails def migration_file_name(relative) # :nodoc: absolute = File.expand_path(relative, destination_root) - dirname, file_name = File.dirname(absolute), File.basename(absolute).sub(/\.rb$/, '') + dirname, file_name = File.dirname(absolute), File.basename(absolute).sub(/\.rb$/, "") Dir.glob("#{dirname}/[0-9]*_*.rb").grep(/\d+_#{file_name}.rb$/).first end - end end end diff --git a/railties/lib/rails/info.rb b/railties/lib/rails/info.rb index 5909446b66..5d4acd6f6b 100644 --- a/railties/lib/rails/info.rb +++ b/railties/lib/rails/info.rb @@ -38,64 +38,64 @@ module Rails alias inspect to_s def to_html - '<table>'.tap do |table| + "<table>".tap do |table| properties.each do |(name, value)| table << %(<tr><td class="name">#{CGI.escapeHTML(name.to_s)}</td>) formatted_value = if value.kind_of?(Array) - "<ul>" + value.map { |v| "<li>#{CGI.escapeHTML(v.to_s)}</li>" }.join + "</ul>" - else - CGI.escapeHTML(value.to_s) - end + "<ul>" + value.map { |v| "<li>#{CGI.escapeHTML(v.to_s)}</li>" }.join + "</ul>" + else + CGI.escapeHTML(value.to_s) + end table << %(<td class="value">#{formatted_value}</td></tr>) end - table << '</table>' + table << "</table>" end end end # The Rails version. - property 'Rails version' do + 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 + property "Ruby version" do "#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL} (#{RUBY_PLATFORM})" end # The RubyGems version, if it's installed. - property 'RubyGems version' do + property "RubyGems version" do Gem::RubyGemsVersion end - property 'Rack version' do + property "Rack version" do ::Rack.release end - property 'JavaScript Runtime' do + property "JavaScript Runtime" do ExecJS.runtime.name end - property 'Middleware' do + property "Middleware" do Rails.configuration.middleware.map(&:inspect) end # The application's location on the filesystem. - property 'Application root' do + property "Application root" do File.expand_path(Rails.root) end # The current Rails environment (development, test, or production). - property 'Environment' do + property "Environment" do Rails.env end # The name of the database adapter for the current environment. - property 'Database adapter' do - ActiveRecord::Base.configurations[Rails.env]['adapter'] + property "Database adapter" do + ActiveRecord::Base.configurations[Rails.env]["adapter"] end - property 'Database schema version' do + property "Database schema version" do ActiveRecord::Migrator.current_version rescue nil end end diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb index 778105c5f7..8b553aea79 100644 --- a/railties/lib/rails/info_controller.rb +++ b/railties/lib/rails/info_controller.rb @@ -1,9 +1,9 @@ -require 'rails/application_controller' -require 'action_dispatch/routing/inspector' +require "rails/application_controller" +require "action_dispatch/routing/inspector" class Rails::InfoController < Rails::ApplicationController # :nodoc: prepend_view_path ActionDispatch::DebugExceptions::RESCUES_TEMPLATE_PATH - layout -> { request.xhr? ? false : 'application' } + layout -> { request.xhr? ? false : "application" } before_action :require_local! @@ -13,7 +13,7 @@ class Rails::InfoController < Rails::ApplicationController # :nodoc: def properties @info = Rails::Info.to_html - @page_title = 'Properties' + @page_title = "Properties" end def routes @@ -21,24 +21,24 @@ class Rails::InfoController < Rails::ApplicationController # :nodoc: path = URI.parser.escape path normalized_path = with_leading_slash path render json: { - exact: match_route {|it| it.match normalized_path }, - fuzzy: match_route {|it| it.spec.to_s.match path } + exact: match_route { |it| it.match normalized_path }, + fuzzy: match_route { |it| it.spec.to_s.match path } } else @routes_inspector = ActionDispatch::Routing::RoutesInspector.new(_routes.routes) - @page_title = 'Routes' + @page_title = "Routes" end end private - def match_route - _routes.routes.select {|route| - yield route.path - }.map {|route| route.path.spec.to_s } - end + def match_route + _routes.routes.select { |route| + yield route.path + }.map { |route| route.path.spec.to_s } + end - def with_leading_slash(path) - ('/' + path).squeeze('/') - end + def with_leading_slash(path) + ("/" + path).squeeze("/") + end end diff --git a/railties/lib/rails/initializable.rb b/railties/lib/rails/initializable.rb index 1a0b6d1e1a..81b1cd8110 100644 --- a/railties/lib/rails/initializable.rb +++ b/railties/lib/rails/initializable.rb @@ -1,4 +1,4 @@ -require 'tsort' +require "tsort" module Rails module Initializable @@ -34,6 +34,10 @@ module Rails return self if @context Initializer.new(@name, context, @options, &block) end + + def context_class + @context.class + end end class Collection < Array diff --git a/railties/lib/rails/mailers_controller.rb b/railties/lib/rails/mailers_controller.rb index 6143cf2dd9..95de998208 100644 --- a/railties/lib/rails/mailers_controller.rb +++ b/railties/lib/rails/mailers_controller.rb @@ -1,4 +1,4 @@ -require 'rails/application_controller' +require "rails/application_controller" class Rails::MailersController < Rails::ApplicationController # :nodoc: prepend_view_path ActionDispatch::DebugExceptions::RESCUES_TEMPLATE_PATH @@ -14,7 +14,7 @@ class Rails::MailersController < Rails::ApplicationController # :nodoc: def preview if params[:path] == @preview.preview_name @page_title = "Mailer Previews for #{@preview.preview_name}" - render action: 'mailer' + render action: "mailer" else @email_action = File.basename(params[:path]) @@ -32,7 +32,7 @@ class Rails::MailersController < Rails::ApplicationController # :nodoc: end else @part = find_preferred_part(request.format, Mime[:html], Mime[:text]) - render action: 'email', layout: false, formats: %w[html] + render action: "email", layout: false, formats: %w[html] end else raise AbstractController::ActionNotFound, "Email '#{@email_action}' not found in #{@preview.name}" @@ -47,8 +47,8 @@ class Rails::MailersController < Rails::ApplicationController # :nodoc: def find_preview candidates = [] - params[:path].to_s.scan(%r{/|$}){ candidates << $` } - preview = candidates.detect{ |candidate| ActionMailer::Preview.exists?(candidate) } + params[:path].to_s.scan(%r{/|$}) { candidates << $` } + preview = candidates.detect { |candidate| ActionMailer::Preview.exists?(candidate) } if preview @preview = ActionMailer::Preview.find(preview) @@ -64,7 +64,7 @@ class Rails::MailersController < Rails::ApplicationController # :nodoc: end end - if formats.any?{ |f| @email.mime_type == f } + if formats.any? { |f| @email.mime_type == f } @email end end diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb index e47616a87f..1c1810dde6 100644 --- a/railties/lib/rails/paths.rb +++ b/railties/lib/rails/paths.rb @@ -30,7 +30,7 @@ module Rails # root["config/routes"].inspect # => ["config/routes.rb"] # # The +add+ method accepts the following options as arguments: - # eager_load, autoload, autoload_once and glob. + # eager_load, autoload, autoload_once, and glob. # # Finally, the +Path+ object also provides a few helpers: # @@ -180,7 +180,7 @@ module Rails end def extensions # :nodoc: - $1.split(',') if @glob =~ /\{([\S]+)\}/ + $1.split(",") if @glob =~ /\{([\S]+)\}/ end # Expands all paths against the root and return all unique values. diff --git a/railties/lib/rails/rack/debugger.rb b/railties/lib/rails/rack/debugger.rb index 1fde3db070..dccfa3e9bb 100644 --- a/railties/lib/rails/rack/debugger.rb +++ b/railties/lib/rails/rack/debugger.rb @@ -1,3 +1,3 @@ -require 'active_support/deprecation' +require "active_support/deprecation" ActiveSupport::Deprecation.warn("This file is deprecated and will be removed in Rails 5.1 with no replacement.") diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb index b63d3a58d2..e3fee75603 100644 --- a/railties/lib/rails/rack/logger.rb +++ b/railties/lib/rails/rack/logger.rb @@ -1,8 +1,8 @@ -require 'active_support/core_ext/time/conversions' -require 'active_support/core_ext/object/blank' -require 'active_support/log_subscriber' -require 'action_dispatch/http/request' -require 'rack/body_proxy' +require "active_support/core_ext/time/conversions" +require "active_support/core_ext/object/blank" +require "active_support/log_subscriber" +require "action_dispatch/http/request" +require "rack/body_proxy" module Rails module Rack @@ -31,7 +31,7 @@ module Rails def call_app(request, env) instrumenter = ActiveSupport::Notifications.instrumenter - instrumenter.start 'request.action_dispatch', request: request + instrumenter.start "request.action_dispatch", request: request logger.info { started_request_message(request) } resp = @app.call(env) resp[2] = ::Rack::BodyProxy.new(resp[2]) { finish(request) } @@ -67,14 +67,14 @@ module Rails private - def finish(request) - instrumenter = ActiveSupport::Notifications.instrumenter - instrumenter.finish 'request.action_dispatch', request: request - end + def finish(request) + instrumenter = ActiveSupport::Notifications.instrumenter + instrumenter.finish "request.action_dispatch", request: request + end - def logger - Rails.logger - end + def logger + Rails.logger + end end end end diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb index 492c519222..eb3f5d4ee9 100644 --- a/railties/lib/rails/railtie.rb +++ b/railties/lib/rails/railtie.rb @@ -1,7 +1,7 @@ -require 'rails/initializable' -require 'active_support/inflector' -require 'active_support/core_ext/module/introspection' -require 'active_support/core_ext/module/delegation' +require "rails/initializable" +require "active_support/inflector" +require "active_support/core_ext/module/introspection" +require "active_support/core_ext/module/delegation" module Rails # <tt>Rails::Railtie</tt> is the core of the Rails framework and provides @@ -111,7 +111,7 @@ module Rails # # Be sure to look at the documentation of those specific classes for more information. class Railtie - autoload :Configuration, 'rails/railtie/configuration' + autoload :Configuration, "rails/railtie/configuration" include Initializable @@ -222,31 +222,31 @@ module Rails protected - def run_console_blocks(app) #:nodoc: - each_registered_block(:console) { |block| block.call(app) } - end + def run_console_blocks(app) #:nodoc: + each_registered_block(:console) { |block| block.call(app) } + end - def run_generators_blocks(app) #:nodoc: - each_registered_block(:generators) { |block| block.call(app) } - end + def run_generators_blocks(app) #:nodoc: + each_registered_block(:generators) { |block| block.call(app) } + end - def run_runner_blocks(app) #:nodoc: - each_registered_block(:runner) { |block| block.call(app) } - end + def run_runner_blocks(app) #:nodoc: + each_registered_block(:runner) { |block| block.call(app) } + end - def run_tasks_blocks(app) #:nodoc: - extend Rake::DSL - each_registered_block(:rake_tasks) { |block| instance_exec(app, &block) } - end + def run_tasks_blocks(app) #:nodoc: + extend Rake::DSL + each_registered_block(:rake_tasks) { |block| instance_exec(app, &block) } + end private - def each_registered_block(type, &block) - klass = self.class - while klass.respond_to?(type) - klass.public_send(type).each(&block) - klass = klass.superclass + def each_registered_block(type, &block) + klass = self.class + while klass.respond_to?(type) + klass.public_send(type).each(&block) + klass = klass.superclass + end end - end end end diff --git a/railties/lib/rails/railtie/configurable.rb b/railties/lib/rails/railtie/configurable.rb index 1572af0b2a..39f1f87575 100644 --- a/railties/lib/rails/railtie/configurable.rb +++ b/railties/lib/rails/railtie/configurable.rb @@ -1,4 +1,4 @@ -require 'active_support/concern' +require "active_support/concern" module Rails class Railtie @@ -9,7 +9,7 @@ module Rails delegate :config, to: :instance def inherited(base) - raise "You cannot inherit from a #{self.superclass.name} child" + raise "You cannot inherit from a #{superclass.name} child" end def instance @@ -26,9 +26,9 @@ module Rails protected - def method_missing(*args, &block) - instance.send(*args, &block) - end + def method_missing(*args, &block) + instance.send(*args, &block) + end end end end diff --git a/railties/lib/rails/railtie/configuration.rb b/railties/lib/rails/railtie/configuration.rb index eb3b2d8ef4..aecc81c491 100644 --- a/railties/lib/rails/railtie/configuration.rb +++ b/railties/lib/rails/railtie/configuration.rb @@ -1,4 +1,4 @@ -require 'rails/configuration' +require "rails/configuration" module Rails class Railtie diff --git a/railties/lib/rails/ruby_version_check.rb b/railties/lib/rails/ruby_version_check.rb index 67a19d8a94..b212835df7 100644 --- a/railties/lib/rails/ruby_version_check.rb +++ b/railties/lib/rails/ruby_version_check.rb @@ -1,4 +1,4 @@ -if RUBY_VERSION < '2.2.2' && RUBY_ENGINE == 'ruby' +if RUBY_VERSION < "2.2.2" && RUBY_ENGINE == "ruby" desc = defined?(RUBY_DESCRIPTION) ? RUBY_DESCRIPTION : "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})" abort <<-end_message diff --git a/railties/lib/rails/source_annotation_extractor.rb b/railties/lib/rails/source_annotation_extractor.rb index 8dd87b6cc5..f0df76d3f3 100644 --- a/railties/lib/rails/source_annotation_extractor.rb +++ b/railties/lib/rails/source_annotation_extractor.rb @@ -1,9 +1,9 @@ # Implements the logic behind the rake tasks for annotations like # -# rake notes -# rake notes:optimize +# rails notes +# rails notes:optimize # -# and friends. See <tt>rake -T notes</tt> and <tt>railties/lib/rails/tasks/annotations.rake</tt>. +# and friends. See <tt>rails -T notes</tt> and <tt>railties/lib/rails/tasks/annotations.rake</tt>. # # Annotation objects are triplets <tt>:line</tt>, <tt>:tag</tt>, <tt>:text</tt> that # represent the line where the annotation lives, its tag, and its text. Note @@ -15,7 +15,13 @@ class SourceAnnotationExtractor class Annotation < Struct.new(:line, :tag, :text) def self.directories - @@directories ||= %w(app config db lib test) + (ENV['SOURCE_ANNOTATION_DIRECTORIES'] || '').split(',') + @@directories ||= %w(app config db lib test) + (ENV["SOURCE_ANNOTATION_DIRECTORIES"] || "").split(",") + end + + # Registers additional directories to be included + # SourceAnnotationExtractor::Annotation.register_directories("spec","another") + def self.register_directories(*dirs) + directories.push(*dirs) end def self.extensions diff --git a/railties/lib/rails/tasks.rb b/railties/lib/rails/tasks.rb index d3e33584d7..48675b3845 100644 --- a/railties/lib/rails/tasks.rb +++ b/railties/lib/rails/tasks.rb @@ -1,4 +1,4 @@ -require 'rake' +require "rake" # Load Rails Rakefile extensions %w( @@ -13,7 +13,7 @@ require 'rake' routes tmp ).tap { |arr| - arr << 'statistics' if Rake.application.current_scope.empty? + arr << "statistics" if Rake.application.current_scope.empty? }.each do |task| load "rails/tasks/#{task}.rake" end diff --git a/railties/lib/rails/tasks/annotations.rake b/railties/lib/rails/tasks/annotations.rake index 386ecf44be..9a69eb9934 100644 --- a/railties/lib/rails/tasks/annotations.rake +++ b/railties/lib/rails/tasks/annotations.rake @@ -1,4 +1,4 @@ -require 'rails/source_annotation_extractor' +require "rails/source_annotation_extractor" desc "Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)" task :notes do @@ -15,6 +15,6 @@ namespace :notes do desc "Enumerate a custom annotation, specify with ANNOTATION=CUSTOM" task :custom do - SourceAnnotationExtractor.enumerate ENV['ANNOTATION'] + SourceAnnotationExtractor.enumerate ENV["ANNOTATION"] end -end
\ No newline at end of file +end diff --git a/railties/lib/rails/tasks/dev.rake b/railties/lib/rails/tasks/dev.rake index d2ceaacc0c..334e968123 100644 --- a/railties/lib/rails/tasks/dev.rake +++ b/railties/lib/rails/tasks/dev.rake @@ -1,7 +1,7 @@ -require 'rails/dev_caching' +require "rails/dev_caching" namespace :dev do - desc 'Toggle development mode caching on/off' + desc "Toggle development mode caching on/off" task :cache do Rails::DevCaching.enable_by_file end diff --git a/railties/lib/rails/tasks/engine.rake b/railties/lib/rails/tasks/engine.rake index e678103f63..c92b42f6c1 100644 --- a/railties/lib/rails/tasks/engine.rake +++ b/railties/lib/rails/tasks/engine.rake @@ -2,7 +2,7 @@ task "load_app" do namespace :app do load APP_RAKEFILE end - task :environment => "app:environment" + task environment: "app:environment" if !defined?(ENGINE_ROOT) || !ENGINE_ROOT ENGINE_ROOT = find_engine_path(APP_RAKEFILE) @@ -26,11 +26,11 @@ namespace :db do desc "Display status of migrations" app_task "migrate:status" - desc 'Create the database from config/database.yml for the current Rails.env (use db:create:all to create all databases in the config)' + desc "Create the database from config/database.yml for the current Rails.env (use db:create:all to create all databases in the config)" app_task "create" app_task "create:all" - desc 'Drops the database for the current Rails.env (use db:drop:all to drop all databases)' + desc "Drops the database for the current Rails.env (use db:drop:all to drop all databases)" app_task "drop" app_task "drop:all" @@ -65,7 +65,7 @@ def find_engine_path(path) if Rails::Engine.find(path) path else - find_engine_path(File.expand_path('..', path)) + find_engine_path(File.expand_path("..", path)) end end diff --git a/railties/lib/rails/tasks/framework.rake b/railties/lib/rails/tasks/framework.rake index 3e771167ee..a2167796eb 100644 --- a/railties/lib/rails/tasks/framework.rake +++ b/railties/lib/rails/tasks/framework.rake @@ -1,16 +1,16 @@ -require 'active_support/deprecation' +require "active_support/deprecation" namespace :app do desc "Update configs and some other initially generated files (or use just update:configs or update:bin)" - task update: [ "update:configs", "update:bin" ] + task update: [ "update:configs", "update:bin", "update:upgrade_guide_info" ] desc "Applies the template supplied by LOCATION=(/path/to/template) or URL" task template: :environment do template = ENV["LOCATION"] raise "No LOCATION value given. Please set LOCATION either as path to a file or a URL" if template.blank? template = File.expand_path(template) if template !~ %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} - require 'rails/generators' - require 'rails/generators/rails/app/app_generator' + require "rails/generators" + require "rails/generators/rails/app/app_generator" generator = Rails::Generators::AppGenerator.new [Rails.root], {}, destination_root: Rails.root generator.apply template, verbose: false end @@ -45,10 +45,10 @@ namespace :app do def self.app_generator @app_generator ||= begin - require 'rails/generators' - require 'rails/generators/rails/app/app_generator' + require "rails/generators" + require "rails/generators/rails/app/app_generator" gen = Rails::Generators::AppGenerator.new ["rails"], - { api: !!Rails.application.config.api_only }, + { api: !!Rails.application.config.api_only, update: true }, destination_root: Rails.root File.exist?(Rails.root.join("config", "application.rb")) ? gen.send(:app_const) : gen.send(:valid_const?) @@ -67,6 +67,10 @@ namespace :app do task :bin do RailsUpdate.invoke_from_app_generator :create_bin_files end + + task :upgrade_guide_info do + RailsUpdate.invoke_from_app_generator :display_upgrade_guide_info + end end end diff --git a/railties/lib/rails/tasks/initializers.rake b/railties/lib/rails/tasks/initializers.rake index 2968b5cb53..6522f2ae5a 100644 --- a/railties/lib/rails/tasks/initializers.rake +++ b/railties/lib/rails/tasks/initializers.rake @@ -1,6 +1,6 @@ desc "Print out all defined initializers in the order they are invoked by Rails." task initializers: :environment do Rails.application.initializers.tsort_each do |initializer| - puts initializer.name + puts "#{initializer.context_class}.#{initializer.name}" end end diff --git a/railties/lib/rails/tasks/log.rake b/railties/lib/rails/tasks/log.rake index 073f235ec5..c376234fee 100644 --- a/railties/lib/rails/tasks/log.rake +++ b/railties/lib/rails/tasks/log.rake @@ -1,8 +1,8 @@ namespace :log do - - ## + + ## # Truncates all/specified log files - # ENV['LOGS'] + # ENV['LOGS'] # - defaults to standard environment log files i.e. 'development,test,production' # - ENV['LOGS']=all truncates all files i.e. log/*.log # - ENV['LOGS']='test,development' truncates only specified files @@ -14,21 +14,21 @@ namespace :log do end def log_files - if ENV['LOGS'] == 'all' + if ENV["LOGS"] == "all" FileList["log/*.log"] - elsif ENV['LOGS'] - log_files_to_truncate(ENV['LOGS']) + elsif ENV["LOGS"] + log_files_to_truncate(ENV["LOGS"]) else log_files_to_truncate("development,test,production") end end def log_files_to_truncate(envs) - envs.split(',') + envs.split(",") .map { |file| "log/#{file.strip}.log" } .select { |file| File.exist?(file) } end - + def clear_log_file(file) f = File.open(file, "w") f.close diff --git a/railties/lib/rails/tasks/middleware.rake b/railties/lib/rails/tasks/middleware.rake index 31e961b483..fd98be1ea9 100644 --- a/railties/lib/rails/tasks/middleware.rake +++ b/railties/lib/rails/tasks/middleware.rake @@ -1,4 +1,4 @@ -desc 'Prints out your Rack middleware stack' +desc "Prints out your Rack middleware stack" task middleware: :environment do Rails.configuration.middleware.each do |middleware| puts "use #{middleware.inspect}" diff --git a/railties/lib/rails/tasks/misc.rake b/railties/lib/rails/tasks/misc.rake index e6b13cc077..29ea0ff804 100644 --- a/railties/lib/rails/tasks/misc.rake +++ b/railties/lib/rails/tasks/misc.rake @@ -1,16 +1,16 @@ -desc 'Generate a cryptographically secure secret key (this is typically used to generate a secret for cookie sessions).' +desc "Generate a cryptographically secure secret key (this is typically used to generate a secret for cookie sessions)." task :secret do - require 'securerandom' + require "securerandom" puts SecureRandom.hex(64) end -desc 'List versions of all Rails frameworks and the environment' +desc "List versions of all Rails frameworks and the environment" task about: :environment do puts Rails::Info end namespace :time do - desc 'List all time zones, list by two-letter country code (`rails time:zones[US]`), or list by UTC offset (`rails time:zones[-8]`)' + desc "List all time zones, list by two-letter country code (`rails time:zones[US]`), or list by UTC offset (`rails time:zones[-8]`)" task :zones, :country_or_offset do |t, args| zones, offset = ActiveSupport::TimeZone.all, nil @@ -38,8 +38,8 @@ namespace :time do # desc 'Displays names of time zones recognized by the Rails TimeZone class with the same offset as the system local time' task :local do - require 'active_support' - require 'active_support/time' + require "active_support" + require "active_support/time" jan_offset = Time.now.beginning_of_year.utc_offset jul_offset = Time.now.beginning_of_year.change(month: 7).utc_offset @@ -49,12 +49,12 @@ namespace :time do end # to find UTC -06:00 zones, OFFSET can be set to either -6, -6:00 or 21600 - def build_time_zone_list(zones, offset = ENV['OFFSET']) - require 'active_support' - require 'active_support/time' + def build_time_zone_list(zones, offset = ENV["OFFSET"]) + require "active_support" + require "active_support/time" if offset offset = if offset.to_s.match(/(\+|-)?(\d+):(\d+)/) - sign = $1 == '-' ? -1 : 1 + sign = $1 == "-" ? -1 : 1 hours, minutes = $2.to_f, $3.to_f ((hours * 3600) + (minutes.to_f * 60)) * sign elsif offset.to_f.abs <= 13 diff --git a/railties/lib/rails/tasks/restart.rake b/railties/lib/rails/tasks/restart.rake index 3f98cbe51f..03177d9954 100644 --- a/railties/lib/rails/tasks/restart.rake +++ b/railties/lib/rails/tasks/restart.rake @@ -1,8 +1,8 @@ -desc 'Restart app by touching tmp/restart.txt' +desc "Restart app by touching tmp/restart.txt" task :restart do verbose(false) do - mkdir_p 'tmp' - touch 'tmp/restart.txt' - rm_f 'tmp/pids/server.pid' + mkdir_p "tmp" + touch "tmp/restart.txt" + rm_f "tmp/pids/server.pid" end end diff --git a/railties/lib/rails/tasks/routes.rake b/railties/lib/rails/tasks/routes.rake index ff7233cae9..f5e5b9ae87 100644 --- a/railties/lib/rails/tasks/routes.rake +++ b/railties/lib/rails/tasks/routes.rake @@ -1,13 +1,13 @@ -require 'active_support/deprecation' -require 'active_support/core_ext/string/strip' # for strip_heredoc -require 'optparse' +require "active_support/deprecation" +require "active_support/core_ext/string/strip" # for strip_heredoc +require "optparse" -desc 'Print out all defined routes in match order, with names. Target specific controller with -c option, or grep routes using -g option' +desc "Print out all defined routes in match order, with names. Target specific controller with -c option, or grep routes using -g option" task routes: :environment do all_routes = Rails.application.routes.routes - require 'action_dispatch/routing/inspector' + require "action_dispatch/routing/inspector" inspector = ActionDispatch::Routing::RoutesInspector.new(all_routes) - if ARGV.any?{ |argv| argv.start_with? 'CONTROLLER' } + if ARGV.any? { |argv| argv.start_with? "CONTROLLER" } puts <<-eow.strip_heredoc Passing `CONTROLLER` to `bin/rails routes` is deprecated and will be removed in Rails 5.1. Please use `bin/rails routes -c controller_name` instead. @@ -15,7 +15,7 @@ task routes: :environment do end routes_filter = nil - routes_filter = { controller: ENV['CONTROLLER'] } if ENV['CONTROLLER'] + routes_filter = { controller: ENV["CONTROLLER"] } if ENV["CONTROLLER"] OptionParser.new do |opts| opts.banner = "Usage: rails routes [options]" diff --git a/railties/lib/rails/tasks/statistics.rake b/railties/lib/rails/tasks/statistics.rake index 3e40d3b037..a6cdd1e99c 100644 --- a/railties/lib/rails/tasks/statistics.rake +++ b/railties/lib/rails/tasks/statistics.rake @@ -24,6 +24,6 @@ end.select { |name, dir| File.directory?(dir) } desc "Report code statistics (KLOCs, etc) from the application or engine" task :stats do - require 'rails/code_statistics' + require "rails/code_statistics" CodeStatistics.new(*STATS_DIRECTORIES).to_s end diff --git a/railties/lib/rails/tasks/tmp.rake b/railties/lib/rails/tasks/tmp.rake index c74a17a0ca..d42a890cb6 100644 --- a/railties/lib/rails/tasks/tmp.rake +++ b/railties/lib/rails/tasks/tmp.rake @@ -2,10 +2,10 @@ namespace :tmp do 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/cache', - 'tmp/sockets', - 'tmp/pids', - 'tmp/cache/assets' ] + tmp_dirs = [ "tmp/cache", + "tmp/sockets", + "tmp/pids", + "tmp/cache/assets" ] tmp_dirs.each { |d| directory d } @@ -15,21 +15,21 @@ namespace :tmp do namespace :cache do # desc "Clears all files and directories in tmp/cache" task :clear do - rm_rf Dir['tmp/cache/[^.]*'], verbose: false + rm_rf Dir["tmp/cache/[^.]*"], verbose: false end end namespace :sockets do # desc "Clears all files in tmp/sockets" task :clear do - rm Dir['tmp/sockets/[^.]*'], verbose: false + rm Dir["tmp/sockets/[^.]*"], verbose: false end end namespace :pids do # desc "Clears all files in tmp/pids" task :clear do - rm Dir['tmp/pids/[^.]*'], verbose: false + rm Dir["tmp/pids/[^.]*"], verbose: false end end end diff --git a/railties/lib/rails/templates/rails/mailers/email.html.erb b/railties/lib/rails/templates/rails/mailers/email.html.erb index fed96fbc85..c63781ed0c 100644 --- a/railties/lib/rails/templates/rails/mailers/email.html.erb +++ b/railties/lib/rails/templates/rails/mailers/email.html.erb @@ -88,7 +88,10 @@ <% unless @email.attachments.nil? || @email.attachments.empty? %> <dt>Attachments:</dt> <dd> - <%= @email.attachments.map { |a| a.respond_to?(:original_filename) ? a.original_filename : a.filename }.join(', ') %> + <% @email.attachments.each do |a| %> + <% filename = a.respond_to?(:original_filename) ? a.original_filename : a.filename %> + <%= link_to filename, "data:application/octet-stream;charset=utf-8;base64,#{Base64.encode64(a.body.to_s)}", download: filename %> + <% end %> </dd> <% end %> diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb index 5cc1b5b219..db341dd847 100644 --- a/railties/lib/rails/test_help.rb +++ b/railties/lib/rails/test_help.rb @@ -3,13 +3,13 @@ abort("Abort testing: Your Rails environment is running in production mode!") if Rails.env.production? require "rails/test_unit/minitest_plugin" -require 'active_support/test_case' -require 'action_controller' -require 'action_controller/test_case' -require 'action_dispatch/testing/integration' -require 'rails/generators/test_case' +require "active_support/test_case" +require "action_controller" +require "action_controller/test_case" +require "action_dispatch/testing/integration" +require "rails/generators/test_case" -require 'active_support/testing/autorun' +require "active_support/testing/autorun" if defined?(ActiveRecord::Base) ActiveRecord::Migration.maintain_test_schema! diff --git a/railties/lib/rails/test_unit/line_filtering.rb b/railties/lib/rails/test_unit/line_filtering.rb index dd9732bb12..32ba744701 100644 --- a/railties/lib/rails/test_unit/line_filtering.rb +++ b/railties/lib/rails/test_unit/line_filtering.rb @@ -1,4 +1,4 @@ -require 'method_source' +require "method_source" module Rails module LineFiltering # :nodoc: @@ -39,7 +39,7 @@ module Rails def derive_line_filters(patterns) patterns.flat_map do |file_and_line| - file, *lines = file_and_line.split(':') + file, *lines = file_and_line.split(":") if lines.empty? Filter.new(@runnable, file, nil) if file diff --git a/railties/lib/rails/test_unit/minitest_plugin.rb b/railties/lib/rails/test_unit/minitest_plugin.rb index 076ab536be..6e196a32ab 100644 --- a/railties/lib/rails/test_unit/minitest_plugin.rb +++ b/railties/lib/rails/test_unit/minitest_plugin.rb @@ -1,7 +1,7 @@ require "active_support/core_ext/module/attribute_accessors" require "rails/test_unit/reporter" require "rails/test_unit/test_requirer" -require 'shellwords' +require "shellwords" module Minitest class SuppressedSummaryReporter < SummaryReporter @@ -61,19 +61,30 @@ module Minitest # as the patterns would also contain the other Rake tasks. def self.rake_run(patterns) # :nodoc: @rake_patterns = patterns - passed = run(Shellwords.split(ENV['TESTOPTS'] || '')) - exit passed unless passed - passed + autorun end + module RunRespectingRakeTestopts + def run(args = []) + if defined?(@rake_patterns) + args = Shellwords.split(ENV["TESTOPTS"] || "") + end + + super + end + end + + singleton_class.prepend RunRespectingRakeTestopts + # Owes great inspiration to test runner trailblazers like RSpec, # minitest-reporters, maxitest and others. def self.plugin_rails_init(options) - self.run_with_rails_extension = true - ENV["RAILS_ENV"] = options[:environment] || "test" - ::Rails::TestRequirer.require_files(options[:patterns]) unless run_with_autorun + # If run via `ruby` we've been passed the files to run directly. + unless run_via[:ruby] + ::Rails::TestRequirer.require_files(options[:patterns]) + end unless options[:full_backtrace] || ENV["BACKTRACE"] # Plugin can run without Rails loaded, check before filtering. @@ -86,8 +97,7 @@ module Minitest reporter << ::Rails::TestUnitReporter.new(options[:io], options) end - mattr_accessor(:run_with_autorun) { false } - mattr_accessor(:run_with_rails_extension) { false } + mattr_accessor(:run_via) { Hash.new } end # Put Rails as the first plugin minitest initializes so other plugins @@ -95,4 +105,4 @@ end # Since minitest only loads plugins if its extensions are empty we have # to call `load_plugins` first. Minitest.load_plugins -Minitest.extensions.unshift 'rails' +Minitest.extensions.unshift "rails" diff --git a/railties/lib/rails/test_unit/railtie.rb b/railties/lib/rails/test_unit/railtie.rb index 511cee33bd..d0fc795515 100644 --- a/railties/lib/rails/test_unit/railtie.rb +++ b/railties/lib/rails/test_unit/railtie.rb @@ -1,7 +1,7 @@ -require 'rails/test_unit/line_filtering' +require "rails/test_unit/line_filtering" if defined?(Rake.application) && Rake.application.top_level_tasks.grep(/^(default$|test(:|$))/).any? - ENV['RAILS_ENV'] ||= 'test' + ENV["RAILS_ENV"] ||= "test" end module Rails diff --git a/railties/lib/rails/test_unit/reporter.rb b/railties/lib/rails/test_unit/reporter.rb index 4086d5b731..fe11664d5e 100644 --- a/railties/lib/rails/test_unit/reporter.rb +++ b/railties/lib/rails/test_unit/reporter.rb @@ -50,7 +50,7 @@ module Rails end def relative_path_for(file) - file.sub(/^#{app_root}\/?/, '') + file.sub(/^#{app_root}\/?/, "") end private @@ -68,7 +68,7 @@ module Rails def format_rerun_snippet(result) location, line = result.method(result.name).source_location - "#{self.executable} #{relative_path_for(location)}:#{line}" + "#{executable} #{relative_path_for(location)}:#{line}" end def app_root diff --git a/railties/lib/rails/test_unit/test_requirer.rb b/railties/lib/rails/test_unit/test_requirer.rb index 8b211ce130..fe35934abc 100644 --- a/railties/lib/rails/test_unit/test_requirer.rb +++ b/railties/lib/rails/test_unit/test_requirer.rb @@ -1,5 +1,5 @@ -require 'active_support/core_ext/object/blank' -require 'rake/file_list' +require "active_support/core_ext/object/blank" +require "rake/file_list" module Rails class TestRequirer # :nodoc: @@ -7,7 +7,7 @@ module Rails def require_files(patterns) patterns = expand_patterns(patterns) - Rake::FileList[patterns.compact.presence || 'test/**/*_test.rb'].to_a.each do |file| + Rake::FileList[patterns.compact.presence || "test/**/*_test.rb"].to_a.each do |file| require File.expand_path(file) end end @@ -15,7 +15,7 @@ module Rails private def expand_patterns(patterns) patterns.map do |arg| - arg = arg.gsub(/(:\d+)+?$/, '') + arg = arg.gsub(/(:\d+)+?$/, "") if Dir.exist?(arg) "#{arg}/**/*_test.rb" else diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake index 41921e43f3..4c157c1262 100644 --- a/railties/lib/rails/test_unit/testing.rake +++ b/railties/lib/rails/test_unit/testing.rake @@ -1,17 +1,17 @@ -gem 'minitest' -require 'minitest' -require 'rails/test_unit/minitest_plugin' +gem "minitest" +require "minitest" +require "rails/test_unit/minitest_plugin" task default: :test desc "Runs all tests in test folder" task :test do $: << "test" - pattern = if ENV.key?('TEST') - ENV['TEST'] - else - "test" - end + pattern = if ENV.key?("TEST") + ENV["TEST"] + else + "test" + end Minitest.rake_run([pattern]) end @@ -21,10 +21,10 @@ namespace :test do # If used with Active Record, this task runs before the database schema is synchronized. end - task :run => %w[test] + task run: %w[test] desc "Run tests quickly, but also reset db" - task :db => %w[db:test:prepare test] + task db: %w[db:test:prepare test] ["models", "helpers", "controllers", "mailers", "integration", "jobs"].each do |name| task name => "test:prepare" do @@ -33,17 +33,17 @@ namespace :test do end end - task :generators => "test:prepare" do + task generators: "test:prepare" do $: << "test" Minitest.rake_run(["test/lib/generators"]) end - task :units => "test:prepare" do + task units: "test:prepare" do $: << "test" Minitest.rake_run(["test/models", "test/helpers", "test/unit"]) end - task :functionals => "test:prepare" do + task functionals: "test:prepare" do $: << "test" Minitest.rake_run(["test/controllers", "test/mailers", "test/functional"]) end diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb index df351c4238..3d8e8291d1 100644 --- a/railties/lib/rails/version.rb +++ b/railties/lib/rails/version.rb @@ -1,4 +1,4 @@ -require_relative 'gem_version' +require_relative "gem_version" module Rails # Returns the version of the currently loaded Rails as a string. diff --git a/railties/lib/rails/welcome_controller.rb b/railties/lib/rails/welcome_controller.rb index de9cd18b01..b757dc72ef 100644 --- a/railties/lib/rails/welcome_controller.rb +++ b/railties/lib/rails/welcome_controller.rb @@ -1,4 +1,4 @@ -require 'rails/application_controller' +require "rails/application_controller" class Rails::WelcomeController < Rails::ApplicationController # :nodoc: layout false diff --git a/railties/railties.gemspec b/railties/railties.gemspec index fa417816eb..76de2b4639 100644 --- a/railties/railties.gemspec +++ b/railties/railties.gemspec @@ -1,34 +1,34 @@ -version = File.read(File.expand_path('../../RAILS_VERSION', __FILE__)).strip +version = File.read(File.expand_path("../../RAILS_VERSION", __FILE__)).strip Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY - s.name = 'railties' + s.name = "railties" s.version = version - s.summary = 'Tools for creating, working with, and running Rails applications.' - s.description = 'Rails internals: application bootup, plugins, generators, and rake tasks.' + 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 = '>= 2.2.2' + s.required_ruby_version = ">= 2.2.2" - s.license = 'MIT' + s.license = "MIT" - s.author = 'David Heinemeier Hansson' - s.email = 'david@loudthinking.com' - s.homepage = 'http://rubyonrails.org' + s.author = "David Heinemeier Hansson" + s.email = "david@loudthinking.com" + s.homepage = "http://rubyonrails.org" - s.files = Dir['CHANGELOG.md', 'README.rdoc', 'MIT-LICENSE', 'RDOC_MAIN.rdoc', 'exe/**/*', 'lib/**/{*,.[a-z]*}'] - s.require_path = 'lib' + s.files = Dir["CHANGELOG.md", "README.rdoc", "MIT-LICENSE", "RDOC_MAIN.rdoc", "exe/**/*", "lib/**/{*,.[a-z]*}"] + s.require_path = "lib" - s.bindir = 'exe' - s.executables = ['rails'] + s.bindir = "exe" + s.executables = ["rails"] - s.rdoc_options << '--exclude' << '.' + s.rdoc_options << "--exclude" << "." - s.add_dependency 'activesupport', version - s.add_dependency 'actionpack', version + s.add_dependency "activesupport", version + s.add_dependency "actionpack", version - s.add_dependency 'rake', '>= 0.8.7' - s.add_dependency 'thor', '>= 0.18.1', '< 2.0' - s.add_dependency 'method_source' + s.add_dependency "rake", ">= 0.8.7" + s.add_dependency "thor", ">= 0.18.1", "< 2.0" + s.add_dependency "method_source" - s.add_development_dependency 'actionview', version + s.add_development_dependency "actionview", version end diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb index 2a5a731fe2..fd1e1b9662 100644 --- a/railties/test/abstract_unit.rb +++ b/railties/test/abstract_unit.rb @@ -1,28 +1,28 @@ ENV["RAILS_ENV"] ||= "test" -require 'stringio' -require 'active_support/testing/autorun' -require 'active_support/testing/stream' -require 'fileutils' +require "stringio" +require "active_support/testing/autorun" +require "active_support/testing/stream" +require "fileutils" -require 'active_support' -require 'action_controller' -require 'action_view' -require 'rails/all' +require "active_support" +require "action_controller" +require "action_view" +require "rails/all" module TestApp class Application < Rails::Application config.root = File.dirname(__FILE__) - secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' + secrets.secret_key_base = "b3c631c314c0bbca50c1b2843150fe33" end end # Skips the current run on Rubinius using Minitest::Assertions#skip -def rubinius_skip(message = '') - skip message if RUBY_ENGINE == 'rbx' +def rubinius_skip(message = "") + skip message if RUBY_ENGINE == "rbx" end # Skips the current run on JRuby using Minitest::Assertions#skip -def jruby_skip(message = '') +def jruby_skip(message = "") skip message if defined?(JRUBY_VERSION) end diff --git a/railties/test/app_loader_test.rb b/railties/test/app_loader_test.rb index 5946c8fd4c..7fd5c72c1c 100644 --- a/railties/test/app_loader_test.rb +++ b/railties/test/app_loader_test.rb @@ -1,6 +1,6 @@ -require 'tmpdir' -require 'abstract_unit' -require 'rails/app_loader' +require "tmpdir" +require "abstract_unit" +require "rails/app_loader" class AppLoaderTest < ActiveSupport::TestCase def loader @@ -27,12 +27,12 @@ class AppLoaderTest < ActiveSupport::TestCase end setup do - @tmp = Dir.mktmpdir('railties-rails-loader-test-suite') + @tmp = Dir.mktmpdir("railties-rails-loader-test-suite") @cwd = Dir.pwd Dir.chdir(@tmp) end - ['bin', 'script'].each do |script_dir| + ["bin", "script"].each do |script_dir| exe = "#{script_dir}/rails" test "is not in a Rails application if #{exe} is not found in the current or parent directories" do @@ -47,7 +47,7 @@ class AppLoaderTest < ActiveSupport::TestCase assert !loader.exec_app end - ['APP_PATH', 'ENGINE_PATH'].each do |keyword| + ["APP_PATH", "ENGINE_PATH"].each do |keyword| test "is in a Rails application if #{exe} exists and contains #{keyword}" do write exe, keyword @@ -66,7 +66,7 @@ class AppLoaderTest < ActiveSupport::TestCase write "foo/bar/#{exe}" write "foo/#{exe}", keyword - Dir.chdir('foo/bar') + Dir.chdir("foo/bar") loader.exec_app diff --git a/railties/test/application/asset_debugging_test.rb b/railties/test/application/asset_debugging_test.rb index bcb6aff0d7..3e17a1efa5 100644 --- a/railties/test/application/asset_debugging_test.rb +++ b/railties/test/application/asset_debugging_test.rb @@ -1,5 +1,5 @@ -require 'isolation/abstract_unit' -require 'rack/test' +require "isolation/abstract_unit" +require "rack/test" module ApplicationTests class AssetDebuggingTest < ActiveSupport::TestCase @@ -28,8 +28,6 @@ module ApplicationTests RUBY ENV["RAILS_ENV"] = "production" - - boot_rails end def teardown @@ -44,7 +42,7 @@ module ApplicationTests test "assets are concatenated when debug is off and compile is off either if debug_assets param is provided" do # config.assets.debug and config.assets.compile are false for production environment ENV["RAILS_ENV"] = "production" - output = Dir.chdir(app_path){ `bin/rails assets:precompile --trace 2>&1` } + output = Dir.chdir(app_path) { `bin/rails assets:precompile --trace 2>&1` } assert $?.success?, output # Load app env @@ -53,7 +51,7 @@ module ApplicationTests class ::PostsController < ActionController::Base ; end # the debug_assets params isn't used if compile is off - get '/posts?debug_assets=true' + get "/posts?debug_assets=true" assert_match(/<script src="\/assets\/application-([0-z]+)\.js"><\/script>/, last_response.body) assert_no_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js"><\/script>/, last_response.body) end @@ -66,9 +64,106 @@ module ApplicationTests class ::PostsController < ActionController::Base ; end - get '/posts?debug_assets=true' + get "/posts?debug_assets=true" assert_match(/<script src="\/assets\/application(\.self)?-([0-z]+)\.js\?body=1"><\/script>/, last_response.body) assert_match(/<script src="\/assets\/xmlhr(\.self)?-([0-z]+)\.js\?body=1"><\/script>/, last_response.body) end + + test "public path and tag methods are not over-written by the asset pipeline" do + contents = "doesnotexist" + cases = { + asset_path: %r{/#{contents}}, + image_path: %r{/images/#{contents}}, + video_path: %r{/videos/#{contents}}, + audio_path: %r{/audios/#{contents}}, + font_path: %r{/fonts/#{contents}}, + javascript_path: %r{/javascripts/#{contents}}, + stylesheet_path: %r{/stylesheets/#{contents}}, + image_tag: %r{<img src="/images/#{contents}"}, + favicon_link_tag: %r{<link rel="shortcut icon" type="image/x-icon" href="/images/#{contents}" />}, + stylesheet_link_tag: %r{<link rel="stylesheet" media="screen" href="/stylesheets/#{contents}.css" />}, + javascript_include_tag: %r{<script src="/javascripts/#{contents}.js">}, + audio_tag: %r{<audio src="/audios/#{contents}"></audio>}, + video_tag: %r{<video src="/videos/#{contents}"></video>} + } + + cases.each do |(view_method, tag_match)| + app_file "app/views/posts/index.html.erb", "<%= #{view_method} '#{contents}', skip_pipeline: true %>" + + app "development" + + class ::PostsController < ActionController::Base ; end + + get "/posts?debug_assets=true" + + body = last_response.body + assert_match(tag_match, body, "Expected `#{view_method}` to produce a match to #{tag_match}, but did not: #{body}") + end + end + + test "public url methods are not over-written by the asset pipeline" do + contents = "doesnotexist" + cases = { + asset_url: %r{http://example.org/#{contents}}, + image_url: %r{http://example.org/images/#{contents}}, + video_url: %r{http://example.org/videos/#{contents}}, + audio_url: %r{http://example.org/audios/#{contents}}, + font_url: %r{http://example.org/fonts/#{contents}}, + javascript_url: %r{http://example.org/javascripts/#{contents}}, + stylesheet_url: %r{http://example.org/stylesheets/#{contents}}, + } + + cases.each do |(view_method, tag_match)| + app_file "app/views/posts/index.html.erb", "<%= #{view_method} '#{contents}', skip_pipeline: true %>" + + app "development" + + class ::PostsController < ActionController::Base ; end + + get "/posts?debug_assets=true" + + body = last_response.body + assert_match(tag_match, body, "Expected `#{view_method}` to produce a match to #{tag_match}, but did not: #{body}") + end + end + + test "{ skip_pipeline: true } does not use the asset pipeline" do + cases = { + /\/assets\/application-.*.\.js/ => {}, + /application.js/ => { skip_pipeline: true }, + } + cases.each do |(tag_match, options_hash)| + app_file "app/views/posts/index.html.erb", "<%= asset_path('application.js', #{options_hash}) %>" + + app "development" + + class ::PostsController < ActionController::Base ; end + + get "/posts?debug_assets=true" + + body = last_response.body.strip + assert_match(tag_match, body, "Expected `asset_path` with `#{options_hash}` to produce a match to #{tag_match}, but did not: #{body}") + end + end + + test "public_compute_asset_path does not use the asset pipeline" do + cases = { + compute_asset_path: /\/assets\/application-.*.\.js/, + public_compute_asset_path: /application.js/, + } + + cases.each do |(view_method, tag_match)| + app_file "app/views/posts/index.html.erb", "<%= #{ view_method } 'application.js' %>" + + app "development" + + class ::PostsController < ActionController::Base ; end + + get "/posts?debug_assets=true" + + body = last_response.body.strip + assert_match(tag_match, body, "Expected `#{view_method}` to produce a match to #{ tag_match }, but did not: #{ body }") + end + end end end diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index e32eea42b7..e84e01a41b 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -1,6 +1,6 @@ -require 'isolation/abstract_unit' -require 'rack/test' -require 'active_support/json' +require "isolation/abstract_unit" +require "rack/test" +require "active_support/json" module ApplicationTests class AssetsTest < ActiveSupport::TestCase @@ -9,7 +9,6 @@ module ApplicationTests def setup build_app(initializers: true) - boot_rails end def teardown @@ -36,7 +35,7 @@ module ApplicationTests def clean_assets! quietly do - assert Dir.chdir(app_path) { system('bin/rails assets:clobber') } + assert Dir.chdir(app_path) { system("bin/rails assets:clobber") } end end @@ -53,7 +52,7 @@ module ApplicationTests app_file "app/assets/images/rails.png", "notactuallyapng" app_file "app/assets/javascripts/demo.js.erb", "a = <%= image_path('rails.png').inspect %>;" - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get '*path', to: lambda { |env| [200, { "Content-Type" => "text/html" }, ["Not an asset"]] } end @@ -111,8 +110,8 @@ module ApplicationTests eoruby precompile! \ - RAILS_ENV: 'production', - DATABASE_URL: 'postgresql://baduser:badpass@127.0.0.1/dbname' + RAILS_ENV: "production", + DATABASE_URL: "postgresql://baduser:badpass@127.0.0.1/dbname" files = Dir["#{app_path}/public/assets/application-*.js"] files << Dir["#{app_path}/public/assets/foo/application-*.js"].first @@ -177,19 +176,19 @@ module ApplicationTests assert_file_exists("#{app_path}/public/assets/something/index-*.js") end - test 'precompile use assets defined in app env config' do - add_to_env_config 'production', 'config.assets.precompile = [ "something.js" ]' - app_file 'app/assets/javascripts/something.js.erb', 'alert();' + test "precompile use assets defined in app env config" do + add_to_env_config "production", 'config.assets.precompile = [ "something.js" ]' + app_file "app/assets/javascripts/something.js.erb", "alert();" - precompile! RAILS_ENV: 'production' + precompile! RAILS_ENV: "production" assert_file_exists("#{app_path}/public/assets/something-*.js") end - test 'sprockets cache is not shared between environments' do + test "sprockets cache is not shared between environments" do app_file "app/assets/images/rails.png", "notactuallyapng" - app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>" - add_to_env_config 'production', 'config.assets.prefix = "production_assets"' + app_file "app/assets/stylesheets/application.css.erb", "body { background: '<%= asset_path('rails.png') %>'; }" + add_to_env_config "production", 'config.assets.prefix = "production_assets"' precompile! @@ -198,7 +197,7 @@ module ApplicationTests file = Dir["#{app_path}/public/assets/application-*.css"].first assert_match(/assets\/rails-([0-z]+)\.png/, File.read(file)) - precompile! RAILS_ENV: 'production' + precompile! RAILS_ENV: "production" assert_file_exists("#{app_path}/public/production_assets/application-*.css") @@ -206,17 +205,17 @@ module ApplicationTests assert_match(/production_assets\/rails-([0-z]+)\.png/, File.read(file)) end - test 'precompile use assets defined in app config and reassigned in app env config' do + test "precompile use assets defined in app config and reassigned in app env config" do add_to_config 'config.assets.precompile = [ "something_manifest.js" ]' - add_to_env_config 'production', 'config.assets.precompile += [ "another_manifest.js" ]' + add_to_env_config "production", 'config.assets.precompile += [ "another_manifest.js" ]' - app_file 'app/assets/config/something_manifest.js', '//= link something.js' - app_file 'app/assets/config/another_manifest.js', '//= link another.js' + app_file "app/assets/config/something_manifest.js", "//= link something.js" + app_file "app/assets/config/another_manifest.js", "//= link another.js" - app_file 'app/assets/javascripts/something.js.erb', 'alert();' - app_file 'app/assets/javascripts/another.js.erb', 'alert();' + app_file "app/assets/javascripts/something.js.erb", "alert();" + app_file "app/assets/javascripts/another.js.erb", "alert();" - precompile! RAILS_ENV: 'production' + precompile! RAILS_ENV: "production" assert_file_exists("#{app_path}/public/assets/something_manifest-*.js") assert_file_exists("#{app_path}/public/assets/something-*.js") @@ -262,7 +261,7 @@ module ApplicationTests app_file "app/assets/javascripts/application.js", "alert();" add_to_env_config "production", "config.public_file_server.enabled = true" - precompile! RAILS_ENV: 'production' + precompile! RAILS_ENV: "production" manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first assets = ActiveSupport::JSON.decode(File.read(manifest)) @@ -293,7 +292,7 @@ module ApplicationTests app_file "app/assets/stylesheets/application.css.erb", "p { background-image: url(<%= asset_path('rails.png') %>) }" - precompile! RAILS_ENV: 'production' + precompile! RAILS_ENV: "production" manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first assets = ActiveSupport::JSON.decode(File.read(manifest)) @@ -307,11 +306,11 @@ module ApplicationTests assert_not_equal asset_path, assets["assets"]["application.css"] end - test "precompile appends the md5 hash to files referenced with asset_path and run in production with digest true" do + test "precompile appends the MD5 hash to files referenced with asset_path and run in production with digest true" do app_file "app/assets/images/rails.png", "notactuallyapng" app_file "app/assets/stylesheets/application.css.erb", "p { background-image: url(<%= asset_path('rails.png') %>) }" - precompile! RAILS_ENV: 'production' + precompile! RAILS_ENV: "production" file = Dir["#{app_path}/public/assets/application-*.css"].first assert_match(/\/assets\/rails-([0-z]+)\.png/, File.read(file)) @@ -381,7 +380,7 @@ module ApplicationTests end get "/omg" - assert_equal 'ok', last_response.body + assert_equal "ok", last_response.body get "/assets/demo.js" assert_match "alert()", last_response.body @@ -409,7 +408,7 @@ module ApplicationTests app_with_assets_in_view # config.assets.debug and config.assets.compile are false for production environment - precompile! RAILS_ENV: 'production' + precompile! RAILS_ENV: "production" # Load app env app "production" @@ -417,7 +416,7 @@ module ApplicationTests class ::PostsController < ActionController::Base ; end # the debug_assets params isn't used if compile is off - get '/posts?debug_assets=true' + get "/posts?debug_assets=true" assert_match(/<script src="\/assets\/application-([0-z]+)\.js"><\/script>/, last_response.body) assert_no_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js"><\/script>/, last_response.body) end @@ -476,9 +475,9 @@ module ApplicationTests class ::PostsController < ActionController::Base; end - get '/posts', {}, {'HTTPS'=>'off'} + get "/posts", {}, "HTTPS"=>"off" assert_match('src="http://example.com/assets/application.self.js', last_response.body) - get '/posts', {}, {'HTTPS'=>'on'} + get "/posts", {}, "HTTPS"=>"on" assert_match('src="https://example.com/assets/application.self.js', last_response.body) end @@ -508,16 +507,16 @@ module ApplicationTests private - def app_with_assets_in_view - app_file "app/assets/javascripts/application.js", "//= require_tree ." - app_file "app/assets/javascripts/xmlhr.js", "function f1() { alert(); }" - app_file "app/views/posts/index.html.erb", "<%= javascript_include_tag 'application' %>" + def app_with_assets_in_view + app_file "app/assets/javascripts/application.js", "//= require_tree ." + app_file "app/assets/javascripts/xmlhr.js", "function f1() { alert(); }" + app_file "app/views/posts/index.html.erb", "<%= javascript_include_tag 'application' %>" - app_file "config/routes.rb", <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get '/posts', :to => "posts#index" end RUBY - end + end end end diff --git a/railties/test/application/bin_setup_test.rb b/railties/test/application/bin_setup_test.rb index ba700df1d6..0bbd25db2b 100644 --- a/railties/test/application/bin_setup_test.rb +++ b/railties/test/application/bin_setup_test.rb @@ -1,4 +1,4 @@ -require 'isolation/abstract_unit' +require "isolation/abstract_unit" module ApplicationTests class BinSetupTest < ActiveSupport::TestCase @@ -6,15 +6,22 @@ module ApplicationTests def setup build_app + + create_gemfile + update_boot_file_to_use_bundler + @old_gemfile_env = ENV["BUNDLE_GEMFILE"] + ENV["BUNDLE_GEMFILE"] = app_path + "/Gemfile" end def teardown teardown_app + + ENV["BUNDLE_GEMFILE"] = @old_gemfile_env end def test_bin_setup Dir.chdir(app_path) do - app_file 'db/schema.rb', <<-RUBY + app_file "db/schema.rb", <<-RUBY ActiveRecord::Schema.define(version: 20140423102712) do create_table(:articles) {} end @@ -23,7 +30,7 @@ module ApplicationTests list_tables = lambda { `bin/rails runner 'p ActiveRecord::Base.connection.tables'`.strip } File.write("log/test.log", "zomg!") - assert_equal '[]', list_tables.call + assert_equal "[]", list_tables.call assert_equal 5, File.size("log/test.log") assert_not File.exist?("tmp/restart.txt") `bin/setup 2>&1` @@ -35,7 +42,7 @@ module ApplicationTests def test_bin_setup_output Dir.chdir(app_path) do - app_file 'db/schema.rb', "" + app_file "db/schema.rb", "" output = `bin/setup 2>&1` assert_equal(<<-OUTPUT, output) @@ -52,5 +59,16 @@ Created database 'db/test.sqlite3' OUTPUT end end + + private + def create_gemfile + app_file("Gemfile", "source 'https://rubygems.org'") + app_file("Gemfile", "gem 'rails', path: '#{RAILS_FRAMEWORK_ROOT}'", "a") + app_file("Gemfile", "gem 'sqlite3'", "a") + end + + def update_boot_file_to_use_bundler + app_file("config/boot.rb", "require 'bundler/setup'") + end end end diff --git a/railties/test/application/configuration/custom_test.rb b/railties/test/application/configuration/custom_test.rb index 28b3b2f2d6..13fc98f0d6 100644 --- a/railties/test/application/configuration/custom_test.rb +++ b/railties/test/application/configuration/custom_test.rb @@ -1,11 +1,10 @@ -require 'isolation/abstract_unit' +require "isolation/abstract_unit" module ApplicationTests module ConfigurationTests class CustomTest < ActiveSupport::TestCase def setup build_app - boot_rails FileUtils.rm_rf("#{app_path}/config/environments") end @@ -14,7 +13,7 @@ module ApplicationTests FileUtils.rm_rf(new_app) if File.directory?(new_app) end - test 'access custom configuration point' do + test "access custom configuration point" do add_to_config <<-RUBY config.x.payment_processing.schedule = :daily config.x.payment_processing.retries = 3 @@ -33,6 +32,13 @@ module ApplicationTests assert_nil x.i_do_not_exist.zomg end + test "custom configuration responds to all messages" do + x = Rails.configuration.x + assert_equal true, x.respond_to?(:i_do_not_exist) + assert_kind_of Method, x.method(:i_do_not_exist) + assert_kind_of ActiveSupport::OrderedOptions, x.i_do_not_exist + end + private def new_app File.expand_path("#{app_path}/../new_app") diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 1ca6bbcecf..5dceaae96b 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -1,6 +1,6 @@ require "isolation/abstract_unit" -require 'rack/test' -require 'env_helpers' +require "rack/test" +require "env_helpers" class ::MyMailInterceptor def self.delivering_email(email); email; end @@ -34,9 +34,9 @@ module ApplicationTests FileUtils.cp_r(app_path, new_app) end - def app(env = 'development') + def app(env = "development") @app ||= begin - ENV['RAILS_ENV'] = env + ENV["RAILS_ENV"] = env # FIXME: shush Sass warning spam, not relevant to testing Railties Kernel.silence_warnings do @@ -45,13 +45,12 @@ module ApplicationTests Rails.application ensure - ENV.delete 'RAILS_ENV' + ENV.delete "RAILS_ENV" end end def setup build_app - boot_rails supress_default_config end @@ -75,7 +74,7 @@ module ApplicationTests switch_env "RAILS_ENV", nil do Rails.env = "development" assert_equal "development", Rails.env - assert_nil ENV['RAILS_ENV'] + assert_nil ENV["RAILS_ENV"] end end @@ -83,7 +82,7 @@ module ApplicationTests restore_default_config with_rails_env "development" do - app 'development' + app "development" assert Rails.application.config.log_tags.blank? end end @@ -92,13 +91,13 @@ module ApplicationTests restore_default_config with_rails_env "production" do - app 'production' + app "production" assert_equal [:request_id], Rails.application.config.log_tags end end test "lib dir is on LOAD_PATH during config" do - app_file 'lib/my_logger.rb', <<-RUBY + app_file "lib/my_logger.rb", <<-RUBY require "logger" class MyLogger < ::Logger end @@ -108,9 +107,9 @@ module ApplicationTests config.logger = MyLogger.new STDOUT RUBY - app 'development' + app "development" - assert_equal 'MyLogger', Rails.application.config.logger.class.name + assert_equal "MyLogger", Rails.application.config.logger.class.name end test "a renders exception on pending migration" do @@ -120,7 +119,7 @@ module ApplicationTests config.action_dispatch.show_exceptions = true RUBY - app_file 'db/migrate/20140708012246_create_user.rb', <<-RUBY + app_file "db/migrate/20140708012246_create_user.rb", <<-RUBY class CreateUser < ActiveRecord::Migration::Current def change create_table :users @@ -128,7 +127,7 @@ module ApplicationTests end RUBY - app 'development' + app "development" ActiveRecord::Migrator.migrations_paths = ["#{app_path}/db/migrate"] @@ -157,31 +156,31 @@ module ApplicationTests end test "Rails.application is nil until app is initialized" do - require 'rails' + require "rails" assert_nil Rails.application - app 'development' + app "development" assert_equal AppTemplate::Application.instance, Rails.application end test "Rails.application responds to all instance methods" do - app 'development' + app "development" assert_respond_to Rails.application, :routes_reloader assert_equal Rails.application.routes_reloader, AppTemplate::Application.routes_reloader end test "Rails::Application responds to paths" do - app 'development' + app "development" assert_respond_to AppTemplate::Application, :paths assert_equal ["#{app_path}/app/views"], AppTemplate::Application.paths["app/views"].expanded end test "the application root is set correctly" do - app 'development' + app "development" assert_equal Pathname.new(app_path), Rails.application.root end test "the application root can be seen from the application singleton" do - app 'development' + app "development" assert_equal Pathname.new(app_path), AppTemplate::Application.root end @@ -193,7 +192,7 @@ module ApplicationTests use_frameworks [] - app 'development' + app "development" assert_equal Pathname.new(new_app), Rails.application.root end @@ -204,7 +203,7 @@ module ApplicationTests use_frameworks [] Dir.chdir("#{app_path}") do - app 'development' + app "development" assert_equal Pathname.new("#{app_path}"), Rails.application.root end end @@ -214,7 +213,7 @@ module ApplicationTests config.root = "#{app_path}" RUBY - app 'development' + app "development" assert_instance_of Pathname, Rails.root end @@ -224,7 +223,7 @@ module ApplicationTests config.paths["public"] = "somewhere" RUBY - app 'development' + app "development" assert_instance_of Pathname, Rails.public_path end @@ -235,13 +234,13 @@ module ApplicationTests config.cache_classes = true RUBY - app 'development' + app "development" assert_equal :require, ActiveSupport::Dependencies.mechanism end test "application is always added to eager_load namespaces" do - app 'development' + app "development" assert_includes Rails.application.config.eager_load_namespaces, AppTemplate::Application end @@ -257,7 +256,7 @@ module ApplicationTests use_frameworks [] assert_nothing_raised do - app 'development' + app "development" end end @@ -269,18 +268,18 @@ module ApplicationTests RUBY assert_nothing_raised do - app 'development' + app "development" end end test "filter_parameters should be able to set via config.filter_parameters in an initializer" do - app_file 'config/initializers/filter_parameters_logging.rb', <<-RUBY + app_file "config/initializers/filter_parameters_logging.rb", <<-RUBY Rails.application.config.filter_parameters += [ :password, :foo, 'bar' ] RUBY - app 'development' + app "development" - assert_equal [:password, :foo, 'bar'], Rails.application.env_config['action_dispatch.parameter_filter'] + assert_equal [:password, :foo, "bar"], Rails.application.env_config["action_dispatch.parameter_filter"] end test "config.to_prepare is forwarded to ActionDispatch" do @@ -294,7 +293,7 @@ module ApplicationTests assert !$prepared - app 'development' + app "development" get "/" assert $prepared @@ -306,7 +305,7 @@ module ApplicationTests end test "skipping config.encoding still results in 'utf-8' as the default" do - app 'development' + app "development" assert_utf8 end @@ -315,7 +314,7 @@ module ApplicationTests config.encoding = "utf-8" RUBY - app 'development' + app "development" assert_utf8 end @@ -324,7 +323,7 @@ module ApplicationTests config.paths["public"] = "somewhere" RUBY - app 'development' + app "development" assert_equal Pathname.new(app_path).join("somewhere"), Rails.public_path end @@ -332,7 +331,7 @@ module ApplicationTests restore_default_config with_rails_env "production" do - app 'production' + app "production" assert_not app.config.public_file_server.enabled end end @@ -342,7 +341,7 @@ module ApplicationTests with_rails_env "production" do switch_env "RAILS_SERVE_STATIC_FILES", "1" do - app 'production' + app "production" assert app.config.public_file_server.enabled end end @@ -353,7 +352,7 @@ module ApplicationTests with_rails_env "production" do switch_env "RAILS_LOG_TO_STDOUT", "1" do - app 'production' + app "production" assert ActiveSupport::Logger.logger_outputs_to?(app.config.logger, STDOUT) end end @@ -364,7 +363,7 @@ module ApplicationTests with_rails_env "production" do switch_env "RAILS_SERVE_STATIC_FILES", " " do - app 'production' + app "production" assert_not app.config.public_file_server.enabled end end @@ -392,7 +391,7 @@ module ApplicationTests test "Use key_generator when secret_key_base is set" do make_basic_app do |application| - application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' + application.secrets.secret_key_base = "b3c631c314c0bbca50c1b2843150fe33" application.config.session_store :disabled end @@ -405,53 +404,53 @@ module ApplicationTests get "/" - secret = app.key_generator.generate_key('signed cookie') + secret = app.key_generator.generate_key("signed cookie") verifier = ActiveSupport::MessageVerifier.new(secret) - assert_equal 'some_value', verifier.verify(last_response.body) + assert_equal "some_value", verifier.verify(last_response.body) end test "application verifier can be used in the entire application" do make_basic_app do |application| - application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' + application.secrets.secret_key_base = "b3c631c314c0bbca50c1b2843150fe33" application.config.session_store :disabled end message = app.message_verifier(:sensitive_value).generate("some_value") - assert_equal 'some_value', Rails.application.message_verifier(:sensitive_value).verify(message) + assert_equal "some_value", Rails.application.message_verifier(:sensitive_value).verify(message) - secret = app.key_generator.generate_key('sensitive_value') + secret = app.key_generator.generate_key("sensitive_value") verifier = ActiveSupport::MessageVerifier.new(secret) - assert_equal 'some_value', verifier.verify(message) + 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 + app_file "config/initializers/secret_token.rb", <<-RUBY Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" RUBY - app_file 'config/secrets.yml', <<-YAML + app_file "config/secrets.yml", <<-YAML development: secret_key_base: YAML - app 'development' + app "development" - 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 + 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) + 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 + app_file "config/initializers/secret_token.rb", <<-RUBY Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" RUBY - app_file 'config/secrets.yml', <<-YAML + app_file "config/secrets.yml", <<-YAML development: secret_key_base: YAML - app 'development' + app "development" assert_deprecated(/You didn't set `secret_key_base`./) do app.env_config @@ -459,12 +458,12 @@ module ApplicationTests end test "raise when secrets.secret_key_base is not a type of string" do - app_file 'config/secrets.yml', <<-YAML + app_file "config/secrets.yml", <<-YAML development: secret_key_base: 123 YAML - app 'development' + app "development" assert_raise(ArgumentError) do app.key_generator @@ -472,31 +471,31 @@ module ApplicationTests end test "prefer secrets.secret_token over config.secret_token" do - app_file 'config/initializers/secret_token.rb', <<-RUBY + app_file "config/initializers/secret_token.rb", <<-RUBY Rails.application.config.secret_token = "" RUBY - app_file 'config/secrets.yml', <<-YAML + app_file "config/secrets.yml", <<-YAML development: secret_token: 3b7cd727ee24e8444053437c36cc66c3 YAML - app 'development' + app "development" - assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token + assert_equal "3b7cd727ee24e8444053437c36cc66c3", app.secrets.secret_token end test "application verifier can build different verifiers" do make_basic_app do |application| - application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' + application.secrets.secret_key_base = "b3c631c314c0bbca50c1b2843150fe33" application.config.session_store :disabled end default_verifier = app.message_verifier(:sensitive_value) text_verifier = app.message_verifier(:text) - message = text_verifier.generate('some_value') + message = text_verifier.generate("some_value") - assert_equal 'some_value', text_verifier.verify(message) + assert_equal "some_value", text_verifier.verify(message) assert_raises ActiveSupport::MessageVerifier::InvalidSignature do default_verifier.verify(message) end @@ -506,106 +505,131 @@ module ApplicationTests end test "secrets.secret_key_base is used when config/secrets.yml is present" do - app_file 'config/secrets.yml', <<-YAML + app_file "config/secrets.yml", <<-YAML development: secret_key_base: 3b7cd727ee24e8444053437c36cc66c3 YAML - app 'development' - assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_key_base + app "development" + assert_equal "3b7cd727ee24e8444053437c36cc66c3", app.secrets.secret_key_base end test "secret_key_base is copied from config to secrets when not set" do remove_file "config/secrets.yml" - app_file 'config/initializers/secret_token.rb', <<-RUBY + app_file "config/initializers/secret_token.rb", <<-RUBY Rails.application.config.secret_key_base = "3b7cd727ee24e8444053437c36cc66c3" RUBY - app 'development' - assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_key_base + app "development" + 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 + app_file "config/initializers/secret_token.rb", <<-RUBY Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" RUBY - app_file 'config/secrets.yml', <<-YAML + app_file "config/secrets.yml", <<-YAML development: secret_key_base: secret_token: YAML - app 'development' + app "development" - assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.secrets.secret_token - assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token + 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 + app_file "config/secrets.yml", <<-YAML development: secret_key_base: 3b7cd727ee24e8444053437c36cc66c3 aws_access_key_id: myamazonaccesskeyid aws_secret_access_key: myamazonsecretaccesskey YAML - app 'development' + app "development" + + assert_equal "myamazonaccesskeyid", app.secrets.aws_access_key_id + assert_equal "myamazonsecretaccesskey", app.secrets.aws_secret_access_key + end + + test "shared secrets saved in config/secrets.yml are loaded in app secrets" do + app_file "config/secrets.yml", <<-YAML + shared: + api_key: 3b7cd727 + YAML + + app "development" + + assert_equal "3b7cd727", app.secrets.api_key + end + + test "shared secrets will yield to environment specific secrets" do + app_file "config/secrets.yml", <<-YAML + shared: + api_key: 3b7cd727 + + development: + api_key: abc12345 + YAML + + app "development" - assert_equal 'myamazonaccesskeyid', app.secrets.aws_access_key_id - assert_equal 'myamazonsecretaccesskey', app.secrets.aws_secret_access_key + assert_equal "abc12345", app.secrets.api_key end test "blank config/secrets.yml does not crash the loading process" do - app_file 'config/secrets.yml', <<-YAML + app_file "config/secrets.yml", <<-YAML YAML - app 'development' + app "development" 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 + app_file "config/initializers/secret_token.rb", <<-RUBY Rails.application.config.secret_key_base = "iaminallyoursecretkeybase" RUBY - app_file 'config/secrets.yml', <<-YAML + app_file "config/secrets.yml", <<-YAML development: secret_key_base: YAML - app 'development' + app "development" 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 + app_file "config/initializers/secret_token.rb", <<-RUBY Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" RUBY - app_file 'config/secrets.yml', <<-YAML + app_file "config/secrets.yml", <<-YAML development: secret_key_base: YAML - app 'development' + app "development" - assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token + 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 + app_file "config/initializers/secret_token.rb", <<-RUBY Rails.application.config.secret_token = "" RUBY - app_file 'config/secrets.yml', <<-YAML + app_file "config/secrets.yml", <<-YAML development: secret_key_base: YAML - app 'development' + app "development" - assert_equal '', app.config.secret_token + 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 @@ -626,7 +650,7 @@ module ApplicationTests end test "default form builder specified as a string" do - app_file 'config/initializers/form_builder.rb', <<-RUBY + app_file "config/initializers/form_builder.rb", <<-RUBY class CustomFormBuilder < ActionView::Helpers::FormBuilder def text_field(attribute, *args) label(attribute) + super(attribute, *args) @@ -635,15 +659,14 @@ module ApplicationTests Rails.configuration.action_view.default_form_builder = "CustomFormBuilder" RUBY - app_file 'app/models/post.rb', <<-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 + 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 %>" @@ -657,14 +680,14 @@ module ApplicationTests end RUBY - app 'development' + app "development" 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 + app_file "app/models/post.rb", <<-RUBY class Post include ActiveModel::Model def to_key; [1]; end @@ -674,7 +697,7 @@ module ApplicationTests token = "cf50faa3fe97702ca1ae" - app_file 'app/controllers/posts_controller.rb', <<-RUBY + app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ApplicationController def show render inline: "<%= begin; form_for(Post.new) {}; rescue => e; e.to_s; end %>" @@ -686,7 +709,7 @@ module ApplicationTests private - def form_authenticity_token(*args); token; end # stub the authenticy token + def form_authenticity_token(*args); token; end # stub the authenticity token end RUBY @@ -696,7 +719,7 @@ module ApplicationTests end RUBY - app 'development' + app "development" params = { authenticity_token: token } @@ -718,7 +741,7 @@ module ApplicationTests test "request forgery token param can be changed" do make_basic_app do |application| - application.config.action_controller.request_forgery_protection_token = '_xsrf_token_here' + application.config.action_controller.request_forgery_protection_token = "_xsrf_token_here" end class ::OmgController < ActionController::Base @@ -749,12 +772,12 @@ module ApplicationTests config.action_mailer.interceptors = MyMailInterceptor RUBY - app 'development' + app "development" require "mail" _ = ActionMailer::Base - assert_equal [::MyMailInterceptor], ::Mail.send(:class_variable_get, "@@delivery_interceptors") + assert_equal [::MyMailInterceptor], ::Mail.class_variable_get(:@@delivery_interceptors) end test "registers multiple interceptors with ActionMailer" do @@ -762,12 +785,12 @@ module ApplicationTests config.action_mailer.interceptors = [MyMailInterceptor, "MyOtherMailInterceptor"] RUBY - app 'development' + app "development" require "mail" _ = ActionMailer::Base - assert_equal [::MyMailInterceptor, ::MyOtherMailInterceptor], ::Mail.send(:class_variable_get, "@@delivery_interceptors") + assert_equal [::MyMailInterceptor, ::MyOtherMailInterceptor], ::Mail.class_variable_get(:@@delivery_interceptors) end test "registers preview interceptors with ActionMailer" do @@ -775,7 +798,7 @@ module ApplicationTests config.action_mailer.preview_interceptors = MyPreviewMailInterceptor RUBY - app 'development' + app "development" require "mail" _ = ActionMailer::Base @@ -788,7 +811,7 @@ module ApplicationTests config.action_mailer.preview_interceptors = [MyPreviewMailInterceptor, "MyOtherPreviewMailInterceptor"] RUBY - app 'development' + app "development" require "mail" _ = ActionMailer::Base @@ -797,11 +820,11 @@ module ApplicationTests end test "default preview interceptor can be removed" do - app_file 'config/initializers/preview_interceptors.rb', <<-RUBY + app_file "config/initializers/preview_interceptors.rb", <<-RUBY ActionMailer::Base.preview_interceptors.delete(ActionMailer::InlinePreviewInterceptor) RUBY - app 'development' + app "development" require "mail" _ = ActionMailer::Base @@ -814,12 +837,12 @@ module ApplicationTests config.action_mailer.observers = MyMailObserver RUBY - app 'development' + app "development" require "mail" _ = ActionMailer::Base - assert_equal [::MyMailObserver], ::Mail.send(:class_variable_get, "@@delivery_notification_observers") + assert_equal [::MyMailObserver], ::Mail.class_variable_get(:@@delivery_notification_observers) end test "registers multiple observers with ActionMailer" do @@ -827,12 +850,12 @@ module ApplicationTests config.action_mailer.observers = [MyMailObserver, "MyOtherMailObserver"] RUBY - app 'development' + app "development" require "mail" _ = ActionMailer::Base - assert_equal [::MyMailObserver, ::MyOtherMailObserver], ::Mail.send(:class_variable_get, "@@delivery_notification_observers") + assert_equal [::MyMailObserver, ::MyOtherMailObserver], ::Mail.class_variable_get(:@@delivery_notification_observers) end test "allows setting the queue name for the ActionMailer::DeliveryJob" do @@ -840,12 +863,12 @@ module ApplicationTests config.action_mailer.deliver_later_queue_name = 'test_default' RUBY - app 'development' + app "development" require "mail" _ = ActionMailer::Base - assert_equal 'test_default', ActionMailer::Base.send(:class_variable_get, "@@deliver_later_queue_name") + assert_equal "test_default", ActionMailer::Base.class_variable_get(:@@deliver_later_queue_name) end test "valid timezone is setup correctly" do @@ -854,7 +877,7 @@ module ApplicationTests config.time_zone = "Wellington" RUBY - app 'development' + app "development" assert_equal "Wellington", Rails.application.config.time_zone end @@ -866,7 +889,7 @@ module ApplicationTests RUBY assert_raise(ArgumentError) do - app 'development' + app "development" end end @@ -876,7 +899,7 @@ module ApplicationTests config.beginning_of_week = :wednesday RUBY - app 'development' + app "development" assert_equal :wednesday, Rails.application.config.beginning_of_week end @@ -888,15 +911,15 @@ module ApplicationTests RUBY assert_raise(ArgumentError) do - app 'development' + app "development" end end test "config.action_view.cache_template_loading with cache_classes default" do add_to_config "config.cache_classes = true" - app 'development' - require 'action_view/base' + app "development" + require "action_view/base" assert_equal true, ActionView::Resolver.caching? end @@ -904,8 +927,8 @@ module ApplicationTests test "config.action_view.cache_template_loading without cache_classes default" do add_to_config "config.cache_classes = false" - app 'development' - require 'action_view/base' + app "development" + require "action_view/base" assert_equal false, ActionView::Resolver.caching? end @@ -916,8 +939,8 @@ module ApplicationTests config.action_view.cache_template_loading = false RUBY - app 'development' - require 'action_view/base' + app "development" + require "action_view/base" assert_equal false, ActionView::Resolver.caching? end @@ -928,8 +951,8 @@ module ApplicationTests config.action_view.cache_template_loading = true RUBY - app 'development' - require 'action_view/base' + app "development" + require "action_view/base" assert_equal true, ActionView::Resolver.caching? end @@ -939,11 +962,11 @@ module ApplicationTests add_to_env_config "development", "config.cache_classes = false" # These requires are to emulate an engine loading Action View before the application - require 'action_view' - require 'action_view/railtie' - require 'action_view/base' + require "action_view" + require "action_view/railtie" + require "action_view/base" - app 'development' + app "development" assert_equal false, ActionView::Resolver.caching? end @@ -960,15 +983,15 @@ module ApplicationTests end get "/" - assert_equal 'true', last_response.body + assert_equal "true", last_response.body end test "config.action_controller.wrap_parameters is set in ActionController::Base" do - app_file 'config/initializers/wrap_parameters.rb', <<-RUBY + app_file "config/initializers/wrap_parameters.rb", <<-RUBY ActionController::Base.wrap_parameters format: [:json] RUBY - app_file 'app/models/post.rb', <<-RUBY + app_file "app/models/post.rb", <<-RUBY class Post def self.attribute_names %w(title) @@ -976,13 +999,13 @@ module ApplicationTests end RUBY - app_file 'app/controllers/application_controller.rb', <<-RUBY + app_file "app/controllers/application_controller.rb", <<-RUBY class ApplicationController < ActionController::Base protect_from_forgery with: :reset_session # as we are testing API here end RUBY - app_file 'app/controllers/posts_controller.rb', <<-RUBY + app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ApplicationController def create render text: params[:post].inspect @@ -996,14 +1019,14 @@ module ApplicationTests end RUBY - app 'development' + app "development" post "/posts.json", '{ "title": "foo", "name": "bar" }', "CONTENT_TYPE" => "application/json" assert_equal '<ActionController::Parameters {"title"=>"foo"} permitted: false>', last_response.body end test "config.action_controller.permit_all_parameters = true" do - app_file 'app/controllers/posts_controller.rb', <<-RUBY + app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ActionController::Base def create render text: params[:post].permitted? ? "permitted" : "forbidden" @@ -1018,14 +1041,14 @@ module ApplicationTests config.action_controller.permit_all_parameters = true RUBY - app 'development' + app "development" - post "/posts", {post: {"title" =>"zomg"}} - assert_equal 'permitted', last_response.body + post "/posts", post: { "title" =>"zomg" } + assert_equal "permitted", last_response.body end test "config.action_controller.action_on_unpermitted_parameters = :raise" do - app_file 'app/controllers/posts_controller.rb', <<-RUBY + app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ActionController::Base def create render text: params.require(:post).permit(:name) @@ -1040,16 +1063,16 @@ module ApplicationTests config.action_controller.action_on_unpermitted_parameters = :raise RUBY - app 'development' + app "development" assert_equal :raise, ActionController::Parameters.action_on_unpermitted_parameters - post "/posts", {post: {"title" =>"zomg"}} + post "/posts", post: { "title" =>"zomg" } assert_match "We're sorry, but something went wrong", last_response.body end test "config.action_controller.always_permitted_parameters are: controller, action by default" do - app 'development' + app "development" assert_equal %w(controller action), ActionController::Parameters.always_permitted_parameters end @@ -1058,13 +1081,13 @@ module ApplicationTests config.action_controller.always_permitted_parameters = %w( controller action format ) RUBY - app 'development' + app "development" assert_equal %w( controller action format ), ActionController::Parameters.always_permitted_parameters end - test "config.action_controller.always_permitted_parameters = ['controller','action','format'] does not raise exeception" do - app_file 'app/controllers/posts_controller.rb', <<-RUBY + test "config.action_controller.always_permitted_parameters = ['controller','action','format'] does not raise exception" do + app_file "app/controllers/posts_controller.rb", <<-RUBY class PostsController < ActionController::Base def create render text: params.permit(post: [:title]) @@ -1080,28 +1103,28 @@ module ApplicationTests config.action_controller.action_on_unpermitted_parameters = :raise RUBY - app 'development' + app "development" assert_equal :raise, ActionController::Parameters.action_on_unpermitted_parameters - post "/posts", {post: {"title" =>"zomg"}, format: "json"} + post "/posts", post: { "title" =>"zomg" }, format: "json" assert_equal 200, last_response.status end test "config.action_controller.action_on_unpermitted_parameters is :log by default on development" do - app 'development' + app "development" assert_equal :log, ActionController::Parameters.action_on_unpermitted_parameters end test "config.action_controller.action_on_unpermitted_parameters is :log by default on test" do - app 'test' + app "test" assert_equal :log, ActionController::Parameters.action_on_unpermitted_parameters end test "config.action_controller.action_on_unpermitted_parameters is false by default on production" do - app 'production' + app "production" assert_equal false, ActionController::Parameters.action_on_unpermitted_parameters end @@ -1121,21 +1144,21 @@ module ApplicationTests end get "/", {}, "HTTP_ACCEPT" => "application/xml" - assert_equal 'HTML', last_response.body + assert_equal "HTML", last_response.body get "/", { format: :xml }, "HTTP_ACCEPT" => "application/xml" - assert_equal 'XML', last_response.body + assert_equal "XML", last_response.body end test "Rails.application#env_config exists and include some existing parameters" do make_basic_app assert_respond_to app, :env_config - assert_equal app.env_config['action_dispatch.parameter_filter'], app.config.filter_parameters - assert_equal app.env_config['action_dispatch.show_exceptions'], app.config.action_dispatch.show_exceptions - assert_equal app.env_config['action_dispatch.logger'], Rails.logger - assert_equal app.env_config['action_dispatch.backtrace_cleaner'], Rails.backtrace_cleaner - assert_equal app.env_config['action_dispatch.key_generator'], Rails.application.key_generator + assert_equal app.env_config["action_dispatch.parameter_filter"], app.config.filter_parameters + assert_equal app.env_config["action_dispatch.show_exceptions"], app.config.action_dispatch.show_exceptions + assert_equal app.env_config["action_dispatch.logger"], Rails.logger + assert_equal app.env_config["action_dispatch.backtrace_cleaner"], Rails.backtrace_cleaner + assert_equal app.env_config["action_dispatch.key_generator"], Rails.application.key_generator end test "config.colorize_logging default is true" do @@ -1162,6 +1185,22 @@ module ApplicationTests end end + test "default session store initializer does not overwrite the user defined session store even if it is disabled" do + make_basic_app do |application| + application.config.session_store :disabled + end + + assert_equal nil, app.config.session_store + end + + test "default session store initializer sets session store to cookie store" do + session_options = { key: "_myapp_session", cookie_only: true } + make_basic_app + + assert_equal ActionDispatch::Session::CookieStore, app.config.session_store + assert_equal session_options, app.config.session_options + end + test "config.log_level with custom logger" do make_basic_app do |application| application.config.logger = Logger.new(STDOUT) @@ -1180,13 +1219,13 @@ module ApplicationTests test "config.active_record.dump_schema_after_migration is false on production" do build_app - app 'production' + app "production" assert_not ActiveRecord::Base.dump_schema_after_migration end test "config.active_record.dump_schema_after_migration is true by default on development" do - app 'development' + app "development" assert ActiveRecord::Base.dump_schema_after_migration end @@ -1212,12 +1251,12 @@ module ApplicationTests end RUBY - app 'development' + app "development" assert_not Rails.configuration.ran_block - require 'rake' - require 'rake/testtask' - require 'rdoc/task' + require "rake" + require "rake/testtask" + require "rdoc/task" Rails.application.load_tasks assert Rails.configuration.ran_block @@ -1234,7 +1273,7 @@ module ApplicationTests end RUBY - app 'development' + app "development" assert_not Rails.configuration.ran_block Rails.application.load_generators @@ -1252,7 +1291,7 @@ module ApplicationTests end RUBY - app 'development' + app "development" assert_not Rails.configuration.ran_block Rails.application.load_console @@ -1270,7 +1309,7 @@ module ApplicationTests end RUBY - app 'development' + app "development" assert_not Rails.configuration.ran_block Rails.application.load_runner @@ -1278,7 +1317,7 @@ module ApplicationTests end test "loading the first existing database configuration available" do - app_file 'config/environments/development.rb', <<-RUBY + app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do config.paths.add 'config/database', with: 'config/nonexistent.yml' @@ -1286,44 +1325,44 @@ module ApplicationTests end RUBY - app 'development' + app "development" assert_kind_of Hash, Rails.application.config.database_configuration end - test 'raises with proper error message if no database configuration found' do + test "raises with proper error message if no database configuration found" do FileUtils.rm("#{app_path}/config/database.yml") - app 'development' + app "development" err = assert_raises RuntimeError do Rails.application.config.database_configuration end - assert_match 'config/database', err.message + assert_match "config/database", err.message end - test 'config.action_mailer.show_previews defaults to true in development' do - app 'development' + test "config.action_mailer.show_previews defaults to true in development" do + app "development" assert Rails.application.config.action_mailer.show_previews end - test 'config.action_mailer.show_previews defaults to false in production' do - app 'production' + test "config.action_mailer.show_previews defaults to false in production" do + app "production" 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 + test "config.action_mailer.show_previews can be set in the configuration file" do add_to_config <<-RUBY config.action_mailer.show_previews = true RUBY - app 'production' + app "production" assert_equal true, Rails.application.config.action_mailer.show_previews end test "config_for loads custom configuration from yaml files" do - app_file 'config/custom.yml', <<-RUBY + app_file "config/custom.yml", <<-RUBY development: key: 'custom key' RUBY @@ -1332,13 +1371,13 @@ module ApplicationTests config.my_custom_config = config_for('custom') RUBY - app 'development' + app "development" - assert_equal 'custom key', Rails.application.config.my_custom_config['key'] + assert_equal "custom key", Rails.application.config.my_custom_config["key"] end test "config_for uses the Pathname object if it is provided" do - app_file 'config/custom.yml', <<-RUBY + app_file "config/custom.yml", <<-RUBY development: key: 'custom key' RUBY @@ -1347,9 +1386,9 @@ module ApplicationTests config.my_custom_config = config_for(Pathname.new(Rails.root.join("config/custom.yml"))) RUBY - app 'development' + app "development" - assert_equal 'custom key', Rails.application.config.my_custom_config['key'] + assert_equal "custom key", Rails.application.config.my_custom_config["key"] end test "config_for raises an exception if the file does not exist" do @@ -1358,14 +1397,14 @@ module ApplicationTests RUBY exception = assert_raises(RuntimeError) do - app 'development' + app "development" end assert_equal "Could not load configuration. No such file - #{app_path}/config/custom.yml", exception.message end test "config_for without the environment configured returns an empty hash" do - app_file 'config/custom.yml', <<-RUBY + app_file "config/custom.yml", <<-RUBY test: key: 'custom key' RUBY @@ -1374,26 +1413,26 @@ module ApplicationTests config.my_custom_config = config_for('custom') RUBY - app 'development' + app "development" assert_equal({}, Rails.application.config.my_custom_config) end test "config_for with empty file returns an empty hash" do - app_file 'config/custom.yml', <<-RUBY + app_file "config/custom.yml", <<-RUBY RUBY add_to_config <<-RUBY config.my_custom_config = config_for('custom') RUBY - app 'development' + app "development" assert_equal({}, Rails.application.config.my_custom_config) end test "config_for containing ERB tags should evaluate" do - app_file 'config/custom.yml', <<-RUBY + app_file "config/custom.yml", <<-RUBY development: key: <%= 'custom key' %> RUBY @@ -1402,13 +1441,13 @@ module ApplicationTests config.my_custom_config = config_for('custom') RUBY - app 'development' + app "development" - assert_equal 'custom key', Rails.application.config.my_custom_config['key'] + assert_equal "custom key", Rails.application.config.my_custom_config["key"] end test "config_for with syntax error show a more descriptive exception" do - app_file 'config/custom.yml', <<-RUBY + app_file "config/custom.yml", <<-RUBY development: key: foo: RUBY @@ -1418,14 +1457,14 @@ module ApplicationTests RUBY exception = assert_raises(RuntimeError) do - app 'development' + app "development" end - assert_match 'YAML syntax error occurred while parsing', exception.message + assert_match "YAML syntax error occurred while parsing", exception.message end test "config_for allows overriding the environment" do - app_file 'config/custom.yml', <<-RUBY + app_file "config/custom.yml", <<-RUBY test: key: 'walrus' production: @@ -1437,11 +1476,11 @@ module ApplicationTests RUBY require "#{app_path}/config/environment" - assert_equal 'unicorn', Rails.application.config.my_custom_config['key'] + assert_equal "unicorn", Rails.application.config.my_custom_config["key"] end test "api_only is false by default" do - app 'development' + app "development" refute Rails.application.config.api_only end @@ -1449,7 +1488,7 @@ module ApplicationTests add_to_config <<-RUBY config.api_only = true RUBY - app 'development' + app "development" Rails.application.load_generators assert Rails.configuration.api_only @@ -1459,7 +1498,7 @@ module ApplicationTests add_to_config <<-RUBY config.api_only = true RUBY - app 'development' + app "development" assert_equal :api, Rails.configuration.debug_exception_response_format end @@ -1469,13 +1508,13 @@ module ApplicationTests config.api_only = true RUBY - app_file 'config/environments/development.rb', <<-RUBY + app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do config.debug_exception_response_format = :default end RUBY - app 'development' + app "development" assert_equal :default, Rails.configuration.debug_exception_response_format end diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb index ea68e63f8f..72f340df34 100644 --- a/railties/test/application/console_test.rb +++ b/railties/test/application/console_test.rb @@ -1,11 +1,10 @@ -require 'isolation/abstract_unit' +require "isolation/abstract_unit" class ConsoleTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup build_app - boot_rails end def teardown @@ -30,7 +29,7 @@ class ConsoleTest < ActiveSupport::TestCase end def test_app_can_access_path_helper_method - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get 'foo', to: 'foo#index' end @@ -38,7 +37,7 @@ class ConsoleTest < ActiveSupport::TestCase load_environment console_session = irb_context.app - assert_equal '/foo', console_session.foo_path + assert_equal "/foo", console_session.foo_path end def test_new_session_should_return_integration_session @@ -89,8 +88,8 @@ class ConsoleTest < ActiveSupport::TestCase helper = irb_context.helper assert_not_nil helper assert_instance_of ActionView::Base, helper - assert_equal 'Once upon a time in a world...', - helper.truncate('Once upon a time in a world far far away') + assert_equal "Once upon a time in a world...", + helper.truncate("Once upon a time in a world far far away") end end @@ -104,7 +103,7 @@ class FullStackConsoleTest < ActiveSupport::TestCase skip "PTY unavailable" unless defined?(PTY) && PTY.respond_to?(:open) build_app - app_file 'app/models/post.rb', <<-CODE + app_file "app/models/post.rb", <<-CODE class Post < ActiveRecord::Base end CODE @@ -127,7 +126,7 @@ class FullStackConsoleTest < ActiveSupport::TestCase end end - assert output.include?(expected), "#{expected.inspect} expected, but got:\n\n#{output}" + assert_includes output, expected, "#{expected.inspect} expected, but got:\n\n#{output}" end def write_prompt(command, expected_output = nil) diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb index 644af0e737..0153f94504 100644 --- a/railties/test/application/generators_test.rb +++ b/railties/test/application/generators_test.rb @@ -6,7 +6,6 @@ module ApplicationTests def setup build_app - boot_rails end def teardown @@ -30,7 +29,7 @@ module ApplicationTests end test "allow running plugin new generator inside Rails app directory" do - FileUtils.cd(rails_root){ `ruby bin/rails plugin new vendor/plugins/bukkits` } + FileUtils.cd(rails_root) { `ruby bin/rails plugin new vendor/plugins/bukkits` } assert File.exist?(File.join(rails_root, "vendor/plugins/bukkits/test/dummy/config/application.rb")) end @@ -114,7 +113,7 @@ module ApplicationTests test "generators with string and hash for options should generate symbol keys" do with_bare_config do |c| c.generators do |g| - g.orm 'data_mapper', migration: false + g.orm "data_mapper", migration: false end expected = { @@ -135,10 +134,10 @@ module ApplicationTests require "#{app_path}/config/environment" Rails.application.load_generators - assert Rails::Generators.hidden_namespaces.include?("assets") - assert Rails::Generators.hidden_namespaces.include?("helper") - assert Rails::Generators.hidden_namespaces.include?("js") - assert Rails::Generators.hidden_namespaces.include?("css") + assert_includes Rails::Generators.hidden_namespaces, "assets" + assert_includes Rails::Generators.hidden_namespaces, "helper" + assert_includes Rails::Generators.hidden_namespaces, "js" + assert_includes Rails::Generators.hidden_namespaces, "css" assert Rails::Generators.options[:rails][:api] assert_equal false, Rails::Generators.options[:rails][:assets] assert_equal false, Rails::Generators.options[:rails][:helper] @@ -166,7 +165,7 @@ module ApplicationTests config.api_only = true RUBY - FileUtils.cd(rails_root){ `bin/rails generate mailer notifier foo` } + FileUtils.cd(rails_root) { `bin/rails generate mailer notifier foo` } assert File.exist?(File.join(rails_root, "app/views/notifier_mailer/foo.text.erb")) assert File.exist?(File.join(rails_root, "app/views/notifier_mailer/foo.html.erb")) end diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index 44209a52f7..b2cd339c1a 100644 --- a/railties/test/application/initializers/frameworks_test.rb +++ b/railties/test/application/initializers/frameworks_test.rb @@ -6,7 +6,6 @@ module ApplicationTests def setup build_app - boot_rails FileUtils.rm_rf "#{app_path}/config/environments" end @@ -129,7 +128,7 @@ module ApplicationTests end RUBY - require 'rack/test' + require "rack/test" extend Rack::Test::Methods get "/foo/included_helpers" @@ -161,10 +160,10 @@ module ApplicationTests end RUBY - require 'rack/test' + require "rack/test" extend Rack::Test::Methods - get 'omg/show' + get "omg/show" assert_equal '{"omg":"omg"}', last_response.body end @@ -176,7 +175,7 @@ module ApplicationTests end test "assignment config.encoding to default_charset" do - charset = 'Shift_JIS' + charset = "Shift_JIS" add_to_config "config.encoding = '#{charset}'" require "#{app_path}/config/environment" assert_equal charset, ActionDispatch::Response.default_charset @@ -204,7 +203,7 @@ module ApplicationTests test "active_record extensions are applied to ActiveRecord" do add_to_config "config.active_record.table_name_prefix = 'tbl_'" require "#{app_path}/config/environment" - assert_equal 'tbl_', ActiveRecord::Base.table_name_prefix + assert_equal "tbl_", ActiveRecord::Base.table_name_prefix end test "database middleware doesn't initialize when activerecord is not in frameworks" do @@ -238,7 +237,7 @@ module ApplicationTests begin require "#{app_path}/config/environment" orig_database_url = ENV.delete("DATABASE_URL") - orig_rails_env, Rails.env = Rails.env, 'development' + orig_rails_env, Rails.env = Rails.env, "development" ActiveRecord::Base.establish_connection assert ActiveRecord::Base.connection assert_match(/#{ActiveRecord::Base.configurations[Rails.env]['database']}/, ActiveRecord::Base.connection_config[:database]) @@ -253,7 +252,7 @@ module ApplicationTests begin require "#{app_path}/config/environment" orig_database_url = ENV.delete("DATABASE_URL") - orig_rails_env, Rails.env = Rails.env, 'development' + orig_rails_env, Rails.env = Rails.env, "development" database_url_db_name = "db/database_url_db.sqlite3" ENV["DATABASE_URL"] = "sqlite3:#{database_url_db_name}" ActiveRecord::Base.establish_connection diff --git a/railties/test/application/initializers/hooks_test.rb b/railties/test/application/initializers/hooks_test.rb index b2cea0a8e1..0309d02730 100644 --- a/railties/test/application/initializers/hooks_test.rb +++ b/railties/test/application/initializers/hooks_test.rb @@ -6,7 +6,6 @@ module ApplicationTests def setup build_app - boot_rails FileUtils.rm_rf "#{app_path}/config/environments" end @@ -58,7 +57,7 @@ module ApplicationTests require "#{app_path}/config/environment" assert $activerecord_configurations - assert $activerecord_configurations['development'] + assert $activerecord_configurations["development"] end test "after_initialize happens after to_prepare in development" do diff --git a/railties/test/application/initializers/i18n_test.rb b/railties/test/application/initializers/i18n_test.rb index 0f9bb41053..206e42703b 100644 --- a/railties/test/application/initializers/i18n_test.rb +++ b/railties/test/application/initializers/i18n_test.rb @@ -6,7 +6,6 @@ module ApplicationTests def setup build_app - boot_rails FileUtils.rm_rf "#{app_path}/config/environments" require "rails/all" end @@ -31,7 +30,7 @@ module ApplicationTests end def assert_no_fallbacks - assert !I18n.backend.class.included_modules.include?(I18n::Backend::Fallbacks) + assert_not_includes I18n.backend.class.included_modules, I18n::Backend::Fallbacks end # Locales @@ -63,8 +62,8 @@ module ApplicationTests "#{app_path}/config/locales/en.yml", "#{app_path}/config/another_locale.yml" ], Rails.application.config.i18n.load_path - assert I18n.load_path.include?("#{app_path}/config/locales/en.yml") - assert I18n.load_path.include?("#{app_path}/config/another_locale.yml") + assert_includes I18n.load_path, "#{app_path}/config/locales/en.yml" + assert_includes I18n.load_path, "#{app_path}/config/another_locale.yml" end test "load_path is populated before eager loaded models" do @@ -77,19 +76,19 @@ en: foo: "1" YAML - app_file 'app/models/foo.rb', <<-RUBY + app_file "app/models/foo.rb", <<-RUBY class Foo < ActiveRecord::Base @foo = I18n.t(:foo) end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get '/i18n', :to => lambda { |env| [200, {}, [Foo.instance_variable_get('@foo')]] } end RUBY - require 'rack/test' + require "rack/test" extend Rack::Test::Methods load_app @@ -107,13 +106,13 @@ en: foo: "1" YAML - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get '/i18n', :to => lambda { |env| [200, {}, [I18n.t(:foo)]] } end RUBY - require 'rack/test' + require "rack/test" extend Rack::Test::Methods load_app @@ -142,13 +141,13 @@ en: foo: "1" YAML - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get '/i18n', :to => lambda { |env| [200, {}, [I18n.t(:foo)]] } end RUBY - require 'rack/test' + require "rack/test" extend Rack::Test::Methods load_app @@ -178,13 +177,13 @@ en: foo: "1" YAML - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get '/i18n', :to => lambda { |env| [200, {}, [I18n.load_path.inspect]] } end RUBY - require 'rack/test' + require "rack/test" extend Rack::Test::Methods load_app @@ -215,7 +214,7 @@ fr: test "config.i18n.fallbacks = true initializes I18n.fallbacks with default settings" do I18n::Railtie.config.i18n.fallbacks = true load_app - assert I18n.backend.class.included_modules.include?(I18n::Backend::Fallbacks) + assert_includes I18n.backend.class.included_modules, I18n::Backend::Fallbacks assert_fallbacks de: [:de, :en] end @@ -223,7 +222,7 @@ fr: I18n::Railtie.config.i18n.fallbacks = true I18n::Railtie.config.i18n.backend = Class.new(I18n::Backend::Simple).new load_app - assert I18n.backend.class.included_modules.include?(I18n::Backend::Fallbacks) + assert_includes I18n.backend.class.included_modules, I18n::Backend::Fallbacks assert_fallbacks de: [:de, :en] end @@ -234,7 +233,7 @@ fr: end test "config.i18n.fallbacks.map = { :ca => :'es-ES' } initializes fallbacks with a mapping ca => es-ES" do - I18n::Railtie.config.i18n.fallbacks.map = { :ca => :'es-ES' } + I18n::Railtie.config.i18n.fallbacks.map = { ca: :'es-ES' } load_app assert_fallbacks ca: [:ca, :"es-ES", :es, :en] end @@ -246,13 +245,13 @@ fr: end test "[shortcut] config.i18n.fallbacks = [{ :ca => :'es-ES' }] initializes fallbacks with a mapping ca => es-ES" do - I18n::Railtie.config.i18n.fallbacks.map = { :ca => :'es-ES' } + I18n::Railtie.config.i18n.fallbacks.map = { ca: :'es-ES' } load_app assert_fallbacks ca: [:ca, :"es-ES", :es, :en] end test "[shortcut] config.i18n.fallbacks = [:'en-US', { :ca => :'es-ES' }] initializes fallbacks with the given arguments" do - I18n::Railtie.config.i18n.fallbacks = [:'en-US', { :ca => :'es-ES' }] + I18n::Railtie.config.i18n.fallbacks = [:'en-US', { ca: :'es-ES' }] load_app assert_fallbacks ca: [:ca, :"es-ES", :es, :'en-US', :en] end diff --git a/railties/test/application/initializers/load_path_test.rb b/railties/test/application/initializers/load_path_test.rb index cd05956356..dbefb22837 100644 --- a/railties/test/application/initializers/load_path_test.rb +++ b/railties/test/application/initializers/load_path_test.rb @@ -6,7 +6,6 @@ module ApplicationTests def setup build_app - boot_rails FileUtils.rm_rf "#{app_path}/config/environments" end @@ -20,7 +19,7 @@ module ApplicationTests RUBY require "#{app_path}/config/environment" - assert $:.include?("#{app_path}/app/models") + assert_includes $:, "#{app_path}/app/models" end test "initializing an application allows to load code on lib path inside application class definition" do @@ -37,7 +36,7 @@ module ApplicationTests require "#{app_path}/config/environment" end - assert $:.include?("#{app_path}/lib") + assert_includes $:, "#{app_path}/lib" end test "initializing an application eager load any path under app" do diff --git a/railties/test/application/initializers/notifications_test.rb b/railties/test/application/initializers/notifications_test.rb index 95655b74cf..b847ac6b36 100644 --- a/railties/test/application/initializers/notifications_test.rb +++ b/railties/test/application/initializers/notifications_test.rb @@ -6,7 +6,6 @@ module ApplicationTests def setup build_app - boot_rails end def teardown @@ -40,17 +39,17 @@ module ApplicationTests assert_match(/SHOW tables/, logger.logged(:debug).last) end - test 'rails load_config_initializer event is instrumented' do - app_file 'config/initializers/foo.rb', '' + test "rails load_config_initializer event is instrumented" do + app_file "config/initializers/foo.rb", "" events = [] callback = ->(*_) { events << _ } - ActiveSupport::Notifications.subscribed(callback, 'load_config_initializer.railties') do + ActiveSupport::Notifications.subscribed(callback, "load_config_initializer.railties") do app end assert_equal %w[load_config_initializer.railties], events.map(&:first) - assert_includes events.first.last[:initializer], 'config/initializers/foo.rb' + assert_includes events.first.last[:initializer], "config/initializers/foo.rb" end end end diff --git a/railties/test/application/integration_test_case_test.rb b/railties/test/application/integration_test_case_test.rb index d106d5159a..1118e5037a 100644 --- a/railties/test/application/integration_test_case_test.rb +++ b/railties/test/application/integration_test_case_test.rb @@ -1,4 +1,4 @@ -require 'isolation/abstract_unit' +require "isolation/abstract_unit" module ApplicationTests class IntegrationTestCaseTest < ActiveSupport::TestCase @@ -6,7 +6,6 @@ module ApplicationTests setup do build_app - boot_rails end teardown do @@ -14,9 +13,9 @@ module ApplicationTests end test "resets Action Mailer test deliveries" do - script('generate mailer BaseMailer welcome') + script("generate mailer BaseMailer welcome") - app_file 'test/integration/mailer_integration_test.rb', <<-RUBY + app_file "test/integration/mailer_integration_test.rb", <<-RUBY require 'test_helper' class MailerIntegrationTest < ActionDispatch::IntegrationTest @@ -43,4 +42,32 @@ module ApplicationTests assert_match(/0 failures, 0 errors/, output) end end + + class IntegrationTestDefaultApp < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + + setup do + build_app + end + + teardown do + teardown_app + end + + test "app method of integration tests returns test_app by default" do + app_file "test/integration/default_app_test.rb", <<-RUBY + require 'test_helper' + + class DefaultAppIntegrationTest < ActionDispatch::IntegrationTest + def test_app_returns_action_dispatch_test_app_by_default + assert_equal ActionDispatch.test_app, app + end + end + RUBY + + output = Dir.chdir(app_path) { `bin/rails test 2>&1` } + assert_equal 0, $?.to_i, output + assert_match(/0 failures, 0 errors/, output) + end + end end diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb index efb21ae473..38f96f3ab9 100644 --- a/railties/test/application/loading_test.rb +++ b/railties/test/application/loading_test.rb @@ -1,11 +1,10 @@ -require 'isolation/abstract_unit' +require "isolation/abstract_unit" class LoadingTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup build_app - boot_rails end def teardown @@ -26,11 +25,11 @@ class LoadingTest < ActiveSupport::TestCase require "#{rails_root}/config/environment" setup_ar! - p = Post.create(title: 'omg') + p = Post.create(title: "omg") assert_equal 1, Post.count - assert_equal 'omg', p.title + assert_equal "omg", p.title p = Post.first - assert_equal 'omg', p.title + assert_equal "omg", p.title end test "concerns in app are autoloaded" do @@ -103,14 +102,14 @@ class LoadingTest < ActiveSupport::TestCase end MODEL - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get '/load', to: lambda { |env| [200, {}, Post.all] } get '/unload', to: lambda { |env| [200, {}, []] } end RUBY - require 'rack/test' + require "rack/test" extend Rack::Test::Methods require "#{rails_root}/config/environment" @@ -133,7 +132,7 @@ class LoadingTest < ActiveSupport::TestCase config.cache_classes = false RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get '/c', to: lambda { |env| [200, {"Content-Type" => "text/plain"}, [User.counter.to_s]] } end @@ -145,7 +144,7 @@ class LoadingTest < ActiveSupport::TestCase end MODEL - require 'rack/test' + require "rack/test" extend Rack::Test::Methods require "#{rails_root}/config/environment" @@ -174,7 +173,7 @@ class LoadingTest < ActiveSupport::TestCase end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get '/c', to: lambda { |env| [200, {"Content-Type" => "text/plain"}, [User.counter.to_s]] } end @@ -186,7 +185,7 @@ class LoadingTest < ActiveSupport::TestCase end MODEL - require 'rack/test' + require "rack/test" extend Rack::Test::Methods require "#{rails_root}/config/environment" @@ -209,7 +208,7 @@ class LoadingTest < ActiveSupport::TestCase config.cache_classes = false RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY $counter ||= 0 Rails.application.routes.draw do get '/c', to: lambda { |env| User.name; [200, {"Content-Type" => "text/plain"}, [$counter.to_s]] } @@ -222,7 +221,7 @@ class LoadingTest < ActiveSupport::TestCase end MODEL - require 'rack/test' + require "rack/test" extend Rack::Test::Methods require "#{rails_root}/config/environment" @@ -241,7 +240,7 @@ class LoadingTest < ActiveSupport::TestCase config.cache_classes = false RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY $counter ||= 1 $counter *= 2 Rails.application.routes.draw do @@ -255,7 +254,7 @@ class LoadingTest < ActiveSupport::TestCase end MODEL - require 'rack/test' + require "rack/test" extend Rack::Test::Methods require "#{rails_root}/config/environment" @@ -274,7 +273,7 @@ class LoadingTest < ActiveSupport::TestCase config.cache_classes = false RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get '/title', to: lambda { |env| [200, {"Content-Type" => "text/plain"}, [Post.new.title]] } get '/body', to: lambda { |env| [200, {"Content-Type" => "text/plain"}, [Post.new.body]] } @@ -286,7 +285,7 @@ class LoadingTest < ActiveSupport::TestCase end MODEL - require 'rack/test' + require "rack/test" extend Rack::Test::Methods app_file "db/migrate/1_create_posts.rb", <<-MIGRATION @@ -299,7 +298,7 @@ class LoadingTest < ActiveSupport::TestCase end MIGRATION - Dir.chdir(app_path) { `rake db:migrate`} + Dir.chdir(app_path) { `rake db:migrate` } require "#{rails_root}/config/environment" get "/title" @@ -341,11 +340,11 @@ class LoadingTest < ActiveSupport::TestCase require "#{rails_root}/config/environment" - require 'rack/test' + require "rack/test" extend Rack::Test::Methods - get '/omg/show' - assert_equal 'OK', last_response.body + get "/omg/show" + assert_equal "OK", last_response.body end def test_initialize_can_be_called_at_any_time @@ -360,13 +359,13 @@ class LoadingTest < ActiveSupport::TestCase protected - def setup_ar! - ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") - ActiveRecord::Migration.verbose = false - ActiveRecord::Schema.define(version: 1) do - create_table :posts do |t| - t.string :title + def setup_ar! + ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") + ActiveRecord::Migration.verbose = false + ActiveRecord::Schema.define(version: 1) do + create_table :posts do |t| + t.string :title + end end end - end end diff --git a/railties/test/application/mailer_previews_test.rb b/railties/test/application/mailer_previews_test.rb index 643d876a26..790aca2aa4 100644 --- a/railties/test/application/mailer_previews_test.rb +++ b/railties/test/application/mailer_previews_test.rb @@ -1,6 +1,6 @@ -require 'isolation/abstract_unit' -require 'rack/test' -require 'base64' +require "isolation/abstract_unit" +require "rack/test" +require "base64" module ApplicationTests class MailerPreviewsTest < ActiveSupport::TestCase @@ -9,7 +9,6 @@ module ApplicationTests def setup build_app - boot_rails end def teardown @@ -28,10 +27,10 @@ module ApplicationTests assert_equal 404, last_response.status end - test "/rails/mailers is accessible with correct configuraiton" do + test "/rails/mailers is accessible with correct configuration" do add_to_config "config.action_mailer.show_previews = true" app("production") - get "/rails/mailers", {}, {"REMOTE_ADDR" => "4.2.42.42"} + get "/rails/mailers", {}, "REMOTE_ADDR" => "4.2.42.42" assert_equal 200, last_response.status end @@ -54,7 +53,7 @@ module ApplicationTests end test "mailer previews are loaded from the default preview_path" do - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -64,11 +63,11 @@ module ApplicationTests end RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -76,7 +75,7 @@ module ApplicationTests end RUBY - app('development') + app("development") get "/rails/mailers" assert_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body @@ -86,7 +85,7 @@ module ApplicationTests test "mailer previews are loaded from a custom preview_path" do add_to_config "config.action_mailer.preview_path = '#{app_path}/lib/mailer_previews'" - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -96,11 +95,11 @@ module ApplicationTests end RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - app_file 'lib/mailer_previews/notifier_preview.rb', <<-RUBY + app_file "lib/mailer_previews/notifier_preview.rb", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -108,7 +107,7 @@ module ApplicationTests end RUBY - app('development') + app("development") get "/rails/mailers" assert_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body @@ -116,12 +115,12 @@ module ApplicationTests end test "mailer previews are reloaded across requests" do - app('development') + app("development") get "/rails/mailers" assert_no_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -131,11 +130,11 @@ module ApplicationTests end RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -146,7 +145,7 @@ module ApplicationTests get "/rails/mailers" assert_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body - remove_file 'test/mailers/previews/notifier_preview.rb' + remove_file "test/mailers/previews/notifier_preview.rb" sleep(1) get "/rails/mailers" @@ -154,7 +153,7 @@ module ApplicationTests end test "mailer preview actions are added and removed" do - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -164,11 +163,11 @@ module ApplicationTests end RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -176,14 +175,14 @@ module ApplicationTests end RUBY - app('development') + app("development") get "/rails/mailers" assert_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body assert_match '<li><a href="/rails/mailers/notifier/foo">foo</a></li>', last_response.body assert_no_match '<li><a href="/rails/mailers/notifier/bar">bar</a></li>', last_response.body - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -197,15 +196,15 @@ module ApplicationTests end RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - text_template 'notifier/bar', <<-RUBY + text_template "notifier/bar", <<-RUBY Goodbye, World! RUBY - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -224,7 +223,7 @@ module ApplicationTests assert_match '<li><a href="/rails/mailers/notifier/foo">foo</a></li>', last_response.body assert_match '<li><a href="/rails/mailers/notifier/bar">bar</a></li>', last_response.body - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -234,9 +233,9 @@ module ApplicationTests end RUBY - remove_file 'app/views/notifier/bar.text.erb' + remove_file "app/views/notifier/bar.text.erb" - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -255,12 +254,12 @@ module ApplicationTests test "mailer previews are reloaded from a custom preview_path" do add_to_config "config.action_mailer.preview_path = '#{app_path}/lib/mailer_previews'" - app('development') + app("development") get "/rails/mailers" assert_no_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -270,11 +269,11 @@ module ApplicationTests end RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - app_file 'lib/mailer_previews/notifier_preview.rb', <<-RUBY + app_file "lib/mailer_previews/notifier_preview.rb", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -285,7 +284,7 @@ module ApplicationTests get "/rails/mailers" assert_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body - remove_file 'lib/mailer_previews/notifier_preview.rb' + remove_file "lib/mailer_previews/notifier_preview.rb" sleep(1) get "/rails/mailers" @@ -293,14 +292,14 @@ module ApplicationTests end test "mailer preview not found" do - app('development') + app("development") get "/rails/mailers/notifier" assert last_response.not_found? assert_match "Mailer preview 'notifier' not found", last_response.body end test "mailer preview email not found" do - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -310,11 +309,11 @@ module ApplicationTests end RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -322,7 +321,7 @@ module ApplicationTests end RUBY - app('development') + app("development") get "/rails/mailers/notifier/bar" assert last_response.not_found? @@ -330,7 +329,7 @@ module ApplicationTests end test "mailer preview NullMail" do - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -340,7 +339,7 @@ module ApplicationTests end RUBY - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -348,7 +347,7 @@ module ApplicationTests end RUBY - app('development') + app("development") get "/rails/mailers/notifier/foo" assert_match "You are trying to preview an email that does not have any content.", last_response.body @@ -356,7 +355,7 @@ module ApplicationTests end test "mailer preview email part not found" do - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -366,11 +365,11 @@ module ApplicationTests end RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -378,7 +377,7 @@ module ApplicationTests end RUBY - app('development') + app("development") get "/rails/mailers/notifier/foo?part=text%2Fhtml" assert last_response.not_found? @@ -386,7 +385,7 @@ module ApplicationTests end test "message header uses full display names" do - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "Ruby on Rails <core@rubyonrails.org>" @@ -397,11 +396,11 @@ module ApplicationTests end RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -409,7 +408,7 @@ module ApplicationTests end RUBY - app('development') + app("development") get "/rails/mailers/notifier/foo" assert_equal 200, last_response.status @@ -419,7 +418,7 @@ module ApplicationTests end test "part menu selects correct option" do - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -429,15 +428,15 @@ module ApplicationTests end RUBY - html_template 'notifier/foo', <<-RUBY + html_template "notifier/foo", <<-RUBY <p>Hello, World!</p> RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -445,7 +444,7 @@ module ApplicationTests end RUBY - app('development') + app("development") get "/rails/mailers/notifier/foo.html" assert_equal 200, last_response.status @@ -457,7 +456,7 @@ module ApplicationTests end test "mailer previews create correct links when loaded on a subdirectory" do - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -467,11 +466,11 @@ module ApplicationTests end RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -479,9 +478,9 @@ module ApplicationTests end RUBY - app('development') + app("development") - get "/rails/mailers", {}, 'SCRIPT_NAME' => '/my_app' + get "/rails/mailers", {}, "SCRIPT_NAME" => "/my_app" assert_match '<h3><a href="/my_app/rails/mailers/notifier">Notifier</a></h3>', last_response.body assert_match '<li><a href="/my_app/rails/mailers/notifier/foo">foo</a></li>', last_response.body end @@ -489,7 +488,7 @@ module ApplicationTests test "plain text mailer preview with attachment" do image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca/JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo=" - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -500,11 +499,11 @@ module ApplicationTests end RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -512,7 +511,7 @@ module ApplicationTests end RUBY - app('development') + app("development") get "/rails/mailers/notifier/foo" assert_equal 200, last_response.status @@ -526,7 +525,7 @@ module ApplicationTests test "multipart mailer preview with attachment" do image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca/JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo=" - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -537,15 +536,15 @@ module ApplicationTests end RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - html_template 'notifier/foo', <<-RUBY + html_template "notifier/foo", <<-RUBY <p>Hello, World!</p> RUBY - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -553,7 +552,7 @@ module ApplicationTests end RUBY - app('development') + app("development") get "/rails/mailers/notifier/foo" assert_equal 200, last_response.status @@ -571,7 +570,7 @@ module ApplicationTests test "multipart mailer preview with inline attachment" do image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca/JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo=" - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -582,16 +581,16 @@ module ApplicationTests end RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - html_template 'notifier/foo', <<-RUBY + html_template "notifier/foo", <<-RUBY <p>Hello, World!</p> <%= image_tag attachments['pixel.png'].url %> RUBY - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -599,7 +598,7 @@ module ApplicationTests end RUBY - app('development') + app("development") get "/rails/mailers/notifier/foo" assert_equal 200, last_response.status @@ -616,7 +615,7 @@ module ApplicationTests end test "multipart mailer preview with attached email" do - mailer 'notifier', <<-RUBY + mailer "notifier", <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" @@ -641,15 +640,15 @@ module ApplicationTests end RUBY - text_template 'notifier/foo', <<-RUBY + text_template "notifier/foo", <<-RUBY Hello, World! RUBY - html_template 'notifier/foo', <<-RUBY + html_template "notifier/foo", <<-RUBY <p>Hello, World!</p> RUBY - mailer_preview 'notifier', <<-RUBY + mailer_preview "notifier", <<-RUBY class NotifierPreview < ActionMailer::Preview def foo Notifier.foo @@ -657,7 +656,7 @@ module ApplicationTests end RUBY - app('development') + app("development") get "/rails/mailers/notifier/foo" assert_equal 200, last_response.status @@ -695,7 +694,7 @@ module ApplicationTests end def image_file(name, contents) - app_file("public/images/#{name}", Base64.strict_decode64(contents), 'wb') + app_file("public/images/#{name}", Base64.strict_decode64(contents), "wb") end end end diff --git a/railties/test/application/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb index c951dabd6c..cd1371359a 100644 --- a/railties/test/application/middleware/cache_test.rb +++ b/railties/test/application/middleware/cache_test.rb @@ -1,4 +1,4 @@ -require 'isolation/abstract_unit' +require "isolation/abstract_unit" module ApplicationTests class CacheTest < ActiveSupport::TestCase @@ -6,8 +6,7 @@ module ApplicationTests def setup build_app - boot_rails - require 'rack/test' + require "rack/test" extend Rack::Test::Methods end @@ -44,7 +43,7 @@ module ApplicationTests end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get ':controller(/:action)' end @@ -66,12 +65,12 @@ module ApplicationTests app("development") get "/expires/expires_header" - assert_nil last_response.headers['X-Rack-Cache'] + assert_nil last_response.headers["X-Rack-Cache"] body = last_response.body get "/expires/expires_header" - assert_nil last_response.headers['X-Rack-Cache'] + assert_nil last_response.headers["X-Rack-Cache"] assert_not_equal body, last_response.body end @@ -138,7 +137,7 @@ module ApplicationTests body = last_response.body etag = last_response.headers["ETag"] - get "/expires/expires_etag", {private: true}, "If-None-Match" => etag + get "/expires/expires_etag", { private: true }, "If-None-Match" => etag assert_equal "miss", last_response.headers["X-Rack-Cache"] assert_not_equal body, last_response.body end @@ -172,7 +171,7 @@ module ApplicationTests body = last_response.body last = last_response.headers["Last-Modified"] - get "/expires/expires_last_modified", {private: true}, "If-Modified-Since" => last + get "/expires/expires_last_modified", { private: true }, "If-Modified-Since" => last assert_equal "miss", last_response.headers["X-Rack-Cache"] assert_not_equal body, last_response.body end diff --git a/railties/test/application/middleware/cookies_test.rb b/railties/test/application/middleware/cookies_test.rb index bbb7627be9..1e4b5d086c 100644 --- a/railties/test/application/middleware/cookies_test.rb +++ b/railties/test/application/middleware/cookies_test.rb @@ -1,4 +1,4 @@ -require 'isolation/abstract_unit' +require "isolation/abstract_unit" module ApplicationTests class CookiesTest < ActiveSupport::TestCase @@ -10,7 +10,6 @@ module ApplicationTests def setup build_app - boot_rails FileUtils.rm_rf("#{app_path}/config/environments") end @@ -19,27 +18,27 @@ module ApplicationTests FileUtils.rm_rf(new_app) if File.directory?(new_app) end - test 'always_write_cookie is true by default in development' do - require 'rails' - Rails.env = 'development' + test "always_write_cookie is true by default in development" do + require "rails" + Rails.env = "development" require "#{app_path}/config/environment" assert_equal true, ActionDispatch::Cookies::CookieJar.always_write_cookie end - test 'always_write_cookie is false by default in production' do - require 'rails' - Rails.env = 'production' + test "always_write_cookie is false by default in production" do + require "rails" + Rails.env = "production" require "#{app_path}/config/environment" assert_equal false, ActionDispatch::Cookies::CookieJar.always_write_cookie end - test 'always_write_cookie can be overridden' do + test "always_write_cookie can be overridden" do add_to_config <<-RUBY config.action_dispatch.always_write_cookie = false RUBY - require 'rails' - Rails.env = 'development' + require "rails" + Rails.env = "development" require "#{app_path}/config/environment" assert_equal false, ActionDispatch::Cookies::CookieJar.always_write_cookie end diff --git a/railties/test/application/middleware/exceptions_test.rb b/railties/test/application/middleware/exceptions_test.rb index 639b01b562..cbb990f13b 100644 --- a/railties/test/application/middleware/exceptions_test.rb +++ b/railties/test/application/middleware/exceptions_test.rb @@ -1,5 +1,5 @@ -require 'isolation/abstract_unit' -require 'rack/test' +require "isolation/abstract_unit" +require "rack/test" module ApplicationTests class MiddlewareExceptionsTest < ActiveSupport::TestCase @@ -8,7 +8,6 @@ module ApplicationTests def setup build_app - boot_rails end def teardown @@ -70,7 +69,7 @@ module ApplicationTests app.config.action_dispatch.show_exceptions = true - get '/foo' + get "/foo" assert_equal 500, last_response.status end @@ -78,7 +77,7 @@ module ApplicationTests app.config.action_dispatch.show_exceptions = false assert_raise(ActionController::RoutingError) do - get '/foo' + get "/foo" end end @@ -86,7 +85,7 @@ module ApplicationTests app.config.action_dispatch.show_exceptions = true assert_nothing_raised do - get '/foo' + get "/foo" assert_match "The page you were looking for doesn't exist.", last_response.body end end @@ -96,7 +95,7 @@ module ApplicationTests app.config.consider_all_requests_local = true assert_nothing_raised do - get '/foo' + get "/foo" assert_match "No route matches", last_response.body end end @@ -112,12 +111,12 @@ module ApplicationTests app.config.action_dispatch.show_exceptions = true app.config.consider_all_requests_local = true - app_file 'app/views/foo/index.html.erb', <<-ERB + app_file "app/views/foo/index.html.erb", <<-ERB <% raise 'boooom' %> ✓測試テスト시험 ERB - get '/foo', :utf8 => '✓' + get "/foo", utf8: "✓" assert_match(/boooom/, last_response.body) assert_match(/測試テスト시험/, last_response.body) end diff --git a/railties/test/application/middleware/remote_ip_test.rb b/railties/test/application/middleware/remote_ip_test.rb index 37bd8a25c1..c34d9d6ee7 100644 --- a/railties/test/application/middleware/remote_ip_test.rb +++ b/railties/test/application/middleware/remote_ip_test.rb @@ -1,6 +1,6 @@ -require 'ipaddr' -require 'isolation/abstract_unit' -require 'active_support/key_generator' +require "ipaddr" +require "isolation/abstract_unit" +require "active_support/key_generator" module ApplicationTests class RemoteIpTest < ActiveSupport::TestCase @@ -9,8 +9,8 @@ module ApplicationTests def remote_ip(env = {}) remote_ip = nil env = Rack::MockRequest.env_for("/").merge(env).merge!( - 'action_dispatch.show_exceptions' => false, - 'action_dispatch.key_generator' => ActiveSupport::LegacyKeyGenerator.new('b3c631c314c0bbca50c1b2843150fe33') + "action_dispatch.show_exceptions" => false, + "action_dispatch.key_generator" => ActiveSupport::LegacyKeyGenerator.new("b3c631c314c0bbca50c1b2843150fe33") ) endpoint = Proc.new do |e| @@ -69,7 +69,7 @@ module ApplicationTests 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') + 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") diff --git a/railties/test/application/middleware/sendfile_test.rb b/railties/test/application/middleware/sendfile_test.rb index be86f1a3b8..4938402fdc 100644 --- a/railties/test/application/middleware/sendfile_test.rb +++ b/railties/test/application/middleware/sendfile_test.rb @@ -1,4 +1,4 @@ -require 'isolation/abstract_unit' +require "isolation/abstract_unit" module ApplicationTests class SendfileTest < ActiveSupport::TestCase @@ -6,7 +6,6 @@ module ApplicationTests def setup build_app - boot_rails FileUtils.rm_rf "#{app_path}/config/environments" end @@ -49,7 +48,7 @@ module ApplicationTests test "config.action_dispatch.x_sendfile_header is sent to Rack::Sendfile" do make_basic_app do |app| - app.config.action_dispatch.x_sendfile_header = 'X-Lighttpd-Send-File' + app.config.action_dispatch.x_sendfile_header = "X-Lighttpd-Send-File" end simple_controller @@ -60,7 +59,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.action_dispatch.x_sendfile_header = "X-Sendfile" app.config.public_file_server.enabled = 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 85e7761727..a6019a9db4 100644 --- a/railties/test/application/middleware/session_test.rb +++ b/railties/test/application/middleware/session_test.rb @@ -1,5 +1,5 @@ -require 'isolation/abstract_unit' -require 'rack/test' +require "isolation/abstract_unit" +require "rack/test" module ApplicationTests class MiddlewareSessionTest < ActiveSupport::TestCase @@ -8,7 +8,6 @@ module ApplicationTests def setup build_app - boot_rails FileUtils.rm_rf "#{app_path}/config/environments" end @@ -54,7 +53,7 @@ module ApplicationTests end test "session is empty and isn't saved on unverified request when using :null_session protect method" do - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get ':controller(/:action)' post ':controller(/:action)' @@ -82,20 +81,20 @@ module ApplicationTests require "#{app_path}/config/environment" - get '/foo/write_session' - get '/foo/read_session' - assert_equal '1', last_response.body + get "/foo/write_session" + get "/foo/read_session" + assert_equal "1", last_response.body - post '/foo/read_session' # Read session using POST request without CSRF token - assert_equal 'nil', last_response.body # Stored value shouldn't be accessible + post "/foo/read_session" # Read session using POST request without CSRF token + assert_equal "nil", last_response.body # Stored value shouldn't be accessible - post '/foo/write_session' # Write session using POST request without CSRF token - get '/foo/read_session' # Session shouldn't be changed - assert_equal '1', last_response.body + post "/foo/write_session" # Write session using POST request without CSRF token + get "/foo/read_session" # Session shouldn't be changed + assert_equal "1", last_response.body end test "cookie jar is empty and isn't saved on unverified request when using :null_session protect method" do - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get ':controller(/:action)' post ':controller(/:action)' @@ -123,20 +122,20 @@ module ApplicationTests require "#{app_path}/config/environment" - get '/foo/write_cookie' - get '/foo/read_cookie' + get "/foo/write_cookie" + get "/foo/read_cookie" assert_equal '"1"', last_response.body - post '/foo/read_cookie' # Read cookie using POST request without CSRF token - assert_equal 'nil', last_response.body # Stored value shouldn't be accessible + post "/foo/read_cookie" # Read cookie using POST request without CSRF token + assert_equal "nil", last_response.body # Stored value shouldn't be accessible - post '/foo/write_cookie' # Write cookie using POST request without CSRF token - get '/foo/read_cookie' # Cookie shouldn't be changed + post "/foo/write_cookie" # Write cookie using POST request without CSRF token + get "/foo/read_cookie" # Cookie shouldn't be changed assert_equal '"1"', last_response.body end test "session using encrypted cookie store" do - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get ':controller(/:action)' end @@ -165,23 +164,23 @@ module ApplicationTests require "#{app_path}/config/environment" - get '/foo/write_session' - get '/foo/read_session' - assert_equal '1', last_response.body + get "/foo/write_session" + get "/foo/read_session" + assert_equal "1", last_response.body - get '/foo/read_encrypted_cookie' - assert_equal '1', last_response.body + get "/foo/read_encrypted_cookie" + assert_equal "1", last_response.body - secret = app.key_generator.generate_key('encrypted cookie') - sign_secret = app.key_generator.generate_key('signed encrypted cookie') + secret = app.key_generator.generate_key("encrypted cookie") + sign_secret = app.key_generator.generate_key("signed encrypted cookie") encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret) - get '/foo/read_raw_cookie' - assert_equal 1, encryptor.decrypt_and_verify(last_response.body)['foo'] + get "/foo/read_raw_cookie" + assert_equal 1, encryptor.decrypt_and_verify(last_response.body)["foo"] end test "session upgrading signature to encryption cookie store works the same way as encrypted cookie store" do - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get ':controller(/:action)' end @@ -214,23 +213,23 @@ module ApplicationTests require "#{app_path}/config/environment" - get '/foo/write_session' - get '/foo/read_session' - assert_equal '1', last_response.body + get "/foo/write_session" + get "/foo/read_session" + assert_equal "1", last_response.body - get '/foo/read_encrypted_cookie' - assert_equal '1', last_response.body + get "/foo/read_encrypted_cookie" + assert_equal "1", last_response.body - secret = app.key_generator.generate_key('encrypted cookie') - sign_secret = app.key_generator.generate_key('signed encrypted cookie') + secret = app.key_generator.generate_key("encrypted cookie") + sign_secret = app.key_generator.generate_key("signed encrypted cookie") encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret) - get '/foo/read_raw_cookie' - assert_equal 1, encryptor.decrypt_and_verify(last_response.body)['foo'] + get "/foo/read_raw_cookie" + assert_equal 1, encryptor.decrypt_and_verify(last_response.body)["foo"] end test "session upgrading signature to encryption cookie store upgrades session to encrypted mode" do - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get ':controller(/:action)' end @@ -269,27 +268,27 @@ module ApplicationTests require "#{app_path}/config/environment" - get '/foo/write_raw_session' - get '/foo/read_session' - assert_equal '1', last_response.body + get "/foo/write_raw_session" + get "/foo/read_session" + assert_equal "1", last_response.body - get '/foo/write_session' - get '/foo/read_session' - assert_equal '2', last_response.body + get "/foo/write_session" + get "/foo/read_session" + assert_equal "2", last_response.body - get '/foo/read_encrypted_cookie' - assert_equal '2', last_response.body + get "/foo/read_encrypted_cookie" + assert_equal "2", last_response.body - secret = app.key_generator.generate_key('encrypted cookie') - sign_secret = app.key_generator.generate_key('signed encrypted cookie') + secret = app.key_generator.generate_key("encrypted cookie") + sign_secret = app.key_generator.generate_key("signed encrypted cookie") encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret) - get '/foo/read_raw_cookie' - assert_equal 2, encryptor.decrypt_and_verify(last_response.body)['foo'] + get "/foo/read_raw_cookie" + assert_equal 2, encryptor.decrypt_and_verify(last_response.body)["foo"] end test "session upgrading legacy signed cookies to new signed cookies" do - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get ':controller(/:action)' end @@ -329,25 +328,25 @@ module ApplicationTests require "#{app_path}/config/environment" - get '/foo/write_raw_session' - get '/foo/read_session' - assert_equal '1', last_response.body + get "/foo/write_raw_session" + get "/foo/read_session" + assert_equal "1", last_response.body - get '/foo/write_session' - get '/foo/read_session' - assert_equal '2', last_response.body + get "/foo/write_session" + get "/foo/read_session" + assert_equal "2", last_response.body - get '/foo/read_signed_cookie' - assert_equal '2', last_response.body + get "/foo/read_signed_cookie" + assert_equal "2", last_response.body verifier = ActiveSupport::MessageVerifier.new(app.secrets.secret_token) - get '/foo/read_raw_cookie' - assert_equal 2, verifier.verify(last_response.body)['foo'] + get "/foo/read_raw_cookie" + assert_equal 2, verifier.verify(last_response.body)["foo"] end - test 'calling reset_session on request does not trigger an error for API apps' do - add_to_config 'config.api_only = true' + test "calling reset_session on request does not trigger an error for API apps" do + add_to_config "config.api_only = true" controller :test, <<-RUBY class TestController < ApplicationController @@ -358,7 +357,7 @@ module ApplicationTests end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get '/dump_flash' => "test#dump_flash" end @@ -366,12 +365,18 @@ module ApplicationTests require "#{app_path}/config/environment" - get '/dump_flash' + get "/dump_flash" assert_equal 200, last_response.status - assert_equal 'It worked!', last_response.body + assert_equal "It worked!", last_response.body - refute Rails.application.middleware.include?(ActionDispatch::Flash) + assert_not_includes Rails.application.middleware, ActionDispatch::Flash + end + + test "cookie_only is set to true even if user tries to overwrite it" do + add_to_config "config.session_store :cookie_store, key: '_myapp_session', cookie_only: false" + require "#{app_path}/config/environment" + assert app.config.session_options[:cookie_only], "Expected cookie_only to be set to true" end end end diff --git a/railties/test/application/middleware/static_test.rb b/railties/test/application/middleware/static_test.rb index 1246e20d94..5cd3e4325e 100644 --- a/railties/test/application/middleware/static_test.rb +++ b/railties/test/application/middleware/static_test.rb @@ -1,5 +1,5 @@ -require 'isolation/abstract_unit' -require 'rack/test' +require "isolation/abstract_unit" +require "rack/test" module ApplicationTests class MiddlewareStaticTest < ActiveSupport::TestCase @@ -18,17 +18,17 @@ module ApplicationTests # Regression test to #8907 # See https://github.com/rails/rails/commit/9cc82b77196d21a5c7021f6dca59ab9b2b158a45#commitcomment-2416514 test "doesn't set Cache-Control header when it is nil" do - app_file "public/foo.html", 'static' + app_file "public/foo.html", "static" require "#{app_path}/config/environment" - get 'foo' + get "foo" - assert_not last_response.headers.has_key?('Cache-Control'), "Cache-Control should not be set" + assert_not last_response.headers.has_key?("Cache-Control"), "Cache-Control should not be set" end test "headers for static files are configurable" do - app_file "public/about.html", 'static' + app_file "public/about.html", "static" add_to_config <<-CONFIG config.public_file_server.headers = { "Access-Control-Allow-Origin" => "http://rubyonrails.org", @@ -38,19 +38,19 @@ module ApplicationTests require "#{app_path}/config/environment" - get '/about.html' + get "/about.html" - assert_equal 'http://rubyonrails.org', last_response.headers["Access-Control-Allow-Origin"] - assert_equal 'public, max-age=60', last_response.headers["Cache-Control"] + assert_equal "http://rubyonrails.org", last_response.headers["Access-Control-Allow-Origin"] + assert_equal "public, max-age=60", last_response.headers["Cache-Control"] end test "public_file_server.index_name defaults to 'index'" do app_file "public/index.html", "/index.html" - + require "#{app_path}/config/environment" - get '/' - + get "/" + assert_equal "/index.html\n", last_response.body end @@ -60,7 +60,7 @@ module ApplicationTests require "#{app_path}/config/environment" - get '/' + get "/" assert_equal "/other-index.html\n", last_response.body end diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb index 5869ff64bc..45481dc1b6 100644 --- a/railties/test/application/middleware_test.rb +++ b/railties/test/application/middleware_test.rb @@ -1,4 +1,4 @@ -require 'isolation/abstract_unit' +require "isolation/abstract_unit" module ApplicationTests class MiddlewareTest < ActiveSupport::TestCase @@ -6,7 +6,6 @@ module ApplicationTests def setup build_app - boot_rails FileUtils.rm_rf "#{app_path}/config/environments" end @@ -74,7 +73,7 @@ module ApplicationTests test "Rack::Cache is not included by default" do boot! - assert !middleware.include?("Rack::Cache"), "Rack::Cache is not included in the default stack unless you set config.action_dispatch.rack_cache" + assert_not_includes middleware, "Rack::Cache", "Rack::Cache is not included in the default stack unless you set config.action_dispatch.rack_cache" end test "Rack::Cache is present when action_dispatch.rack_cache is set" do @@ -82,7 +81,7 @@ module ApplicationTests boot! - assert middleware.include?("Rack::Cache") + assert_includes middleware, "Rack::Cache" end test "ActiveRecord::Migration::CheckPending is present when active_record.migration_error is set to :page_load" do @@ -90,13 +89,13 @@ module ApplicationTests boot! - assert middleware.include?("ActiveRecord::Migration::CheckPending") + assert_includes middleware, "ActiveRecord::Migration::CheckPending" end test "ActionDispatch::SSL is present when force_ssl is set" do add_to_config "config.force_ssl = true" boot! - assert middleware.include?("ActionDispatch::SSL") + assert_includes middleware, "ActionDispatch::SSL" end test "ActionDispatch::SSL is configured with options when given" do @@ -104,13 +103,13 @@ module ApplicationTests add_to_config "config.ssl_options = { host: 'example.com' }" boot! - assert_equal [{host: 'example.com'}], Rails.application.middleware.first.args + assert_equal [{ host: "example.com" }], Rails.application.middleware.first.args end test "removing Active Record omits its middleware" do use_frameworks [] boot! - assert !middleware.include?("ActiveRecord::Migration::CheckPending") + assert_not_includes middleware, "ActiveRecord::Migration::CheckPending" end test "includes executor" do @@ -140,20 +139,20 @@ module ApplicationTests test "removes static asset server if public_file_server.enabled is disabled" do add_to_config "config.public_file_server.enabled = false" boot! - assert !middleware.include?("ActionDispatch::Static") + assert_not_includes middleware, "ActionDispatch::Static" end test "can delete a middleware from the stack" do add_to_config "config.middleware.delete ActionDispatch::Static" boot! - assert !middleware.include?("ActionDispatch::Static") + assert_not_includes middleware, "ActionDispatch::Static" end test "can delete a middleware from the stack even if insert_before is added after delete" do add_to_config "config.middleware.delete Rack::Runtime" add_to_config "config.middleware.insert_before(Rack::Runtime, Rack::Config)" boot! - assert middleware.include?("Rack::Config") + assert_includes middleware, "Rack::Config" assert_not middleware.include?("Rack::Runtime") end @@ -161,21 +160,21 @@ module ApplicationTests add_to_config "config.middleware.delete Rack::Runtime" add_to_config "config.middleware.insert_after(Rack::Runtime, Rack::Config)" boot! - assert middleware.include?("Rack::Config") + assert_includes middleware, "Rack::Config" assert_not middleware.include?("Rack::Runtime") end test "includes exceptions middlewares even if action_dispatch.show_exceptions is disabled" do add_to_config "config.action_dispatch.show_exceptions = false" boot! - assert middleware.include?("ActionDispatch::ShowExceptions") - assert middleware.include?("ActionDispatch::DebugExceptions") + assert_includes middleware, "ActionDispatch::ShowExceptions" + assert_includes middleware, "ActionDispatch::DebugExceptions" end test "removes ActionDispatch::Reloader if cache_classes is true" do add_to_config "config.cache_classes = true" boot! - assert !middleware.include?("ActionDispatch::Reloader") + assert_not_includes middleware, "ActionDispatch::Reloader" end test "use middleware" do @@ -191,10 +190,10 @@ module ApplicationTests assert_equal "Rack::Config", middleware.second end - test 'unshift middleware' do - add_to_config 'config.middleware.unshift Rack::Config' + test "unshift middleware" do + add_to_config "config.middleware.unshift Rack::Config" boot! - assert_equal 'Rack::Config', middleware.first + assert_equal "Rack::Config", middleware.first end test "Rails.cache does not respond to middleware" do @@ -235,7 +234,7 @@ module ApplicationTests end end - etag = "W/" + "5af83e3196bf99f440f31f2e1a6c9afe".inspect + etag = "W/" + "c00862d1c6c1cf7c1b49388306e7b3c1".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 f2770a9cb4..26b810af73 100644 --- a/railties/test/application/multiple_applications_test.rb +++ b/railties/test/application/multiple_applications_test.rb @@ -1,4 +1,4 @@ -require 'isolation/abstract_unit' +require "isolation/abstract_unit" module ApplicationTests class MultipleApplicationsTest < ActiveSupport::TestCase @@ -6,9 +6,8 @@ module ApplicationTests def setup build_app(initializers: true) - boot_rails require "#{rails_root}/config/environment" - Rails.application.config.some_setting = 'something_or_other' + Rails.application.config.some_setting = "something_or_other" end def teardown @@ -88,9 +87,9 @@ module ApplicationTests require "#{app_path}/config/environment" 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' + 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" end diff --git a/railties/test/application/paths_test.rb b/railties/test/application/paths_test.rb index 4029984ce9..515205296c 100644 --- a/railties/test/application/paths_test.rb +++ b/railties/test/application/paths_test.rb @@ -6,7 +6,6 @@ module ApplicationTests def setup build_app - boot_rails FileUtils.rm_rf("#{app_path}/config/environments") app_file "config/environments/development.rb", "" add_to_config <<-RUBY @@ -56,9 +55,9 @@ module ApplicationTests test "booting up Rails yields a list of paths that are eager" do eager_load = @paths.eager_load - assert eager_load.include?(root("app/controllers")) - assert eager_load.include?(root("app/helpers")) - assert eager_load.include?(root("app/models")) + assert_includes eager_load, root("app/controllers") + assert_includes eager_load, root("app/helpers") + assert_includes eager_load, root("app/models") end test "environments has a glob equal to the current environment" do diff --git a/railties/test/application/per_request_digest_cache_test.rb b/railties/test/application/per_request_digest_cache_test.rb index dfe3fc9354..6c003e9bcc 100644 --- a/railties/test/application/per_request_digest_cache_test.rb +++ b/railties/test/application/per_request_digest_cache_test.rb @@ -1,9 +1,9 @@ -require 'isolation/abstract_unit' -require 'rack/test' -require 'minitest/mock' +require "isolation/abstract_unit" +require "rack/test" +require "minitest/mock" -require 'action_view' -require 'active_support/testing/method_call_assertions' +require "action_view" +require "active_support/testing/method_call_assertions" class PerRequestDigestCacheTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation @@ -12,22 +12,22 @@ class PerRequestDigestCacheTest < ActiveSupport::TestCase setup do build_app - add_to_config 'config.consider_all_requests_local = true' + add_to_config "config.consider_all_requests_local = true" - app_file 'app/models/customer.rb', <<-RUBY + app_file "app/models/customer.rb", <<-RUBY class Customer < Struct.new(:name, :id) extend ActiveModel::Naming include ActiveModel::Conversion end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do resources :customers, only: :index end RUBY - app_file 'app/controllers/customers_controller.rb', <<-RUBY + app_file "app/controllers/customers_controller.rb", <<-RUBY class CustomersController < ApplicationController self.perform_caching = true @@ -37,7 +37,7 @@ class PerRequestDigestCacheTest < ActiveSupport::TestCase end RUBY - app_file 'app/views/customers/_customer.html.erb', <<-RUBY + app_file "app/views/customers/_customer.html.erb", <<-RUBY <% cache customer do %> <%= customer.name %> <% end %> @@ -49,17 +49,17 @@ class PerRequestDigestCacheTest < ActiveSupport::TestCase teardown :teardown_app test "digests are reused when rendering the same template twice" do - get '/customers' + get "/customers" assert_equal 200, last_response.status values = ActionView::LookupContext::DetailsKey.digest_caches.first.values - assert_equal [ '8ba099b7749542fe765ff34a6824d548' ], values + assert_equal [ "8ba099b7749542fe765ff34a6824d548" ], values assert_equal %w(david dingus), last_response.body.split.map(&:strip) end test "template digests are cleared before a request" do assert_called(ActionView::LookupContext::DetailsKey, :clear) do - get '/customers' + get "/customers" assert_equal 200, last_response.status end end diff --git a/railties/test/application/rack/logger_test.rb b/railties/test/application/rack/logger_test.rb index 0082ec9cd2..e71bcbc536 100644 --- a/railties/test/application/rack/logger_test.rb +++ b/railties/test/application/rack/logger_test.rb @@ -41,13 +41,13 @@ module ApplicationTests end test "logger logs HTTP verb override" do - post "/", _method: 'put' + post "/", _method: "put" wait assert_match 'Started PUT "/"', logs end test "logger logs HEAD requests" do - post "/", _method: 'head' + post "/", _method: "head" wait assert_match 'Started HEAD "/"', logs end diff --git a/railties/test/application/rackup_test.rb b/railties/test/application/rackup_test.rb index 49ac9fc66c..2943e9ee5d 100644 --- a/railties/test/application/rackup_test.rb +++ b/railties/test/application/rackup_test.rb @@ -12,14 +12,13 @@ module ApplicationTests def setup build_app - boot_rails end def teardown teardown_app end - test "rails app is present" do + test "Rails app is present" do assert File.exist?(app_path("config")) end @@ -37,7 +36,7 @@ module ApplicationTests test "the config object is available on the application object" do rackup - assert_equal 'UTC', Rails.application.config.time_zone + assert_equal "UTC", Rails.application.config.time_zone end end end diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb index cee9db5535..51db634b75 100644 --- a/railties/test/application/rake/dbs_test.rb +++ b/railties/test/application/rake/dbs_test.rb @@ -8,7 +8,6 @@ module ApplicationTests def setup build_app - boot_rails FileUtils.rm_rf("#{app_path}/config/environments") end @@ -21,7 +20,7 @@ module ApplicationTests end def set_database_url - ENV['DATABASE_URL'] = "sqlite3:#{database_url_db_name}" + ENV["DATABASE_URL"] = "sqlite3:#{database_url_db_name}" # ensure it's using the DATABASE_URL FileUtils.rm_rf("#{app_path}/config/database.yml") end @@ -38,12 +37,12 @@ module ApplicationTests end end - test 'db:create and db:drop without database url' do + test "db:create and db:drop without database url" do require "#{app_path}/config/environment" - db_create_and_drop ActiveRecord::Base.configurations[Rails.env]['database'] + db_create_and_drop ActiveRecord::Base.configurations[Rails.env]["database"] end - test 'db:create and db:drop with database url' do + test "db:create and db:drop with database url" do require "#{app_path}/config/environment" set_database_url db_create_and_drop database_url_db_name @@ -58,7 +57,7 @@ module ApplicationTests end end - test 'db:create failure because database exists' do + test "db:create failure because database exists" do with_database_existing do output = `bin/rails db:create 2>&1` assert_match(/already exists/, output) @@ -75,7 +74,7 @@ module ApplicationTests end end - test 'db:create failure because bad permissions' do + test "db:create failure because bad permissions" do with_bad_permissions do output = `bin/rails db:create 2>&1` assert_match(/Couldn't create database/, output) @@ -83,7 +82,7 @@ module ApplicationTests end end - test 'db:drop failure because database does not exist' do + test "db:drop failure because database does not exist" do Dir.chdir(app_path) do output = `bin/rails db:drop:_unsafe --trace 2>&1` assert_match(/does not exist/, output) @@ -91,7 +90,7 @@ module ApplicationTests end end - test 'db:drop failure because bad permissions' do + test "db:drop failure because bad permissions" do with_database_existing do with_bad_permissions do output = `bin/rails db:drop 2>&1` @@ -111,12 +110,12 @@ module ApplicationTests end end - test 'db:migrate and db:migrate:status without database_url' do + test "db:migrate and db:migrate:status without database_url" do require "#{app_path}/config/environment" - db_migrate_and_status ActiveRecord::Base.configurations[Rails.env]['database'] + db_migrate_and_status ActiveRecord::Base.configurations[Rails.env]["database"] end - test 'db:migrate and db:migrate:status with database_url' do + test "db:migrate and db:migrate:status with database_url" do require "#{app_path}/config/environment" set_database_url db_migrate_and_status database_url_db_name @@ -131,11 +130,11 @@ module ApplicationTests end end - test 'db:schema:dump without database_url' do + test "db:schema:dump without database_url" do db_schema_dump end - test 'db:schema:dump with database_url' do + test "db:schema:dump with database_url" do set_database_url db_schema_dump end @@ -150,18 +149,18 @@ module ApplicationTests end end - test 'db:fixtures:load without database_url' do + test "db:fixtures:load without database_url" do require "#{app_path}/config/environment" - db_fixtures_load ActiveRecord::Base.configurations[Rails.env]['database'] + db_fixtures_load ActiveRecord::Base.configurations[Rails.env]["database"] end - test 'db:fixtures:load with database_url' do + test "db:fixtures:load with database_url" do require "#{app_path}/config/environment" set_database_url db_fixtures_load database_url_db_name end - test 'db:fixtures:load with namespaced fixture' do + test "db:fixtures:load with namespaced fixture" do require "#{app_path}/config/environment" Dir.chdir(app_path) do `bin/rails generate model admin::book title:string; @@ -185,18 +184,18 @@ module ApplicationTests end end - test 'db:structure:dump and db:structure:load without database_url' do + test "db:structure:dump and db:structure:load without database_url" do require "#{app_path}/config/environment" - db_structure_dump_and_load ActiveRecord::Base.configurations[Rails.env]['database'] + db_structure_dump_and_load ActiveRecord::Base.configurations[Rails.env]["database"] end - test 'db:structure:dump and db:structure:load with database_url' do + test "db:structure:dump and db:structure:load with database_url" do require "#{app_path}/config/environment" set_database_url db_structure_dump_and_load database_url_db_name end - test 'db:structure:dump does not dump schema information when no migrations are used' do + test "db:structure:dump does not dump schema information when no migrations are used" do Dir.chdir(app_path) do # create table without migrations `bin/rails runner 'ActiveRecord::Base.connection.create_table(:posts) {|t| t.string :title }'` @@ -208,11 +207,11 @@ module ApplicationTests end end - test 'db:schema:load and db:structure:load do not purge the existing database' do + 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 + app_file "db/schema.rb", <<-RUBY ActiveRecord::Schema.define(version: 20140423102712) do create_table(:comments) {} end @@ -224,7 +223,7 @@ module ApplicationTests `bin/rails db:schema:load` assert_equal '["posts", "comments", "schema_migrations", "ar_internal_metadata"]', list_tables[] - app_file 'db/structure.sql', <<-SQL + app_file "db/structure.sql", <<-SQL CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255)); SQL @@ -235,15 +234,15 @@ module ApplicationTests test "db:schema:load with inflections" do Dir.chdir(app_path) do - app_file 'config/initializers/inflection.rb', <<-RUBY + app_file "config/initializers/inflection.rb", <<-RUBY ActiveSupport::Inflector.inflections do |inflect| inflect.irregular 'goose', 'geese' end RUBY - app_file 'config/initializers/primary_key_table_name.rb', <<-RUBY + app_file "config/initializers/primary_key_table_name.rb", <<-RUBY ActiveRecord::Base.primary_key_prefix_type = :table_name RUBY - app_file 'db/schema.rb', <<-RUBY + app_file "db/schema.rb", <<-RUBY ActiveRecord::Schema.define(version: 20140423102712) do create_table("goose".pluralize) do |t| t.string :name @@ -270,24 +269,24 @@ module ApplicationTests require "#{app_path}/app/models/book" #if structure is not loaded correctly, exception would be raised assert_equal 0, Book.count - assert_match ActiveRecord::Base.configurations['test']['database'], + assert_match ActiveRecord::Base.configurations["test"]["database"], ActiveRecord::Base.connection_config[:database] end end - test 'db:test:load_structure without database_url' do + test "db:test:load_structure without database_url" do require "#{app_path}/config/environment" db_test_load_structure end - test 'db:setup loads schema and seeds database' do + 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 + app_file "db/schema.rb", <<-RUBY ActiveRecord::Schema.define(version: "1") do create_table :users do |t| t.string :name @@ -295,7 +294,7 @@ module ApplicationTests end RUBY - app_file 'db/seeds.rb', <<-RUBY + app_file "db/seeds.rb", <<-RUBY puts ActiveRecord::Base.connection_config[:database] RUBY diff --git a/railties/test/application/rake/dev_test.rb b/railties/test/application/rake/dev_test.rb index 2330ad3535..4f992d9c8d 100644 --- a/railties/test/application/rake/dev_test.rb +++ b/railties/test/application/rake/dev_test.rb @@ -1,4 +1,4 @@ -require 'isolation/abstract_unit' +require "isolation/abstract_unit" module ApplicationTests module RakeTests @@ -13,24 +13,24 @@ module ApplicationTests teardown_app end - test 'dev:cache creates file and outputs message' do + test "dev:cache creates file and outputs message" do Dir.chdir(app_path) do output = `rails dev:cache` - assert File.exist?('tmp/caching-dev.txt') + assert File.exist?("tmp/caching-dev.txt") assert_match(/Development mode is now being cached/, output) end end - test 'dev:cache deletes file and outputs message' do + test "dev:cache deletes file and outputs message" do Dir.chdir(app_path) do `rails dev:cache` # Create caching file. output = `rails dev:cache` # Delete caching file. - assert_not File.exist?('tmp/caching-dev.txt') + assert_not File.exist?("tmp/caching-dev.txt") assert_match(/Development mode is no longer being cached/, output) end end - test 'dev:cache removes server.pid also' do + test "dev:cache removes server.pid also" do Dir.chdir(app_path) do FileUtils.mkdir_p("tmp/pids") FileUtils.touch("tmp/pids/server.pid") diff --git a/railties/test/application/rake/framework_test.rb b/railties/test/application/rake/framework_test.rb index ec57af79f6..7ac37b7700 100644 --- a/railties/test/application/rake/framework_test.rb +++ b/railties/test/application/rake/framework_test.rb @@ -8,7 +8,6 @@ module ApplicationTests def setup build_app - boot_rails FileUtils.rm_rf("#{app_path}/config/environments") end @@ -17,14 +16,14 @@ module ApplicationTests end def load_tasks - require 'rake' - require 'rdoc/task' - require 'rake/testtask' + require "rake" + require "rdoc/task" + require "rake/testtask" Rails.application.load_tasks end - test 'requiring the rake task should not define method .app_generator on Object' do + test "requiring the rake task should not define method .app_generator on Object" do require "#{app_path}/config/environment" load_tasks @@ -34,7 +33,7 @@ module ApplicationTests end end - test 'requiring the rake task should not define method .invoke_from_app_generator on Object' do + test "requiring the rake task should not define method .invoke_from_app_generator on Object" do require "#{app_path}/config/environment" load_tasks diff --git a/railties/test/application/rake/migrations_test.rb b/railties/test/application/rake/migrations_test.rb index 7e2519ae5a..76cb302c62 100644 --- a/railties/test/application/rake/migrations_test.rb +++ b/railties/test/application/rake/migrations_test.rb @@ -5,7 +5,6 @@ module ApplicationTests class RakeMigrationsTest < ActiveSupport::TestCase def setup build_app - boot_rails FileUtils.rm_rf("#{app_path}/config/environments") end @@ -13,7 +12,7 @@ module ApplicationTests teardown_app end - test 'running migrations with given scope' do + test "running migrations with given scope" do Dir.chdir(app_path) do `bin/rails generate model user username:string password:string` @@ -38,31 +37,31 @@ module ApplicationTests end end - test 'model and migration generator with change syntax' do + test "model and migration generator with change syntax" do Dir.chdir(app_path) do `bin/rails generate model user username:string password:string; bin/rails generate migration add_email_to_users email:string` - output = `bin/rails db:migrate` - assert_match(/create_table\(:users\)/, output) - assert_match(/CreateUsers: migrated/, output) - assert_match(/add_column\(:users, :email, :string\)/, output) - assert_match(/AddEmailToUsers: migrated/, output) - - output = `bin/rails db:rollback STEP=2` - assert_match(/drop_table\(:users\)/, output) - assert_match(/CreateUsers: reverted/, output) - assert_match(/remove_column\(:users, :email, :string\)/, output) - assert_match(/AddEmailToUsers: reverted/, output) + output = `bin/rails db:migrate` + assert_match(/create_table\(:users\)/, output) + assert_match(/CreateUsers: migrated/, output) + assert_match(/add_column\(:users, :email, :string\)/, output) + assert_match(/AddEmailToUsers: migrated/, output) + + output = `bin/rails db:rollback STEP=2` + assert_match(/drop_table\(:users\)/, output) + assert_match(/CreateUsers: reverted/, output) + assert_match(/remove_column\(:users, :email, :string\)/, output) + assert_match(/AddEmailToUsers: reverted/, output) end end - test 'migration status when schema migrations table is not present' do - output = Dir.chdir(app_path){ `bin/rails db:migrate:status 2>&1` } + test "migration status when schema migrations table is not present" do + output = Dir.chdir(app_path) { `bin/rails db:migrate:status 2>&1` } assert_equal "Schema migrations table does not exist yet.\n", output end - test 'test migration status' do + test "test migration status" do Dir.chdir(app_path) do `bin/rails generate model user username:string password:string; bin/rails generate migration add_email_to_users email:string; @@ -81,8 +80,8 @@ module ApplicationTests end end - test 'migration status without timestamps' do - add_to_config('config.active_record.timestamped_migrations = false') + test "migration status without timestamps" do + add_to_config("config.active_record.timestamped_migrations = false") Dir.chdir(app_path) do `bin/rails generate model user username:string password:string; @@ -102,59 +101,59 @@ module ApplicationTests end end - test 'test migration status after rollback and redo' do + test "test migration status after rollback and redo" do Dir.chdir(app_path) do `bin/rails generate model user username:string password:string; bin/rails generate migration add_email_to_users email:string; bin/rails db:migrate` - output = `bin/rails db:migrate:status` + output = `bin/rails db:migrate:status` - assert_match(/up\s+\d{14}\s+Create users/, output) - assert_match(/up\s+\d{14}\s+Add email to users/, output) + assert_match(/up\s+\d{14}\s+Create users/, output) + assert_match(/up\s+\d{14}\s+Add email to users/, output) - `bin/rails db:rollback STEP=2` - output = `bin/rails db:migrate:status` + `bin/rails db:rollback STEP=2` + output = `bin/rails db:migrate:status` - assert_match(/down\s+\d{14}\s+Create users/, output) - assert_match(/down\s+\d{14}\s+Add email to users/, output) + assert_match(/down\s+\d{14}\s+Create users/, output) + assert_match(/down\s+\d{14}\s+Add email to users/, output) - `bin/rails db:migrate:redo` - output = `bin/rails db:migrate:status` + `bin/rails db:migrate:redo` + output = `bin/rails db:migrate:status` - assert_match(/up\s+\d{14}\s+Create users/, output) - assert_match(/up\s+\d{14}\s+Add email to users/, output) + assert_match(/up\s+\d{14}\s+Create users/, output) + assert_match(/up\s+\d{14}\s+Add email to users/, output) end end - test 'migration status after rollback and redo without timestamps' do - add_to_config('config.active_record.timestamped_migrations = false') + test "migration status after rollback and redo without timestamps" do + add_to_config("config.active_record.timestamped_migrations = false") Dir.chdir(app_path) do `bin/rails generate model user username:string password:string; bin/rails generate migration add_email_to_users email:string; bin/rails db:migrate` - output = `bin/rails db:migrate:status` + output = `bin/rails db:migrate:status` - assert_match(/up\s+\d{3,}\s+Create users/, output) - assert_match(/up\s+\d{3,}\s+Add email to users/, output) + assert_match(/up\s+\d{3,}\s+Create users/, output) + assert_match(/up\s+\d{3,}\s+Add email to users/, output) - `bin/rails db:rollback STEP=2` - output = `bin/rails db:migrate:status` + `bin/rails db:rollback STEP=2` + output = `bin/rails db:migrate:status` - assert_match(/down\s+\d{3,}\s+Create users/, output) - assert_match(/down\s+\d{3,}\s+Add email to users/, output) + assert_match(/down\s+\d{3,}\s+Create users/, output) + assert_match(/down\s+\d{3,}\s+Add email to users/, output) - `bin/rails db:migrate:redo` - output = `bin/rails db:migrate:status` + `bin/rails db:migrate:redo` + output = `bin/rails db:migrate:status` - assert_match(/up\s+\d{3,}\s+Create users/, output) - assert_match(/up\s+\d{3,}\s+Add email to users/, output) + assert_match(/up\s+\d{3,}\s+Create users/, output) + assert_match(/up\s+\d{3,}\s+Add email to users/, output) end end - test 'running migrations with not timestamp head migration files' do + test "running migrations with not timestamp head migration files" do Dir.chdir(app_path) do app_file "db/migrate/1_one_migration.rb", <<-MIGRATION @@ -169,15 +168,15 @@ module ApplicationTests `bin/rails db:migrate` - output = `bin/rails db:migrate:status` + output = `bin/rails db:migrate:status` - assert_match(/up\s+001\s+One migration/, output) - assert_match(/up\s+002\s+Two migration/, output) + assert_match(/up\s+001\s+One migration/, output) + assert_match(/up\s+002\s+Two migration/, output) end end - test 'schema generation when dump_schema_after_migration is set' do - add_to_config('config.active_record.dump_schema_after_migration = false') + test "schema generation when dump_schema_after_migration is set" do + add_to_config("config.active_record.dump_schema_after_migration = false") Dir.chdir(app_path) do `bin/rails generate model book title:string` @@ -188,7 +187,7 @@ module ApplicationTests assert !File.exist?("db/schema.rb"), "should not dump schema when configured not to" end - add_to_config('config.active_record.dump_schema_after_migration = true') + add_to_config("config.active_record.dump_schema_after_migration = true") Dir.chdir(app_path) do `bin/rails generate model reviews book_id:integer` @@ -199,7 +198,7 @@ module ApplicationTests end end - test 'default schema generation after migration' do + test "default schema generation after migration" do Dir.chdir(app_path) do `bin/rails generate model book title:string; bin/rails db:migrate` @@ -209,7 +208,7 @@ module ApplicationTests end end - test 'test migration status migrated file is deleted' do + test "test migration status migrated file is deleted" do Dir.chdir(app_path) do `bin/rails generate model user username:string password:string; bin/rails generate migration add_email_to_users email:string; @@ -217,7 +216,7 @@ module ApplicationTests rm db/migrate/*email*.rb` output = `bin/rails db:migrate:status` - File.write('test.txt', output) + File.write("test.txt", output) assert_match(/up\s+\d{14}\s+Create users/, output) assert_match(/up\s+\d{14}\s+\** NO FILE \**/, output) diff --git a/railties/test/application/rake/notes_test.rb b/railties/test/application/rake/notes_test.rb index 50def9beb0..e7ffea2e71 100644 --- a/railties/test/application/rake/notes_test.rb +++ b/railties/test/application/rake/notes_test.rb @@ -1,5 +1,5 @@ require "isolation/abstract_unit" -require 'rails/source_annotation_extractor' +require "rails/source_annotation_extractor" module ApplicationTests module RakeTests @@ -17,15 +17,15 @@ module ApplicationTests teardown_app end - test 'notes finds notes for certain file_types' do + test "notes finds notes for certain file_types" do app_file "app/views/home/index.html.erb", "<% # TODO: note in erb %>" app_file "app/assets/javascripts/application.js", "// TODO: note in js" app_file "app/assets/stylesheets/application.css", "// TODO: note in css" app_file "app/controllers/application_controller.rb", 1000.times.map { "" }.join("\n") << "# TODO: note in ruby" app_file "lib/tasks/task.rake", "# TODO: note in rake" - app_file 'app/views/home/index.html.builder', '# TODO: note in builder' - app_file 'config/locales/en.yml', '# TODO: note in yml' - app_file 'config/locales/en.yaml', '# TODO: note in yaml' + app_file "app/views/home/index.html.builder", "# TODO: note in builder" + app_file "config/locales/en.yml", "# TODO: note in yml" + app_file "config/locales/en.yaml", "# TODO: note in yaml" app_file "app/views/home/index.ruby", "# TODO: note in ruby" run_rake_notes do |output, lines| @@ -43,7 +43,7 @@ module ApplicationTests end end - test 'notes finds notes in default directories' do + test "notes finds notes in default directories" do app_file "app/controllers/some_controller.rb", "# TODO: note in app directory" app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory" app_file "db/some_seeds.rb", "# TODO: note in db directory" @@ -65,7 +65,7 @@ module ApplicationTests end end - test 'notes finds notes in custom directories' do + test "notes finds notes in custom directories" do app_file "app/controllers/some_controller.rb", "# TODO: note in app directory" app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory" app_file "db/some_seeds.rb", "# TODO: note in db directory" @@ -88,7 +88,7 @@ module ApplicationTests end end - test 'custom rake task finds specific notes in specific directories' do + test "custom rake task finds specific notes in specific directories" do app_file "app/controllers/some_controller.rb", "# TODO: note in app directory" app_file "lib/some_file.rb", "# OPTIMIZE: note in lib directory\n" << "# FIXME: note in lib directory" app_file "test/some_test.rb", 1000.times.map { "" }.join("\n") << "# TODO: note in test directory" @@ -113,7 +113,7 @@ module ApplicationTests end end - test 'register a new extension' do + test "register a new extension" do add_to_config "config.assets.precompile = []" add_to_config %q{ config.annotations.register_extensions("scss", "sass") { |annotation| /\/\/\s*(#{annotation}):?\s*(.*)$/ } } app_file "app/assets/stylesheets/application.css.scss", "// TODO: note in scss" @@ -126,32 +126,43 @@ module ApplicationTests end end + test "register additional directories" do + app_file "spec/spec_helper.rb", "# TODO: note in spec" + app_file "spec/models/user_spec.rb", "# TODO: note in model spec" + add_to_config ' config.annotations.register_directories("spec") ' + + run_rake_notes do |output, lines| + assert_match(/note in spec/, output) + assert_match(/note in model spec/, output) + assert_equal 2, lines.size + end + end + private - def run_rake_notes(command = 'bin/rails notes') - boot_rails - load_tasks + def run_rake_notes(command = "bin/rails notes") + boot_rails + load_tasks - Dir.chdir(app_path) do - output = `#{command}` - lines = output.scan(/\[([0-9\s]+)\]\s/).flatten + Dir.chdir(app_path) do + output = `#{command}` + lines = output.scan(/\[([0-9\s]+)\]\s/).flatten - yield output, lines + yield output, lines + end end - end - def load_tasks - require 'rake' - require 'rdoc/task' - require 'rake/testtask' + def load_tasks + require "rake" + require "rdoc/task" + require "rake/testtask" - Rails.application.load_tasks - end + Rails.application.load_tasks + end - def boot_rails - super - require "#{app_path}/config/environment" - end + def boot_rails + require "#{app_path}/config/environment" + end end end end diff --git a/railties/test/application/rake/restart_test.rb b/railties/test/application/rake/restart_test.rb index 30f662a9be..6ebd2d5461 100644 --- a/railties/test/application/rake/restart_test.rb +++ b/railties/test/application/rake/restart_test.rb @@ -7,39 +7,38 @@ module ApplicationTests def setup build_app - boot_rails end def teardown teardown_app end - test 'rake restart touches tmp/restart.txt' do + test "rails restart touches tmp/restart.txt" do Dir.chdir(app_path) do - `rake restart` + `bin/rails restart` assert File.exist?("tmp/restart.txt") prev_mtime = File.mtime("tmp/restart.txt") sleep(1) - `rake restart` + `bin/rails restart` curr_mtime = File.mtime("tmp/restart.txt") assert_not_equal prev_mtime, curr_mtime end end - test 'rake restart should work even if tmp folder does not exist' do + test "rails restart should work even if tmp folder does not exist" do Dir.chdir(app_path) do - FileUtils.remove_dir('tmp') - `rake restart` - assert File.exist?('tmp/restart.txt') + FileUtils.remove_dir("tmp") + `bin/rails restart` + assert File.exist?("tmp/restart.txt") end end - test 'rake restart removes server.pid also' do + test "rails restart removes server.pid also" do Dir.chdir(app_path) do FileUtils.mkdir_p("tmp/pids") FileUtils.touch("tmp/pids/server.pid") - `rake restart` + `bin/rails restart` assert_not File.exist?("tmp/pids/server.pid") end end diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb index acdb4e7d79..5fd5507453 100644 --- a/railties/test/application/rake_test.rb +++ b/railties/test/application/rake_test.rb @@ -7,7 +7,6 @@ module ApplicationTests def setup build_app - boot_rails end def teardown @@ -55,7 +54,7 @@ module ApplicationTests Rails.application.initialize! RUBY - assert_match("SuperMiddleware", Dir.chdir(app_path){ `bin/rails middleware` }) + assert_match("SuperMiddleware", Dir.chdir(app_path) { `bin/rails middleware` }) end def test_initializers_are_executed_in_rake_tasks @@ -70,7 +69,7 @@ module ApplicationTests end RUBY - output = Dir.chdir(app_path){ `bin/rails do_nothing` } + output = Dir.chdir(app_path) { `bin/rails do_nothing` } assert_match "Doing something...", output end @@ -83,7 +82,7 @@ module ApplicationTests end RUBY - app_file 'app/models/hello.rb', <<-RUBY + app_file "app/models/hello.rb", <<-RUBY class Hello def world puts 'Hello world' @@ -92,7 +91,7 @@ module ApplicationTests RUBY output = Dir.chdir(app_path) { `bin/rails do_nothing` } - assert_match 'Hello world', output + assert_match "Hello world", output end def test_should_not_eager_load_model_for_rake @@ -103,17 +102,17 @@ module ApplicationTests end RUBY - add_to_env_config 'production', <<-RUBY + add_to_env_config "production", <<-RUBY config.eager_load = true RUBY - app_file 'app/models/hello.rb', <<-RUBY + app_file "app/models/hello.rb", <<-RUBY raise 'should not be pre-required for rake even eager_load=true' RUBY Dir.chdir(app_path) do - assert system('bin/rails do_nothing RAILS_ENV=production'), - 'should not be pre-required for rake even eager_load=true' + assert system("bin/rails do_nothing RAILS_ENV=production"), + "should not be pre-required for rake even eager_load=true" end end @@ -129,7 +128,7 @@ module ApplicationTests end RUBY - output = Dir.chdir(app_path){ `bin/rails routes` } + output = Dir.chdir(app_path) { `bin/rails routes` } assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output end @@ -141,13 +140,13 @@ module ApplicationTests end RUBY - output = Dir.chdir(app_path){ `bin/rails routes CONTROLLER=cart` } + output = Dir.chdir(app_path) { `bin/rails routes CONTROLLER=cart` } assert_equal ["Passing `CONTROLLER` to `bin/rails routes` is deprecated and will be removed in Rails 5.1.", "Please use `bin/rails routes -c controller_name` instead.", "Prefix Verb URI Pattern Controller#Action", " cart GET /cart(.:format) cart#show\n"].join("\n"), output - output = Dir.chdir(app_path){ `bin/rails routes -c cart` } + output = Dir.chdir(app_path) { `bin/rails routes -c cart` } assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output end @@ -168,10 +167,10 @@ module ApplicationTests " PUT /admin/post(.:format) admin/posts#update", " DELETE /admin/post(.:format) admin/posts#destroy\n"].join("\n") - output = Dir.chdir(app_path){ `bin/rails routes -c Admin::PostController` } + output = Dir.chdir(app_path) { `bin/rails routes -c Admin::PostController` } assert_equal expected_output, output - output = Dir.chdir(app_path){ `bin/rails routes -c PostController` } + output = Dir.chdir(app_path) { `bin/rails routes -c PostController` } assert_equal expected_output, output end @@ -184,13 +183,13 @@ module ApplicationTests end RUBY - output = Dir.chdir(app_path){ `bin/rails routes -g show` } + output = Dir.chdir(app_path) { `bin/rails routes -g show` } assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output - output = Dir.chdir(app_path){ `bin/rails routes -g POST` } + output = Dir.chdir(app_path) { `bin/rails routes -g POST` } assert_equal "Prefix Verb URI Pattern Controller#Action\n POST /cart(.:format) cart#create\n", output - output = Dir.chdir(app_path){ `bin/rails routes -g basketballs` } + output = Dir.chdir(app_path) { `bin/rails routes -g basketballs` } assert_equal " Prefix Verb URI Pattern Controller#Action\n" \ "basketballs GET /basketballs(.:format) basketball#index\n", output end @@ -203,13 +202,13 @@ module ApplicationTests end RUBY - output = Dir.chdir(app_path){ `bin/rails routes -c cart` } + output = Dir.chdir(app_path) { `bin/rails routes -c cart` } assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output - output = Dir.chdir(app_path){ `bin/rails routes -c Cart` } + output = Dir.chdir(app_path) { `bin/rails routes -c Cart` } assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output - output = Dir.chdir(app_path){ `bin/rails routes -c CartController` } + output = Dir.chdir(app_path) { `bin/rails routes -c CartController` } assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output end @@ -219,7 +218,7 @@ module ApplicationTests end RUBY - assert_equal <<-MESSAGE.strip_heredoc, Dir.chdir(app_path){ `bin/rails routes` } + assert_equal <<-MESSAGE.strip_heredoc, Dir.chdir(app_path) { `bin/rails routes` } You don't have any routes defined! Please add some routes in config/routes.rb. @@ -235,7 +234,7 @@ module ApplicationTests end RUBY - output = Dir.chdir(app_path){ `bin/rake --rakefile Rakefile routes` } + output = Dir.chdir(app_path) { `bin/rake --rakefile Rakefile routes` } assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output end @@ -248,7 +247,7 @@ module ApplicationTests end RUBY - output = Dir.chdir(app_path){ `bin/rails log_something RAILS_ENV=production && cat log/production.log` } + output = Dir.chdir(app_path) { `bin/rails log_something RAILS_ENV=production && cat log/production.log` } assert_match "Sample log message", output end @@ -287,7 +286,7 @@ module ApplicationTests RAILS_ENV=test bin/rails db:migrate test` end - assert_match(/7 runs, 12 assertions, 0 failures, 0 errors/, output) + assert_match(/7 runs, 9 assertions, 0 failures, 0 errors/, output) assert_no_match(/Errors running/, output) end @@ -318,7 +317,7 @@ module ApplicationTests RAILS_ENV=test bin/rails db:migrate test` end - assert_match(/7 runs, 12 assertions, 0 failures, 0 errors/, output) + assert_match(/7 runs, 9 assertions, 0 failures, 0 errors/, output) assert_no_match(/Errors running/, output) end @@ -347,7 +346,7 @@ module ApplicationTests # ensure we have a schema_migrations table to dump `bin/rails db:migrate db:structure:dump SCHEMA=db/my_structure.sql` end - assert File.exist?(File.join(app_path, 'db', 'my_structure.sql')) + assert File.exist?(File.join(app_path, "db", "my_structure.sql")) end def test_rake_dump_structure_should_be_called_twice_when_migrate_redo @@ -368,24 +367,24 @@ module ApplicationTests bin/rails generate model product name:string; bin/rails db:migrate db:schema:cache:dump` end - assert File.exist?(File.join(app_path, 'db', 'schema_cache.dump')) + assert File.exist?(File.join(app_path, "db", "schema_cache.dump")) end def test_rake_clear_schema_cache Dir.chdir(app_path) do `bin/rails db:schema:cache:dump db:schema:cache:clear` end - assert !File.exist?(File.join(app_path, 'db', 'schema_cache.dump')) + assert !File.exist?(File.join(app_path, "db", "schema_cache.dump")) end def test_copy_templates Dir.chdir(app_path) do `bin/rails app:templates:copy` %w(controller mailer scaffold).each do |dir| - assert File.exist?(File.join(app_path, 'lib', 'templates', 'erb', dir)) + assert File.exist?(File.join(app_path, "lib", "templates", "erb", dir)) end %w(controller helper scaffold_controller assets).each do |dir| - assert File.exist?(File.join(app_path, 'lib', 'templates', 'rails', dir)) + assert File.exist?(File.join(app_path, "lib", "templates", "rails", dir)) end end end diff --git a/railties/test/application/rendering_test.rb b/railties/test/application/rendering_test.rb index b01febd768..ccafc5b6f1 100644 --- a/railties/test/application/rendering_test.rb +++ b/railties/test/application/rendering_test.rb @@ -1,5 +1,5 @@ -require 'isolation/abstract_unit' -require 'rack/test' +require "isolation/abstract_unit" +require "rack/test" module ApplicationTests class RoutingTest < ActiveSupport::TestCase @@ -8,7 +8,6 @@ module ApplicationTests def setup build_app - boot_rails end def teardown @@ -16,13 +15,13 @@ module ApplicationTests end test "Unknown format falls back to HTML template" do - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get 'pages/:id', to: 'pages#show' end RUBY - app_file 'app/controllers/pages_controller.rb', <<-RUBY + app_file "app/controllers/pages_controller.rb", <<-RUBY class PagesController < ApplicationController layout false @@ -31,14 +30,14 @@ module ApplicationTests end RUBY - app_file 'app/views/pages/show.html.erb', <<-RUBY + app_file "app/views/pages/show.html.erb", <<-RUBY <%= params[:id] %> RUBY - get '/pages/foo' + get "/pages/foo" assert_equal 200, last_response.status - get '/pages/foo.bar' + get "/pages/foo.bar" assert_equal 200, last_response.status end end diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb index e51f32aaed..c86759de5a 100644 --- a/railties/test/application/routing_test.rb +++ b/railties/test/application/routing_test.rb @@ -1,5 +1,5 @@ -require 'isolation/abstract_unit' -require 'rack/test' +require "isolation/abstract_unit" +require "rack/test" module ApplicationTests class RoutingTest < ActiveSupport::TestCase @@ -8,7 +8,6 @@ module ApplicationTests def setup build_app - boot_rails end def teardown @@ -39,10 +38,29 @@ module ApplicationTests assert_equal 200, last_response.status end + test "/rails/info routes are accessible with globbing route present" do + app("development") + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + get '*foo', to: 'foo#index' + end + RUBY + + get "/rails/info" + assert_equal 302, last_response.status + + get "rails/info/routes" + assert_equal 200, last_response.status + + get "rails/info/properties" + assert_equal 200, last_response.status + end + test "root takes precedence over internal welcome controller" do app("development") - assert_welcome get('/') + assert_welcome get("/") controller :foo, <<-RUBY class FooController < ApplicationController @@ -52,14 +70,14 @@ module ApplicationTests end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do root to: "foo#index" end RUBY - get '/' - assert_equal 'foo', last_response.body + get "/" + assert_equal "foo", last_response.body end test "rails/welcome in production" do @@ -89,8 +107,8 @@ module ApplicationTests test "simple controller" do simple_controller - get '/foo' - assert_equal 'foo', last_response.body + get "/foo" + assert_equal "foo", last_response.body end test "simple controller with helper" do @@ -102,7 +120,7 @@ module ApplicationTests end RUBY - app_file 'app/helpers/bar_helper.rb', <<-RUBY + app_file "app/helpers/bar_helper.rb", <<-RUBY module BarHelper def foo_or_bar? "bar" @@ -110,18 +128,18 @@ module ApplicationTests end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get ':controller(/:action)' end RUBY - get '/foo' - assert_equal 'bar', last_response.body + get "/foo" + assert_equal "bar", last_response.body end test "mount rack app" do - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do mount lambda { |env| [200, {}, [env["PATH_INFO"]]] }, at: "/blog" # The line below is required because mount sometimes @@ -130,8 +148,8 @@ module ApplicationTests end RUBY - get '/blog/archives' - assert_equal '/archives', last_response.body + get "/blog/archives" + assert_equal "/archives", last_response.body end test "mount named rack app" do @@ -143,15 +161,15 @@ module ApplicationTests end RUBY - app_file 'config/routes.rb', <<-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 + get "/foo" + assert_equal "/blog", last_response.body end test "multiple controllers" do @@ -171,21 +189,21 @@ module ApplicationTests end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get ':controller(/:action)' end RUBY - get '/foo' - assert_equal 'foo', last_response.body + get "/foo" + assert_equal "foo", last_response.body - get '/bar' - assert_equal 'bar', last_response.body + get "/bar" + assert_equal "bar", last_response.body end test "nested controller" do - controller 'foo', <<-RUBY + controller "foo", <<-RUBY class FooController < ApplicationController def index render text: "foo" @@ -193,7 +211,7 @@ module ApplicationTests end RUBY - controller 'admin/foo', <<-RUBY + controller "admin/foo", <<-RUBY module Admin class FooController < ApplicationController def index @@ -203,22 +221,22 @@ module ApplicationTests end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get 'admin/foo', to: 'admin/foo#index' get 'foo', to: 'foo#index' end RUBY - get '/foo' - assert_equal 'foo', last_response.body + get "/foo" + assert_equal "foo", last_response.body - get '/admin/foo' - assert_equal 'admin::foo', last_response.body + get "/admin/foo" + assert_equal "admin::foo", last_response.body end test "routes appending blocks" do - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get ':controller/:action' end @@ -230,22 +248,22 @@ module ApplicationTests end R - app 'development' + app "development" - get '/win' - assert_equal 'WIN', last_response.body + get "/win" + assert_equal "WIN", last_response.body - app_file 'config/routes.rb', <<-R + app_file "config/routes.rb", <<-R Rails.application.routes.draw do get 'lol' => 'hello#index' end R - get '/win' - assert_equal 'WIN', last_response.body + get "/win" + assert_equal "WIN", last_response.body end - {"development" => "baz", "production" => "bar"}.each do |mode, expected| + { "development" => "baz", "production" => "bar" }.each do |mode, expected| test "reloads routes when configuration is changed in #{mode}" do controller :foo, <<-RUBY class FooController < ApplicationController @@ -259,7 +277,7 @@ module ApplicationTests end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get 'foo', to: 'foo#bar' end @@ -267,10 +285,10 @@ module ApplicationTests app(mode) - get '/foo' - assert_equal 'bar', last_response.body + get "/foo" + assert_equal "bar", last_response.body - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get 'foo', to: 'foo#baz' end @@ -278,12 +296,12 @@ module ApplicationTests sleep 0.1 - get '/foo' + get "/foo" assert_equal expected, last_response.body end end - test 'routes are loaded just after initialization' do + test "routes are loaded just after initialization" do require "#{app_path}/config/application" # Create the rack app just inside after initialize callback @@ -291,17 +309,17 @@ module ApplicationTests ::InitializeRackApp = lambda { |env| [200, {}, ["InitializeRackApp"]] } end - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get 'foo', to: ::InitializeRackApp end RUBY - get '/foo' + get "/foo" assert_equal "InitializeRackApp", last_response.body end - test 'reload_routes! is part of Rails.application API' do + test "reload_routes! is part of Rails.application API" do app("development") assert_nothing_raised do Rails.application.reload_routes! @@ -309,7 +327,7 @@ module ApplicationTests end def test_root_path - app('development') + app("development") controller :foo, <<-RUBY class FooController < ApplicationController @@ -319,21 +337,21 @@ module ApplicationTests end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get 'foo', :to => 'foo#index' root :to => 'foo#index' end RUBY - remove_file 'public/index.html' + remove_file "public/index.html" - get '/' - assert_equal 'foo', last_response.body + get "/" + assert_equal "foo", last_response.body end - test 'routes are added and removed when reloading' do - app('development') + test "routes are added and removed when reloading" do + app("development") controller :foo, <<-RUBY class FooController < ApplicationController @@ -351,23 +369,23 @@ module ApplicationTests end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get 'foo', to: 'foo#index' end RUBY - get '/foo' - assert_equal 'foo', last_response.body - assert_equal '/foo', Rails.application.routes.url_helpers.foo_path + get "/foo" + assert_equal "foo", last_response.body + assert_equal "/foo", Rails.application.routes.url_helpers.foo_path - get '/bar' + get "/bar" assert_equal 404, last_response.status assert_raises NoMethodError do - assert_equal '/bar', Rails.application.routes.url_helpers.bar_path + assert_equal "/bar", Rails.application.routes.url_helpers.bar_path end - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get 'foo', to: 'foo#index' get 'bar', to: 'bar#index' @@ -376,15 +394,15 @@ module ApplicationTests Rails.application.reload_routes! - get '/foo' - assert_equal 'foo', last_response.body - assert_equal '/foo', Rails.application.routes.url_helpers.foo_path + get "/foo" + assert_equal "foo", last_response.body + assert_equal "/foo", Rails.application.routes.url_helpers.foo_path - get '/bar' - assert_equal 'bar', last_response.body - assert_equal '/bar', Rails.application.routes.url_helpers.bar_path + get "/bar" + assert_equal "bar", last_response.body + assert_equal "/bar", Rails.application.routes.url_helpers.bar_path - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get 'foo', to: 'foo#index' end @@ -392,19 +410,19 @@ module ApplicationTests Rails.application.reload_routes! - get '/foo' - assert_equal 'foo', last_response.body - assert_equal '/foo', Rails.application.routes.url_helpers.foo_path + get "/foo" + assert_equal "foo", last_response.body + assert_equal "/foo", Rails.application.routes.url_helpers.foo_path - get '/bar' + get "/bar" assert_equal 404, last_response.status assert_raises NoMethodError do - assert_equal '/bar', Rails.application.routes.url_helpers.bar_path + assert_equal "/bar", Rails.application.routes.url_helpers.bar_path end end - test 'named routes are cleared when reloading' do - app('development') + test "named routes are cleared when reloading" do + app("development") controller :foo, <<-RUBY class FooController < ApplicationController @@ -422,17 +440,17 @@ module ApplicationTests end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get ':locale/foo', to: 'foo#index', as: 'foo' end RUBY - get '/en/foo' - assert_equal 'foo', last_response.body - assert_equal '/en/foo', Rails.application.routes.url_helpers.foo_path(:locale => 'en') + get "/en/foo" + assert_equal "foo", last_response.body + assert_equal "/en/foo", Rails.application.routes.url_helpers.foo_path(locale: "en") - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get ':locale/bar', to: 'bar#index', as: 'foo' end @@ -440,28 +458,28 @@ module ApplicationTests Rails.application.reload_routes! - get '/en/foo' + get "/en/foo" assert_equal 404, last_response.status - get '/en/bar' - assert_equal 'bar', last_response.body - assert_equal '/en/bar', Rails.application.routes.url_helpers.foo_path(:locale => 'en') + get "/en/bar" + assert_equal "bar", last_response.body + assert_equal "/en/bar", Rails.application.routes.url_helpers.foo_path(locale: "en") end - test 'resource routing with irregular inflection' do - app_file 'config/initializers/inflection.rb', <<-RUBY + test "resource routing with irregular inflection" do + app_file "config/initializers/inflection.rb", <<-RUBY ActiveSupport::Inflector.inflections do |inflect| inflect.irregular 'yazi', 'yazilar' end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do resources :yazilar end RUBY - controller 'yazilar', <<-RUBY + controller "yazilar", <<-RUBY class YazilarController < ApplicationController def index render text: 'yazilar#index' @@ -469,10 +487,10 @@ module ApplicationTests end RUBY - get '/yazilars' + get "/yazilars" assert_equal 404, last_response.status - get '/yazilar' + get "/yazilar" assert_equal 200, last_response.status end end diff --git a/railties/test/application/runner_test.rb b/railties/test/application/runner_test.rb index 9f15ce5e85..77e7a2cca5 100644 --- a/railties/test/application/runner_test.rb +++ b/railties/test/application/runner_test.rb @@ -1,5 +1,5 @@ -require 'isolation/abstract_unit' -require 'env_helpers' +require "isolation/abstract_unit" +require "env_helpers" module ApplicationTests class RunnerTest < ActiveSupport::TestCase @@ -8,7 +8,6 @@ module ApplicationTests def setup build_app - boot_rails # Lets create a model so we have something to play with app_file "app/models/user.rb", <<-MODEL @@ -75,13 +74,15 @@ module ApplicationTests end def test_runner_detects_syntax_errors - Dir.chdir(app_path) { `bin/rails runner "puts 'hello world" 2>&1` } - refute $?.success? + output = Dir.chdir(app_path) { `bin/rails runner "puts 'hello world" 2>&1` } + assert_not $?.success? + assert_match "unterminated string meets end of file", output end def test_runner_detects_bad_script_name - Dir.chdir(app_path) { `bin/rails runner "iuiqwiourowe" 2>&1` } - refute $?.success? + output = Dir.chdir(app_path) { `bin/rails runner "iuiqwiourowe" 2>&1` } + assert_not $?.success? + assert_match "undefined local variable or method `iuiqwiourowe' for", output end def test_environment_with_rails_env diff --git a/railties/test/application/test_runner_test.rb b/railties/test/application/test_runner_test.rb index 08759ab5a4..b442891769 100644 --- a/railties/test/application/test_runner_test.rb +++ b/railties/test/application/test_runner_test.rb @@ -1,6 +1,6 @@ -require 'isolation/abstract_unit' -require 'active_support/core_ext/string/strip' -require 'env_helpers' +require "isolation/abstract_unit" +require "active_support/core_ext/string/strip" +require "env_helpers" module ApplicationTests class TestRunnerTest < ActiveSupport::TestCase @@ -16,31 +16,31 @@ module ApplicationTests end def test_run_single_file - create_test_file :models, 'foo' - create_test_file :models, 'bar' + create_test_file :models, "foo" + create_test_file :models, "bar" assert_match "1 runs, 1 assertions, 0 failures", run_test_command("test/models/foo_test.rb") end def test_run_multiple_files - create_test_file :models, 'foo' - create_test_file :models, 'bar' + create_test_file :models, "foo" + create_test_file :models, "bar" assert_match "2 runs, 2 assertions, 0 failures", run_test_command("test/models/foo_test.rb test/models/bar_test.rb") end def test_run_file_with_syntax_error - app_file 'test/models/error_test.rb', <<-RUBY + app_file "test/models/error_test.rb", <<-RUBY require 'test_helper' def; end RUBY - error = capture(:stderr) { run_test_command('test/models/error_test.rb') } + error = capture(:stderr) { run_test_command("test/models/error_test.rb") } assert_match "syntax error", error end def test_run_models - create_test_file :models, 'foo' - create_test_file :models, 'bar' - create_test_file :controllers, 'foobar_controller' + create_test_file :models, "foo" + create_test_file :models, "bar" + create_test_file :controllers, "foobar_controller" run_test_command("test/models").tap do |output| assert_match "FooTest", output assert_match "BarTest", output @@ -49,9 +49,9 @@ module ApplicationTests end def test_run_helpers - create_test_file :helpers, 'foo_helper' - create_test_file :helpers, 'bar_helper' - create_test_file :controllers, 'foobar_controller' + create_test_file :helpers, "foo_helper" + create_test_file :helpers, "bar_helper" + create_test_file :controllers, "foobar_controller" run_test_command("test/helpers").tap do |output| assert_match "FooHelperTest", output assert_match "BarHelperTest", output @@ -61,10 +61,10 @@ module ApplicationTests def test_run_units skip "we no longer have the concept of unit tests. Just different directories..." - create_test_file :models, 'foo' - create_test_file :helpers, 'bar_helper' - create_test_file :unit, 'baz_unit' - create_test_file :controllers, 'foobar_controller' + create_test_file :models, "foo" + create_test_file :helpers, "bar_helper" + create_test_file :unit, "baz_unit" + create_test_file :controllers, "foobar_controller" run_test_units_command.tap do |output| assert_match "FooTest", output assert_match "BarHelperTest", output @@ -74,9 +74,9 @@ module ApplicationTests end def test_run_controllers - create_test_file :controllers, 'foo_controller' - create_test_file :controllers, 'bar_controller' - create_test_file :models, 'foo' + create_test_file :controllers, "foo_controller" + create_test_file :controllers, "bar_controller" + create_test_file :models, "foo" run_test_command("test/controllers").tap do |output| assert_match "FooControllerTest", output assert_match "BarControllerTest", output @@ -85,9 +85,9 @@ module ApplicationTests end def test_run_mailers - create_test_file :mailers, 'foo_mailer' - create_test_file :mailers, 'bar_mailer' - create_test_file :models, 'foo' + create_test_file :mailers, "foo_mailer" + create_test_file :mailers, "bar_mailer" + create_test_file :models, "foo" run_test_command("test/mailers").tap do |output| assert_match "FooMailerTest", output assert_match "BarMailerTest", output @@ -96,9 +96,9 @@ module ApplicationTests end def test_run_jobs - create_test_file :jobs, 'foo_job' - create_test_file :jobs, 'bar_job' - create_test_file :models, 'foo' + create_test_file :jobs, "foo_job" + create_test_file :jobs, "bar_job" + create_test_file :models, "foo" run_test_command("test/jobs").tap do |output| assert_match "FooJobTest", output assert_match "BarJobTest", output @@ -108,10 +108,10 @@ module ApplicationTests def test_run_functionals skip "we no longer have the concept of functional tests. Just different directories..." - create_test_file :mailers, 'foo_mailer' - create_test_file :controllers, 'bar_controller' - create_test_file :functional, 'baz_functional' - create_test_file :models, 'foo' + create_test_file :mailers, "foo_mailer" + create_test_file :controllers, "bar_controller" + create_test_file :functional, "baz_functional" + create_test_file :models, "foo" run_test_functionals_command.tap do |output| assert_match "FooMailerTest", output assert_match "BarControllerTest", output @@ -121,8 +121,8 @@ module ApplicationTests end def test_run_integration - create_test_file :integration, 'foo_integration' - create_test_file :models, 'foo' + create_test_file :integration, "foo_integration" + create_test_file :models, "foo" run_test_command("test/integration").tap do |output| assert_match "FooIntegration", output assert_match "1 runs, 1 assertions, 0 failures", output @@ -132,14 +132,14 @@ module ApplicationTests def test_run_all_suites suites = [:models, :helpers, :unit, :controllers, :mailers, :functional, :integration, :jobs] suites.each { |suite| create_test_file suite, "foo_#{suite}" } - run_test_command('') .tap do |output| + run_test_command("") .tap do |output| suites.each { |suite| assert_match "Foo#{suite.to_s.camelize}Test", output } assert_match "8 runs, 8 assertions, 0 failures", output end end def test_run_named_test - app_file 'test/unit/chu_2_koi_test.rb', <<-RUBY + app_file "test/unit/chu_2_koi_test.rb", <<-RUBY require 'test_helper' class Chu2KoiTest < ActiveSupport::TestCase @@ -153,14 +153,14 @@ module ApplicationTests end RUBY - run_test_command('-n test_rikka test/unit/chu_2_koi_test.rb').tap do |output| + run_test_command("-n test_rikka test/unit/chu_2_koi_test.rb").tap do |output| assert_match "Rikka", output assert_no_match "Sanae", output end end def test_run_matched_test - app_file 'test/unit/chu_2_koi_test.rb', <<-RUBY + app_file "test/unit/chu_2_koi_test.rb", <<-RUBY require 'test_helper' class Chu2KoiTest < ActiveSupport::TestCase @@ -174,7 +174,7 @@ module ApplicationTests end RUBY - run_test_command('-n /rikka/ test/unit/chu_2_koi_test.rb').tap do |output| + run_test_command("-n /rikka/ test/unit/chu_2_koi_test.rb").tap do |output| assert_match "Rikka", output assert_no_match "Sanae", output end @@ -195,14 +195,14 @@ module ApplicationTests def test_run_with_model skip "These feel a bit odd. Not sure we should keep supporting them." create_model_with_fixture - create_fixture_test 'models', 'user' + create_fixture_test "models", "user" assert_match "3 users", run_task(["test models/user"]) assert_match "3 users", run_task(["test app/models/user.rb"]) end def test_run_different_environment_using_env_var skip "no longer possible. Running tests in a different environment should be explicit" - app_file 'test/unit/env_test.rb', <<-RUBY + app_file "test/unit/env_test.rb", <<-RUBY require 'test_helper' class EnvTest < ActiveSupport::TestCase @@ -212,14 +212,14 @@ module ApplicationTests end RUBY - ENV['RAILS_ENV'] = 'development' - assert_match "development", run_test_command('test/unit/env_test.rb') + ENV["RAILS_ENV"] = "development" + assert_match "development", run_test_command("test/unit/env_test.rb") end def test_run_in_test_environment_by_default create_env_test - assert_match "Current Environment: test", run_test_command('test/unit/env_test.rb') + assert_match "Current Environment: test", run_test_command("test/unit/env_test.rb") end def test_run_different_environment @@ -231,27 +231,27 @@ module ApplicationTests def test_generated_scaffold_works_with_rails_test create_scaffold - assert_match "0 failures, 0 errors, 0 skips", run_test_command('') + assert_match "0 failures, 0 errors, 0 skips", run_test_command("") end def test_generated_controller_works_with_rails_test create_controller - assert_match "0 failures, 0 errors, 0 skips", run_test_command('') + assert_match "0 failures, 0 errors, 0 skips", run_test_command("") end def test_run_multiple_folders - create_test_file :models, 'account' - create_test_file :controllers, 'accounts_controller' + create_test_file :models, "account" + create_test_file :controllers, "accounts_controller" - run_test_command('test/models test/controllers').tap do |output| - assert_match 'AccountTest', output - assert_match 'AccountsControllerTest', output - assert_match '2 runs, 2 assertions, 0 failures, 0 errors, 0 skips', output + run_test_command("test/models test/controllers").tap do |output| + assert_match "AccountTest", output + assert_match "AccountsControllerTest", output + assert_match "2 runs, 2 assertions, 0 failures, 0 errors, 0 skips", output end end def test_run_with_ruby_command - app_file 'test/models/post_test.rb', <<-RUBY + app_file "test/models/post_test.rb", <<-RUBY require 'test_helper' class PostTest < ActiveSupport::TestCase @@ -264,15 +264,15 @@ module ApplicationTests Dir.chdir(app_path) do `ruby -Itest test/models/post_test.rb`.tap do |output| - assert_match 'PostTest', output - assert_no_match 'is already defined in', output + assert_match "PostTest", output + assert_no_match "is already defined in", output end end end def test_mix_files_and_line_filters - create_test_file :models, 'account' - app_file 'test/models/post_test.rb', <<-RUBY + create_test_file :models, "account" + app_file "test/models/post_test.rb", <<-RUBY require 'test_helper' class PostTest < ActiveSupport::TestCase @@ -287,15 +287,15 @@ module ApplicationTests end RUBY - run_test_command('test/models/account_test.rb test/models/post_test.rb:4').tap do |output| - assert_match 'AccountTest', output - assert_match 'PostTest', output - assert_match '2 runs, 2 assertions', output + run_test_command("test/models/account_test.rb test/models/post_test.rb:4").tap do |output| + assert_match "AccountTest", output + assert_match "PostTest", output + assert_match "2 runs, 2 assertions", output end end def test_more_than_one_line_filter - app_file 'test/models/post_test.rb', <<-RUBY + app_file "test/models/post_test.rb", <<-RUBY require 'test_helper' class PostTest < ActiveSupport::TestCase @@ -315,15 +315,15 @@ module ApplicationTests end RUBY - run_test_command('test/models/post_test.rb:4:9').tap do |output| - assert_match 'PostTest:FirstFilter', output - assert_match 'PostTest:SecondFilter', output - assert_match '2 runs, 2 assertions', output + run_test_command("test/models/post_test.rb:4:9").tap do |output| + assert_match "PostTest:FirstFilter", output + assert_match "PostTest:SecondFilter", output + assert_match "2 runs, 2 assertions", output end end def test_more_than_one_line_filter_with_multiple_files - app_file 'test/models/account_test.rb', <<-RUBY + app_file "test/models/account_test.rb", <<-RUBY require 'test_helper' class AccountTest < ActiveSupport::TestCase @@ -343,7 +343,7 @@ module ApplicationTests end RUBY - app_file 'test/models/post_test.rb', <<-RUBY + app_file "test/models/post_test.rb", <<-RUBY require 'test_helper' class PostTest < ActiveSupport::TestCase @@ -363,27 +363,27 @@ module ApplicationTests end RUBY - run_test_command('test/models/account_test.rb:4:9 test/models/post_test.rb:4:9').tap do |output| - assert_match 'AccountTest:FirstFilter', output - assert_match 'AccountTest:SecondFilter', output - assert_match 'PostTest:FirstFilter', output - assert_match 'PostTest:SecondFilter', output - assert_match '4 runs, 4 assertions', output + run_test_command("test/models/account_test.rb:4:9 test/models/post_test.rb:4:9").tap do |output| + assert_match "AccountTest:FirstFilter", output + assert_match "AccountTest:SecondFilter", output + assert_match "PostTest:FirstFilter", output + assert_match "PostTest:SecondFilter", output + assert_match "4 runs, 4 assertions", output end end def test_multiple_line_filters - create_test_file :models, 'account' - create_test_file :models, 'post' + create_test_file :models, "account" + create_test_file :models, "post" - run_test_command('test/models/account_test.rb:4 test/models/post_test.rb:4').tap do |output| - assert_match 'AccountTest', output - assert_match 'PostTest', output + run_test_command("test/models/account_test.rb:4 test/models/post_test.rb:4").tap do |output| + assert_match "AccountTest", output + assert_match "PostTest", output end end def test_line_filters_trigger_only_one_runnable - app_file 'test/models/post_test.rb', <<-RUBY + app_file "test/models/post_test.rb", <<-RUBY require 'test_helper' class PostTest < ActiveSupport::TestCase @@ -400,14 +400,14 @@ module ApplicationTests RUBY # Pass seed guaranteeing failure. - run_test_command('test/models/post_test.rb:4 --seed 30410').tap do |output| - assert_no_match 'ran second runnable', output - assert_match '1 runs, 1 assertions', output + run_test_command("test/models/post_test.rb:4 --seed 30410").tap do |output| + assert_no_match "ran second runnable", output + assert_match "1 runs, 1 assertions", output end end def test_line_filter_with_minitest_string_filter - app_file 'test/models/post_test.rb', <<-RUBY + app_file "test/models/post_test.rb", <<-RUBY require 'test_helper' class PostTest < ActiveSupport::TestCase @@ -423,128 +423,128 @@ module ApplicationTests end RUBY - run_test_command('test/models/post_test.rb:4 -n test_by_name').tap do |output| - assert_match 'by line', output - assert_match 'by name', output - assert_match '2 runs, 2 assertions', output + run_test_command("test/models/post_test.rb:4 -n test_by_name").tap do |output| + assert_match "by line", output + assert_match "by name", output + assert_match "2 runs, 2 assertions", output end end def test_shows_filtered_backtrace_by_default create_backtrace_test - assert_match 'Rails::BacktraceCleaner', run_test_command('test/unit/backtrace_test.rb') + assert_match "Rails::BacktraceCleaner", run_test_command("test/unit/backtrace_test.rb") end def test_backtrace_option create_backtrace_test - assert_match 'Minitest::BacktraceFilter', run_test_command('test/unit/backtrace_test.rb -b') - assert_match 'Minitest::BacktraceFilter', - run_test_command('test/unit/backtrace_test.rb --backtrace') + assert_match "Minitest::BacktraceFilter", run_test_command("test/unit/backtrace_test.rb -b") + assert_match "Minitest::BacktraceFilter", + run_test_command("test/unit/backtrace_test.rb --backtrace") end def test_show_full_backtrace_using_backtrace_environment_variable create_backtrace_test - switch_env 'BACKTRACE', 'true' do - assert_match 'Minitest::BacktraceFilter', run_test_command('test/unit/backtrace_test.rb') + switch_env "BACKTRACE", "true" do + assert_match "Minitest::BacktraceFilter", run_test_command("test/unit/backtrace_test.rb") end end def test_run_app_without_rails_loaded # Simulate a real Rails app boot. - app_file 'config/boot.rb', <<-RUBY + app_file "config/boot.rb", <<-RUBY ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' # Set up gems listed in the Gemfile. RUBY - assert_match '0 runs, 0 assertions', run_test_command('') + assert_match "0 runs, 0 assertions", run_test_command("") end def test_output_inline_by_default - create_test_file :models, 'post', pass: false + create_test_file :models, "post", pass: false - output = run_test_command('test/models/post_test.rb') + output = run_test_command("test/models/post_test.rb") expect = %r{Running:\n\nPostTest\nF\n\nFailure:\nPostTest#test_truth \[[^\]]+test/models/post_test.rb:6\]:\nwups!\n\nbin/rails test test/models/post_test.rb:4\n\n\n\n} assert_match expect, output end def test_only_inline_failure_output - create_test_file :models, 'post', pass: false + create_test_file :models, "post", pass: false - output = run_test_command('test/models/post_test.rb') + output = run_test_command("test/models/post_test.rb") assert_match %r{Finished in.*\n\n1 runs, 1 assertions}, output end def test_fail_fast - create_test_file :models, 'post', pass: false + create_test_file :models, "post", pass: false assert_match(/Interrupt/, - capture(:stderr) { run_test_command('test/models/post_test.rb --fail-fast') }) + capture(:stderr) { run_test_command("test/models/post_test.rb --fail-fast") }) end def test_raise_error_when_specified_file_does_not_exist - error = capture(:stderr) { run_test_command('test/not_exists.rb') } + error = capture(:stderr) { run_test_command("test/not_exists.rb") } assert_match(%r{cannot load such file.+test/not_exists\.rb}, error) end def test_pass_TEST_env_on_rake_test - create_test_file :models, 'account' - create_test_file :models, 'post', pass: false + create_test_file :models, "account" + create_test_file :models, "post", pass: false # This specifically verifies TEST for backwards compatibility with rake test # as bin/rails test already supports running tests from a single file more cleanly. output = Dir.chdir(app_path) { `bin/rake test TEST=test/models/post_test.rb` } assert_match "PostTest", output, "passing TEST= should run selected test" assert_no_match "AccountTest", output, "passing TEST= should only run selected test" - assert_match '1 runs, 1 assertions', output + assert_match "1 runs, 1 assertions", output end def test_pass_rake_options - create_test_file :models, 'account' + create_test_file :models, "account" output = Dir.chdir(app_path) { `bin/rake --rakefile Rakefile --trace=stdout test` } - assert_match '1 runs, 1 assertions', output - assert_match 'Execute test', output + assert_match "1 runs, 1 assertions", output + assert_match "Execute test", output end def test_rails_db_create_all_restores_db_connection - create_test_file :models, 'account' + create_test_file :models, "account" output = Dir.chdir(app_path) { `bin/rails db:create:all db:migrate && echo ".tables" | rails dbconsole` } assert_match "ar_internal_metadata", output, "tables should be dumped" end def test_rails_db_create_all_restores_db_connection_after_drop - create_test_file :models, 'account' + create_test_file :models, "account" Dir.chdir(app_path) { `bin/rails db:create:all` } # create all to avoid warnings output = Dir.chdir(app_path) { `bin/rails db:drop:all db:create:all db:migrate && echo ".tables" | rails dbconsole` } assert_match "ar_internal_metadata", output, "tables should be dumped" end def test_rake_passes_TESTOPTS_to_minitest - create_test_file :models, 'account' + create_test_file :models, "account" output = Dir.chdir(app_path) { `bin/rake test TESTOPTS=-v` } assert_match "AccountTest#test_truth", output, "passing TEST= should run selected test" end def test_rake_passes_multiple_TESTOPTS_to_minitest - create_test_file :models, 'account' + create_test_file :models, "account" output = Dir.chdir(app_path) { `bin/rake test TESTOPTS='-v --seed=1234'` } assert_match "AccountTest#test_truth", output, "passing TEST= should run selected test" assert_match "seed=1234", output, "passing TEST= should run selected test" end private - def run_test_command(arguments = 'test/unit/test_test.rb') + def run_test_command(arguments = "test/unit/test_test.rb") Dir.chdir(app_path) { `bin/rails t #{arguments}` } end def create_model_with_fixture - script 'generate model user name:string' + script "generate model user name:string" - app_file 'test/fixtures/users.yml', <<-YAML.strip_heredoc + app_file "test/fixtures/users.yml", <<-YAML.strip_heredoc vampire: id: 1 name: Koyomi Araragi @@ -559,7 +559,7 @@ module ApplicationTests run_migration end - def create_fixture_test(path = :unit, name = 'test') + def create_fixture_test(path = :unit, name = "test") app_file "test/#{path}/#{name}_test.rb", <<-RUBY require 'test_helper' @@ -572,7 +572,7 @@ module ApplicationTests end def create_backtrace_test - app_file 'test/unit/backtrace_test.rb', <<-RUBY + app_file "test/unit/backtrace_test.rb", <<-RUBY require 'test_helper' class BacktraceTest < ActiveSupport::TestCase @@ -584,10 +584,10 @@ module ApplicationTests end def create_schema - app_file 'db/schema.rb', '' + app_file "db/schema.rb", "" end - def create_test_file(path = :unit, name = 'test', pass: true) + def create_test_file(path = :unit, name = "test", pass: true) app_file "test/#{path}/#{name}_test.rb", <<-RUBY require 'test_helper' @@ -601,7 +601,7 @@ module ApplicationTests end def create_env_test - app_file 'test/unit/env_test.rb', <<-RUBY + app_file "test/unit/env_test.rb", <<-RUBY require 'test_helper' class EnvTest < ActiveSupport::TestCase @@ -613,13 +613,13 @@ module ApplicationTests end def create_scaffold - script 'generate scaffold user name:string' - Dir.chdir(app_path) { File.exist?('app/models/user.rb') } + script "generate scaffold user name:string" + Dir.chdir(app_path) { File.exist?("app/models/user.rb") } run_migration end def create_controller - script 'generate controller admin/dashboard index' + script "generate controller admin/dashboard index" end def run_migration diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb index 85b003fce9..32d2a6857c 100644 --- a/railties/test/application/test_test.rb +++ b/railties/test/application/test_test.rb @@ -1,4 +1,4 @@ -require 'isolation/abstract_unit' +require "isolation/abstract_unit" module ApplicationTests class TestTest < ActiveSupport::TestCase @@ -6,15 +6,14 @@ module ApplicationTests def setup build_app - boot_rails end def teardown teardown_app end - test "truth" do - app_file 'test/unit/foo_test.rb', <<-RUBY + test "simple successful test" do + app_file "test/unit/foo_test.rb", <<-RUBY require 'test_helper' class FooTest < ActiveSupport::TestCase @@ -24,20 +23,52 @@ module ApplicationTests end RUBY - assert_successful_test_run 'unit/foo_test.rb' + assert_successful_test_run "unit/foo_test.rb" + end + + test "after_run" do + app_file "test/unit/foo_test.rb", <<-RUBY + require 'test_helper' + + Minitest.after_run { puts "WORLD" } + Minitest.after_run { puts "HELLO" } + + class FooTest < ActiveSupport::TestCase + def test_truth + assert true + end + end + RUBY + + result = assert_successful_test_run "unit/foo_test.rb" + assert_equal ["HELLO", "WORLD"], result.scan(/HELLO|WORLD/) # only once and in correct order + end + + test "simple failed test" do + app_file "test/unit/foo_test.rb", <<-RUBY + require 'test_helper' + + class FooTest < ActiveSupport::TestCase + def test_truth + assert false + end + end + RUBY + + assert_unsuccessful_run "unit/foo_test.rb", "Failed assertion" end test "integration test" do - controller 'posts', <<-RUBY + controller "posts", <<-RUBY class PostsController < ActionController::Base end RUBY - app_file 'app/views/posts/index.html.erb', <<-HTML + app_file "app/views/posts/index.html.erb", <<-HTML Posts#index HTML - app_file 'test/integration/posts_test.rb', <<-RUBY + app_file "test/integration/posts_test.rb", <<-RUBY require 'test_helper' class PostsTest < ActionDispatch::IntegrationTest @@ -49,11 +80,11 @@ module ApplicationTests end RUBY - assert_successful_test_run 'integration/posts_test.rb' + assert_successful_test_run "integration/posts_test.rb" end test "enable full backtraces on test failures" do - app_file 'test/unit/failing_test.rb', <<-RUBY + app_file "test/unit/failing_test.rb", <<-RUBY require 'test_helper' class FailingTest < ActiveSupport::TestCase @@ -63,16 +94,16 @@ module ApplicationTests end RUBY - output = run_test_file('unit/failing_test.rb', env: { "BACKTRACE" => "1" }) + output = run_test_file("unit/failing_test.rb", env: { "BACKTRACE" => "1" }) assert_match %r{test/unit/failing_test\.rb}, output assert_match %r{test/unit/failing_test\.rb:4}, output end test "ruby schema migrations" do - output = script('generate model user name:string') + output = script("generate model user name:string") version = output.match(/(\d+)_create_users\.rb/)[1] - app_file 'test/models/user_test.rb', <<-RUBY + app_file "test/models/user_test.rb", <<-RUBY require 'test_helper' class UserTest < ActiveSupport::TestCase @@ -81,11 +112,11 @@ module ApplicationTests end end RUBY - app_file 'db/schema.rb', '' + app_file "db/schema.rb", "" assert_unsuccessful_run "models/user_test.rb", "Migrations are pending" - app_file 'db/schema.rb', <<-RUBY + app_file "db/schema.rb", <<-RUBY ActiveRecord::Schema.define(version: #{version}) do create_table :users do |t| t.string :name @@ -93,7 +124,7 @@ module ApplicationTests end RUBY - app_file 'config/initializers/disable_maintain_test_schema.rb', <<-RUBY + app_file "config/initializers/disable_maintain_test_schema.rb", <<-RUBY Rails.application.config.active_record.maintain_test_schema = false RUBY @@ -101,15 +132,15 @@ module ApplicationTests File.delete "#{app_path}/config/initializers/disable_maintain_test_schema.rb" - result = assert_successful_test_run('models/user_test.rb') - assert !result.include?("create_table(:users)") + result = assert_successful_test_run("models/user_test.rb") + assert_not_includes result, "create_table(:users)" end test "sql structure migrations" do - output = script('generate model user name:string') + output = script("generate model user name:string") version = output.match(/(\d+)_create_users\.rb/)[1] - app_file 'test/models/user_test.rb', <<-RUBY + app_file "test/models/user_test.rb", <<-RUBY require 'test_helper' class UserTest < ActiveSupport::TestCase @@ -119,21 +150,21 @@ module ApplicationTests end RUBY - app_file 'db/structure.sql', '' - app_file 'config/initializers/enable_sql_schema_format.rb', <<-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 + 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 + app_file "config/initializers/disable_maintain_test_schema.rb", <<-RUBY Rails.application.config.active_record.maintain_test_schema = false RUBY @@ -141,14 +172,14 @@ module ApplicationTests File.delete "#{app_path}/config/initializers/disable_maintain_test_schema.rb" - assert_successful_test_run('models/user_test.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') + 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 + app_file "test/models/user_test.rb", <<-RUBY require 'test_helper' class UserTest < ActiveSupport::TestCase test "user" do @@ -157,23 +188,23 @@ module ApplicationTests end RUBY - app_file 'config/initializers/enable_sql_schema_format.rb', <<-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 + 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') + assert_successful_test_run("models/user_test.rb") - output_2 = script('generate migration add_email_to_users') + 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 + app_file "test/models/user_test.rb", <<-RUBY require 'test_helper' class UserTest < ActiveSupport::TestCase @@ -183,7 +214,7 @@ module ApplicationTests end RUBY - app_file 'db/structure.sql', <<-SQL + 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)); @@ -191,17 +222,17 @@ module ApplicationTests INSERT INTO schema_migrations (version) VALUES ('#{version_2}'); SQL - assert_successful_test_run('models/user_test.rb') + 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') + output = script("generate model user name:string") version = output.match(/(\d+)_create_users\.rb/)[1] - app_file 'test/models/user_test.rb', <<-RUBY + app_file "test/models/user_test.rb", <<-RUBY require 'test_helper' class UserTest < ActiveSupport::TestCase @@ -210,7 +241,7 @@ module ApplicationTests end end RUBY - app_file 'db/schema.rb', <<-RUBY + app_file "db/schema.rb", <<-RUBY ActiveRecord::Schema.define(version: #{version}) do create_table :users do |t| t.string :name @@ -221,7 +252,7 @@ module ApplicationTests assert_successful_test_run "models/user_test.rb" # Simulate `db:rollback` + edit of the migration file + `db:migrate` - app_file 'db/schema.rb', <<-RUBY + app_file "db/schema.rb", <<-RUBY ActiveRecord::Schema.define(version: #{version}) do create_table :users do |t| t.string :name @@ -241,10 +272,10 @@ Expected: ["id", "name"] end test "hooks for plugins" do - output = script('generate model user name:string') + output = script("generate model user name:string") version = output.match(/(\d+)_create_users\.rb/)[1] - app_file 'lib/tasks/hooks.rake', <<-RUBY + 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 @@ -259,7 +290,7 @@ Expected: ["id", "name"] Rake::Task[:after_hook].invoke end RUBY - app_file 'test/models/user_test.rb', <<-RUBY + app_file "test/models/user_test.rb", <<-RUBY require 'test_helper' class UserTest < ActiveSupport::TestCase test "user" do @@ -269,7 +300,7 @@ Expected: ["id", "name"] RUBY # Simulate `db:migrate` - app_file 'db/schema.rb', <<-RUBY + app_file "db/schema.rb", <<-RUBY ActiveRecord::Schema.define(version: #{version}) do create_table :users do |t| t.string :name @@ -290,7 +321,7 @@ Expected: ["id", "name"] def assert_unsuccessful_run(name, message) result = run_test_file(name) assert_not_equal 0, $?.to_i - assert result.include?(message) + assert_includes result, message result end diff --git a/railties/test/application/url_generation_test.rb b/railties/test/application/url_generation_test.rb index 894e18cb39..ced6c6b0a6 100644 --- a/railties/test/application/url_generation_test.rb +++ b/railties/test/application/url_generation_test.rb @@ -1,4 +1,4 @@ -require 'isolation/abstract_unit' +require "isolation/abstract_unit" module ApplicationTests class UrlGenerationTest < ActiveSupport::TestCase @@ -9,7 +9,6 @@ module ApplicationTests end test "it works" do - boot_rails require "rails" require "action_controller/railtie" require "action_view/railtie" @@ -36,7 +35,7 @@ module ApplicationTests get "/" => "omg#index", as: :omg end - require 'rack/test' + require "rack/test" extend Rack::Test::Methods get "/" @@ -44,12 +43,11 @@ module ApplicationTests end def test_routes_know_the_relative_root - boot_rails require "rails" require "action_controller/railtie" require "action_view/railtie" - relative_url = '/hello' + relative_url = "/hello" ENV["RAILS_RELATIVE_URL_ROOT"] = relative_url app = Class.new(Rails::Application) assert_equal relative_url, app.routes.relative_url_root diff --git a/railties/test/backtrace_cleaner_test.rb b/railties/test/backtrace_cleaner_test.rb index 2dd74f8fd1..17201d6f77 100644 --- a/railties/test/backtrace_cleaner_test.rb +++ b/railties/test/backtrace_cleaner_test.rb @@ -1,24 +1,32 @@ -require 'abstract_unit' -require 'rails/backtrace_cleaner' +require "abstract_unit" +require "rails/backtrace_cleaner" -class BacktraceCleanerVendorGemTest < ActiveSupport::TestCase +class BacktraceCleanerTest < ActiveSupport::TestCase def setup @cleaner = Rails::BacktraceCleaner.new end test "should format installed gems correctly" do - @backtrace = [ "#{Gem.path[0]}/gems/nosuchgem-1.2.3/lib/foo.rb" ] - @result = @cleaner.clean(@backtrace, :all) - assert_equal "nosuchgem (1.2.3) lib/foo.rb", @result[0] + backtrace = [ "#{Gem.path[0]}/gems/nosuchgem-1.2.3/lib/foo.rb" ] + result = @cleaner.clean(backtrace, :all) + assert_equal "nosuchgem (1.2.3) lib/foo.rb", result[0] end test "should format installed gems not in Gem.default_dir correctly" do - @target_dir = Gem.path.detect { |p| p != Gem.default_dir } + target_dir = Gem.path.detect { |p| p != Gem.default_dir } # skip this test if default_dir is the only directory on Gem.path if @target_dir - @backtrace = [ "#{@target_dir}/gems/nosuchgem-1.2.3/lib/foo.rb" ] - @result = @cleaner.clean(@backtrace, :all) - assert_equal "nosuchgem (1.2.3) lib/foo.rb", @result[0] + backtrace = [ "#{target_dir}/gems/nosuchgem-1.2.3/lib/foo.rb" ] + result = @cleaner.clean(backtrace, :all) + assert_equal "nosuchgem (1.2.3) lib/foo.rb", result[0] end end + + test "should consider traces from irb lines as User code" do + backtrace = [ "from (irb):1", + "from /Path/to/rails/railties/lib/rails/commands/console.rb:77:in `start'", + "from bin/rails:4:in `<main>'" ] + result = @cleaner.clean(backtrace, :all) + assert_equal "from (irb):1", result[0] + end end diff --git a/railties/test/code_statistics_calculator_test.rb b/railties/test/code_statistics_calculator_test.rb index cecc3908b3..2dba3c6e96 100644 --- a/railties/test/code_statistics_calculator_test.rb +++ b/railties/test/code_statistics_calculator_test.rb @@ -1,12 +1,12 @@ -require 'abstract_unit' -require 'rails/code_statistics_calculator' +require "abstract_unit" +require "rails/code_statistics_calculator" class CodeStatisticsCalculatorTest < ActiveSupport::TestCase def setup @code_statistics_calculator = CodeStatisticsCalculator.new end - test 'calculate statistics using #add_by_file_path' do + test "calculate statistics using #add_by_file_path" do code = <<-RUBY def foo puts 'foo' @@ -14,7 +14,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase end RUBY - temp_file 'stats.rb', code do |path| + temp_file "stats.rb", code do |path| @code_statistics_calculator.add_by_file_path path assert_equal 4, @code_statistics_calculator.lines @@ -24,7 +24,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase end end - test 'count number of methods in MiniTest file' do + test "count number of methods in MiniTest file" do code = <<-RUBY class FooTest < ActionController::TestCase test 'expectation' do @@ -37,13 +37,13 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase end RUBY - temp_file 'foo_test.rb', code do |path| + temp_file "foo_test.rb", code do |path| @code_statistics_calculator.add_by_file_path path assert_equal 2, @code_statistics_calculator.methods end end - test 'add statistics to another using #add' do + test "add statistics to another using #add" do code_statistics_calculator_1 = CodeStatisticsCalculator.new(1, 2, 3, 4) @code_statistics_calculator.add(code_statistics_calculator_1) @@ -61,7 +61,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase assert_equal 9, @code_statistics_calculator.methods end - test 'accumulate statistics using #add_by_io' do + test "accumulate statistics using #add_by_io" do code_statistics_calculator_1 = CodeStatisticsCalculator.new(1, 2, 3, 4) @code_statistics_calculator.add(code_statistics_calculator_1) @@ -82,7 +82,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase assert_equal 6, @code_statistics_calculator.methods end - test 'calculate number of Ruby methods' do + test "calculate number of Ruby methods" do code = <<-'CODE' def foo puts 'foo' @@ -101,7 +101,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase assert_equal 3, @code_statistics_calculator.methods end - test 'calculate Ruby LOCs' do + test "calculate Ruby LOCs" do code = <<-'CODE' def foo puts 'foo' @@ -119,7 +119,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase assert_equal 5, @code_statistics_calculator.code_lines end - test 'calculate number of Ruby classes' do + test "calculate number of Ruby classes" do code = <<-'CODE' class Foo < Bar def foo @@ -138,7 +138,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase assert_equal 2, @code_statistics_calculator.classes end - test 'skip Ruby comments' do + test "skip Ruby comments" do code = <<-'CODE' =begin class Foo @@ -160,7 +160,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase assert_equal 0, @code_statistics_calculator.methods end - test 'calculate number of JS methods' do + test "calculate number of JS methods" do code = <<-'CODE' function foo(x, y, z) { doX(); @@ -179,7 +179,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase assert_equal 3, @code_statistics_calculator.methods end - test 'calculate JS LOCs' do + test "calculate JS LOCs" do code = <<-'CODE' function foo() alert('foo'); @@ -196,7 +196,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase assert_equal 4, @code_statistics_calculator.code_lines end - test 'skip JS comments' do + test "skip JS comments" do code = <<-'CODE' /* * var f = function () { @@ -216,7 +216,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase assert_equal 0, @code_statistics_calculator.methods end - test 'calculate number of CoffeeScript methods' do + test "calculate number of CoffeeScript methods" do code = <<-'CODE' square = (x) -> x * x @@ -235,7 +235,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase assert_equal 4, @code_statistics_calculator.methods end - test 'calculate CoffeeScript LOCs' do + test "calculate CoffeeScript LOCs" do code = <<-'CODE' # Assignment: number = 42 @@ -256,7 +256,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase assert_equal 3, @code_statistics_calculator.code_lines end - test 'calculate number of CoffeeScript classes' do + test "calculate number of CoffeeScript classes" do code = <<-'CODE' class Animal constructor: (@name) -> @@ -277,7 +277,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase assert_equal 2, @code_statistics_calculator.classes end - test 'skip CoffeeScript comments' do + test "skip CoffeeScript comments" do code = <<-'CODE' ### class Animal @@ -299,7 +299,7 @@ class Animal assert_equal 0, @code_statistics_calculator.methods end - test 'count rake tasks' do + test "count rake tasks" do code = <<-'CODE' task :test_task do puts 'foo' @@ -317,7 +317,7 @@ class Animal private def temp_file(name, content) - dir = File.expand_path '../fixtures/tmp', __FILE__ + dir = File.expand_path "../fixtures/tmp", __FILE__ path = "#{dir}/#{name}" FileUtils.mkdir_p dir diff --git a/railties/test/code_statistics_test.rb b/railties/test/code_statistics_test.rb index 4d80901217..965b6eeb79 100644 --- a/railties/test/code_statistics_test.rb +++ b/railties/test/code_statistics_test.rb @@ -1,10 +1,10 @@ -require 'abstract_unit' -require 'rails/code_statistics' +require "abstract_unit" +require "rails/code_statistics" class CodeStatisticsTest < ActiveSupport::TestCase def setup - @tmp_path = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'tmp')) - @dir_js = File.join(@tmp_path, 'lib.js') + @tmp_path = File.expand_path(File.join(File.dirname(__FILE__), "fixtures", "tmp")) + @dir_js = File.join(@tmp_path, "lib.js") FileUtils.mkdir_p(@dir_js) end @@ -12,22 +12,21 @@ class CodeStatisticsTest < ActiveSupport::TestCase FileUtils.rm_rf(@tmp_path) end - test 'ignores directories that happen to have source files extensions' do + test "ignores directories that happen to have source files extensions" do assert_nothing_raised do - @code_statistics = CodeStatistics.new(['tmp dir', @tmp_path]) + @code_statistics = CodeStatistics.new(["tmp dir", @tmp_path]) end end - test 'ignores hidden files' do - File.write File.join(@tmp_path, '.example.rb'), <<-CODE + test "ignores hidden files" do + File.write File.join(@tmp_path, ".example.rb"), <<-CODE def foo puts 'foo' end CODE assert_nothing_raised do - CodeStatistics.new(['hidden file', @tmp_path]) + CodeStatistics.new(["hidden file", @tmp_path]) end end - end diff --git a/railties/test/commands/console_test.rb b/railties/test/commands/console_test.rb index de0cf0ba9e..4fc082e4ca 100644 --- a/railties/test/commands/console_test.rb +++ b/railties/test/commands/console_test.rb @@ -1,6 +1,7 @@ -require 'abstract_unit' -require 'env_helpers' -require 'rails/commands/console' +require "abstract_unit" +require "env_helpers" +require "rails/command" +require "rails/commands/console/console_command" class Rails::ConsoleTest < ActiveSupport::TestCase include EnvHelpers @@ -40,7 +41,6 @@ class Rails::ConsoleTest < ActiveSupport::TestCase def test_start_with_sandbox start ["--sandbox"] - assert app.console.started? assert app.sandbox assert_match(/Loading \w+ environment in sandbox \(Rails/, output) @@ -64,52 +64,60 @@ class Rails::ConsoleTest < ActiveSupport::TestCase end def test_default_environment_with_rails_env - with_rails_env 'special-production' do + with_rails_env "special-production" do start assert_match(/\sspecial-production\s/, output) end end def test_default_environment_with_rack_env - with_rack_env 'production' do + with_rack_env "production" do start assert_match(/\sproduction\s/, output) end end def test_e_option - start ['-e', 'special-production'] + start ["-e", "special-production"] assert_match(/\sspecial-production\s/, output) end def test_environment_option - start ['--environment=special-production'] + start ["--environment=special-production"] assert_match(/\sspecial-production\s/, output) end def test_rails_env_is_production_when_first_argument_is_p - start ['p'] + start ["p"] assert_match(/\sproduction\s/, output) end def test_rails_env_is_test_when_first_argument_is_t - start ['t'] + start ["t"] assert_match(/\stest\s/, output) end def test_rails_env_is_development_when_argument_is_d - start ['d'] + start ["d"] assert_match(/\sdevelopment\s/, output) end def test_rails_env_is_dev_when_argument_is_dev_and_dev_env_is_present - stubbed_console = Class.new(Rails::Console) do - def available_environments - ['dev'] + Rails::Command::ConsoleCommand.class_eval do + alias_method :old_environments, :available_environments + + define_method :available_environments do + ["dev"] end end - options = stubbed_console.parse_arguments(['dev']) - assert_match('dev', options[:environment]) + + assert_match("dev", parse_arguments(["dev"])[:environment]) + ensure + Rails::Command::ConsoleCommand.class_eval do + undef_method :available_environments + alias_method :available_environments, :old_environments + undef_method :old_environments + end end attr_reader :output @@ -117,38 +125,53 @@ class Rails::ConsoleTest < ActiveSupport::TestCase private - def start(argv = []) - rails_console = Rails::Console.new(app, parse_arguments(argv)) - @output = capture(:stdout) { rails_console.start } - end + def start(argv = []) + rails_console = Rails::Console.new(app, parse_arguments(argv)) + @output = capture(:stdout) { rails_console.start } + end - def app - @app ||= build_app(FakeConsole) - end + def app + @app ||= build_app(FakeConsole) + end - def build_app(console) - mocked_console = Class.new do - attr_reader :sandbox, :console + def build_app(console) + mocked_console = Class.new do + attr_reader :sandbox, :console - def initialize(console) - @console = console - end + def initialize(console) + @console = console + end + + def config + self + end - def config - self + def sandbox=(arg) + @sandbox = arg + end + + def load_console + end end + mocked_console.new(console) + end - def sandbox=(arg) - @sandbox = arg + def parse_arguments(args) + Rails::Command::ConsoleCommand.class_eval do + alias_method :old_perform, :perform + define_method(:perform) do + extract_environment_option_from_argument + + options + end end - def load_console + Rails::Command.invoke(:console, args) + ensure + Rails::Command::ConsoleCommand.class_eval do + undef_method :perform + alias_method :perform, :old_perform + undef_method :old_perform end end - mocked_console.new(console) - end - - def parse_arguments(args) - Rails::Console.parse_arguments(args) - end end diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb index a5aa6c14a2..2ddb269eae 100644 --- a/railties/test/commands/dbconsole_test.rb +++ b/railties/test/commands/dbconsole_test.rb @@ -1,17 +1,16 @@ -require 'abstract_unit' -require 'minitest/mock' -require 'rails/commands/dbconsole' +require "abstract_unit" +require "minitest/mock" +require "rails/command" +require "rails/commands/dbconsole/dbconsole_command" class Rails::DBConsoleTest < ActiveSupport::TestCase - - def setup - Rails::DBConsole.const_set('APP_PATH', 'rails/all') + Rails::DBConsole.const_set("APP_PATH", "rails/all") end def teardown - Rails::DBConsole.send(:remove_const, 'APP_PATH') - %w[PGUSER PGHOST PGPORT PGPASSWORD DATABASE_URL].each{|key| ENV.delete(key)} + Rails::DBConsole.send(:remove_const, "APP_PATH") + %w[PGUSER PGHOST PGPORT PGPASSWORD DATABASE_URL].each { |key| ENV.delete(key) } end def test_config_with_db_config_only @@ -41,7 +40,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase end def test_config_with_database_url_only - ENV['DATABASE_URL'] = 'postgresql://foo:bar@localhost:9000/foo_test?pool=5&timeout=3000' + ENV["DATABASE_URL"] = "postgresql://foo:bar@localhost:9000/foo_test?pool=5&timeout=3000" expected = { "adapter" => "postgresql", "host" => "localhost", @@ -60,7 +59,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase def test_config_choose_database_url_if_exists host = "database-url-host.com" - ENV['DATABASE_URL'] = "postgresql://foo:bar@#{host}:9000/foo_test?pool=5&timeout=3000" + ENV["DATABASE_URL"] = "postgresql://foo:bar@#{host}:9000/foo_test?pool=5&timeout=3000" sample_config = { "test" => { "adapter" => "postgresql", @@ -81,144 +80,138 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase def test_env assert_equal "test", Rails::DBConsole.new.environment - ENV['RAILS_ENV'] = nil - ENV['RACK_ENV'] = nil + ENV["RAILS_ENV"] = nil + ENV["RACK_ENV"] = nil Rails.stub(:respond_to?, false) do assert_equal "development", Rails::DBConsole.new.environment - ENV['RACK_ENV'] = "rack_env" + ENV["RACK_ENV"] = "rack_env" assert_equal "rack_env", Rails::DBConsole.new.environment - ENV['RAILS_ENV'] = "rails_env" + ENV["RAILS_ENV"] = "rails_env" assert_equal "rails_env", Rails::DBConsole.new.environment end ensure - ENV['RAILS_ENV'] = "test" - ENV['RACK_ENV'] = nil + ENV["RAILS_ENV"] = "test" + ENV["RACK_ENV"] = nil end def test_rails_env_is_development_when_argument_is_dev - Rails::DBConsole.stub(:available_environments, ['development', 'test']) do - options = Rails::DBConsole.send(:parse_arguments, ['dev']) - assert_match('development', options[:environment]) + stub_available_environments([ "development", "test" ]) do + assert_match("development", parse_arguments([ "dev" ])[:environment]) end end def test_rails_env_is_dev_when_argument_is_dev_and_dev_env_is_present - Rails::DBConsole.stub(:available_environments, ['dev']) do - options = Rails::DBConsole.send(:parse_arguments, ['dev']) - assert_match('dev', options[:environment]) + stub_available_environments([ "dev" ]) do + assert_match("dev", parse_arguments([ "dev" ])[:environment]) end end def test_mysql - start(adapter: 'mysql2', database: 'db') + start(adapter: "mysql2", database: "db") assert !aborted - assert_equal [%w[mysql mysql5], 'db'], dbconsole.find_cmd_and_exec_args + assert_equal [%w[mysql mysql5], "db"], dbconsole.find_cmd_and_exec_args end def test_mysql_full - start(adapter: 'mysql2', database: 'db', host: 'locahost', port: 1234, socket: 'socket', username: 'user', password: 'qwerty', encoding: 'UTF-8') + start(adapter: "mysql2", database: "db", host: "locahost", port: 1234, socket: "socket", username: "user", password: "qwerty", encoding: "UTF-8") assert !aborted - assert_equal [%w[mysql mysql5], '--host=locahost', '--port=1234', '--socket=socket', '--user=user', '--default-character-set=UTF-8', '-p', 'db'], dbconsole.find_cmd_and_exec_args + assert_equal [%w[mysql mysql5], "--host=locahost", "--port=1234", "--socket=socket", "--user=user", "--default-character-set=UTF-8", "-p", "db"], dbconsole.find_cmd_and_exec_args end def test_mysql_include_password - start({adapter: 'mysql2', database: 'db', username: 'user', password: 'qwerty'}, ['-p']) + start({ adapter: "mysql2", database: "db", username: "user", password: "qwerty" }, ["-p"]) assert !aborted - assert_equal [%w[mysql mysql5], '--user=user', '--password=qwerty', 'db'], dbconsole.find_cmd_and_exec_args + assert_equal [%w[mysql mysql5], "--user=user", "--password=qwerty", "db"], dbconsole.find_cmd_and_exec_args end def test_postgresql - start(adapter: 'postgresql', database: 'db') + start(adapter: "postgresql", database: "db") assert !aborted - assert_equal ['psql', 'db'], dbconsole.find_cmd_and_exec_args + assert_equal ["psql", "db"], dbconsole.find_cmd_and_exec_args end def test_postgresql_full - start(adapter: 'postgresql', database: 'db', username: 'user', password: 'q1w2e3', host: 'host', port: 5432) + start(adapter: "postgresql", database: "db", username: "user", password: "q1w2e3", host: "host", port: 5432) assert !aborted - assert_equal ['psql', 'db'], dbconsole.find_cmd_and_exec_args - assert_equal 'user', ENV['PGUSER'] - assert_equal 'host', ENV['PGHOST'] - assert_equal '5432', ENV['PGPORT'] - assert_not_equal 'q1w2e3', ENV['PGPASSWORD'] + assert_equal ["psql", "db"], dbconsole.find_cmd_and_exec_args + assert_equal "user", ENV["PGUSER"] + assert_equal "host", ENV["PGHOST"] + assert_equal "5432", ENV["PGPORT"] + assert_not_equal "q1w2e3", ENV["PGPASSWORD"] end def test_postgresql_include_password - start({adapter: 'postgresql', database: 'db', username: 'user', password: 'q1w2e3'}, ['-p']) + start({ adapter: "postgresql", database: "db", username: "user", password: "q1w2e3" }, ["-p"]) assert !aborted - assert_equal ['psql', 'db'], dbconsole.find_cmd_and_exec_args - assert_equal 'user', ENV['PGUSER'] - assert_equal 'q1w2e3', ENV['PGPASSWORD'] + assert_equal ["psql", "db"], dbconsole.find_cmd_and_exec_args + assert_equal "user", ENV["PGUSER"] + assert_equal "q1w2e3", ENV["PGPASSWORD"] end def test_sqlite3 - start(adapter: 'sqlite3', database: 'db.sqlite3') + start(adapter: "sqlite3", database: "db.sqlite3") assert !aborted - assert_equal ['sqlite3', Rails.root.join('db.sqlite3').to_s], dbconsole.find_cmd_and_exec_args + assert_equal ["sqlite3", Rails.root.join("db.sqlite3").to_s], dbconsole.find_cmd_and_exec_args end def test_sqlite3_mode - start({adapter: 'sqlite3', database: 'db.sqlite3'}, ['--mode', 'html']) + start({ adapter: "sqlite3", database: "db.sqlite3" }, ["--mode", "html"]) assert !aborted - assert_equal ['sqlite3', '-html', Rails.root.join('db.sqlite3').to_s], dbconsole.find_cmd_and_exec_args + assert_equal ["sqlite3", "-html", Rails.root.join("db.sqlite3").to_s], dbconsole.find_cmd_and_exec_args end def test_sqlite3_header - start({adapter: 'sqlite3', database: 'db.sqlite3'}, ['--header']) - assert_equal ['sqlite3', '-header', Rails.root.join('db.sqlite3').to_s], dbconsole.find_cmd_and_exec_args + start({ adapter: "sqlite3", database: "db.sqlite3" }, ["--header"]) + assert_equal ["sqlite3", "-header", Rails.root.join("db.sqlite3").to_s], dbconsole.find_cmd_and_exec_args end def test_sqlite3_db_absolute_path - start(adapter: 'sqlite3', database: '/tmp/db.sqlite3') + start(adapter: "sqlite3", database: "/tmp/db.sqlite3") assert !aborted - assert_equal ['sqlite3', '/tmp/db.sqlite3'], dbconsole.find_cmd_and_exec_args + assert_equal ["sqlite3", "/tmp/db.sqlite3"], dbconsole.find_cmd_and_exec_args end def test_sqlite3_db_without_defined_rails_root Rails.stub(:respond_to?, false) do - start(adapter: 'sqlite3', database: 'config/db.sqlite3') + start(adapter: "sqlite3", database: "config/db.sqlite3") assert !aborted - assert_equal ['sqlite3', Rails.root.join('../config/db.sqlite3').to_s], dbconsole.find_cmd_and_exec_args + assert_equal ["sqlite3", Rails.root.join("../config/db.sqlite3").to_s], dbconsole.find_cmd_and_exec_args end end def test_oracle - start(adapter: 'oracle', database: 'db', username: 'user', password: 'secret') + start(adapter: "oracle", database: "db", username: "user", password: "secret") assert !aborted - assert_equal ['sqlplus', 'user@db'], dbconsole.find_cmd_and_exec_args + assert_equal ["sqlplus", "user@db"], dbconsole.find_cmd_and_exec_args end def test_oracle_include_password - start({adapter: 'oracle', database: 'db', username: 'user', password: 'secret'}, ['-p']) + start({ adapter: "oracle", database: "db", username: "user", password: "secret" }, ["-p"]) assert !aborted - assert_equal ['sqlplus', 'user/secret@db'], dbconsole.find_cmd_and_exec_args + assert_equal ["sqlplus", "user/secret@db"], dbconsole.find_cmd_and_exec_args end def test_unknown_command_line_client - start(adapter: 'unknown', database: 'db') + start(adapter: "unknown", database: "db") assert aborted assert_match(/Unknown command-line client for db/, output) end def test_print_help_short stdout = capture(:stdout) do - start({}, ['-h']) + Rails::Command.invoke(:dbconsole, ["-h"]) end - assert aborted - assert_equal '', output - assert_match(/Usage:.*dbconsole/, stdout) + assert_match(/bin\/rails dbconsole \[environment\]/, stdout) end def test_print_help_long stdout = capture(:stdout) do - start({}, ['--help']) + Rails::Command.invoke(:dbconsole, ["--help"]) end - assert aborted - assert_equal '', output - assert_match(/Usage:.*dbconsole/, stdout) + assert_match(/bin\/rails dbconsole \[environment\]/, stdout) end attr_reader :aborted, :output @@ -226,39 +219,76 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase private - def app_db_config(results) - Rails.application.config.stub(:database_configuration, results || {}) do - yield + def app_db_config(results) + Rails.application.config.stub(:database_configuration, results || {}) do + yield + end end - end - def dbconsole - @dbconsole ||= Class.new(Rails::DBConsole) do - attr_reader :find_cmd_and_exec_args + def make_dbconsole + Class.new(Rails::DBConsole) do + attr_reader :find_cmd_and_exec_args - def find_cmd_and_exec(*args) - @find_cmd_and_exec_args = args + def find_cmd_and_exec(*args) + @find_cmd_and_exec_args = args + end end - end.new(nil) - end + end - def start(config = {}, argv = []) - dbconsole.stub(:config, config.stringify_keys) do - dbconsole.stub(:arguments, argv) do - capture_abort { dbconsole.start } + attr_reader :dbconsole + + def start(config = {}, argv = []) + @dbconsole = make_dbconsole.new(parse_arguments(argv)) + @dbconsole.stub(:config, config.stringify_keys) do + capture_abort { @dbconsole.start } end end - end - def capture_abort - @aborted = false - @output = capture(:stderr) do - begin - yield - rescue SystemExit - @aborted = true + def capture_abort + @aborted = false + @output = capture(:stderr) do + begin + yield + rescue SystemExit + @aborted = true + end end end - end + def stub_available_environments(environments) + Rails::Command::DbconsoleCommand.class_eval do + alias_method :old_environments, :available_environments + + define_method :available_environments do + environments + end + end + + yield + ensure + Rails::Command::DbconsoleCommand.class_eval do + undef_method :available_environments + alias_method :available_environments, :old_environments + undef_method :old_environments + end + end + + def parse_arguments(args) + Rails::Command::DbconsoleCommand.class_eval do + alias_method :old_perform, :perform + define_method(:perform) do + extract_environment_option_from_argument + + options + end + end + + Rails::Command.invoke(:dbconsole, args) + ensure + Rails::Command::DbconsoleCommand.class_eval do + undef_method :perform + alias_method :perform, :old_perform + undef_method :old_perform + end + end end diff --git a/railties/test/commands/server_test.rb b/railties/test/commands/server_test.rb index 38a1605d1f..391886bf33 100644 --- a/railties/test/commands/server_test.rb +++ b/railties/test/commands/server_test.rb @@ -1,6 +1,7 @@ -require 'abstract_unit' -require 'env_helpers' -require 'rails/commands/server' +require "abstract_unit" +require "env_helpers" +require "rails/command" +require "rails/commands/server/server_command" class Rails::ServerTest < ActiveSupport::TestCase include EnvHelpers @@ -8,14 +9,14 @@ class Rails::ServerTest < ActiveSupport::TestCase def test_environment_with_server_option args = ["thin", "-e", "production"] options = Rails::Server::Options.new.parse!(args) - assert_equal 'production', options[:environment] - assert_equal 'thin', options[:server] + assert_equal "production", options[:environment] + assert_equal "thin", options[:server] end def test_environment_without_server_option args = ["-e", "production"] options = Rails::Server::Options.new.parse!(args) - assert_equal 'production', options[:environment] + assert_equal "production", options[:environment] assert_nil options[:server] end @@ -23,23 +24,23 @@ class Rails::ServerTest < ActiveSupport::TestCase args = ["thin"] options = Rails::Server::Options.new.parse!(args) assert_nil options[:environment] - assert_equal 'thin', options[:server] + assert_equal "thin", options[:server] end def test_environment_with_rails_env with_rack_env nil do - with_rails_env 'production' do + with_rails_env "production" do server = Rails::Server.new - assert_equal 'production', server.options[:environment] + assert_equal "production", server.options[:environment] end end end def test_environment_with_rack_env with_rails_env nil do - with_rack_env 'production' do + with_rack_env "production" do server = Rails::Server.new - assert_equal 'production', server.options[:environment] + assert_equal "production", server.options[:environment] end end end @@ -51,6 +52,13 @@ class Rails::ServerTest < ActiveSupport::TestCase end end + def test_environment_with_host + switch_env "HOST", "1.2.3.4" do + server = Rails::Server.new + assert_equal "1.2.3.4", server.options[:Host] + end + end + def test_caching_without_option args = [] options = Rails::Server::Options.new.parse!(args) @@ -83,25 +91,25 @@ class Rails::ServerTest < ActiveSupport::TestCase options = Rails::Server::Options.new.parse!(args) assert_equal false, options[:log_stdout] - with_rack_env 'development' do + with_rack_env "development" do args = [] options = Rails::Server::Options.new.parse!(args) assert_equal true, options[:log_stdout] end - with_rack_env 'production' do + with_rack_env "production" do args = [] options = Rails::Server::Options.new.parse!(args) assert_equal false, options[:log_stdout] end - with_rails_env 'development' do + with_rails_env "development" do args = [] options = Rails::Server::Options.new.parse!(args) assert_equal true, options[:log_stdout] end - with_rails_env 'production' do + with_rails_env "production" do args = [] options = Rails::Server::Options.new.parse!(args) assert_equal false, options[:log_stdout] diff --git a/railties/test/configuration/middleware_stack_proxy_test.rb b/railties/test/configuration/middleware_stack_proxy_test.rb index d5072614cf..559ce72693 100644 --- a/railties/test/configuration/middleware_stack_proxy_test.rb +++ b/railties/test/configuration/middleware_stack_proxy_test.rb @@ -1,8 +1,8 @@ -require 'active_support' -require 'active_support/testing/autorun' -require 'rails/configuration' -require 'active_support/test_case' -require 'minitest/mock' +require "active_support" +require "active_support/testing/autorun" +require "rails/configuration" +require "active_support/test_case" +require "minitest/mock" module Rails module Configuration @@ -50,12 +50,12 @@ module Rails private - def assert_playback(msg_name, args) - mock = Minitest::Mock.new - mock.expect :send, nil, [msg_name, args] - @stack.merge_into(mock) - mock.verify - end + def assert_playback(msg_name, args) + mock = Minitest::Mock.new + mock.expect :send, nil, [msg_name, args] + @stack.merge_into(mock) + mock.verify + end end end end diff --git a/railties/test/engine/commands_tasks_test.rb b/railties/test/engine/commands_tasks_test.rb new file mode 100644 index 0000000000..817175b9ef --- /dev/null +++ b/railties/test/engine/commands_tasks_test.rb @@ -0,0 +1,24 @@ +require "abstract_unit" + +class Rails::Engine::CommandsTasksTest < ActiveSupport::TestCase + def setup + @destination_root = Dir.mktmpdir("bukkits") + Dir.chdir(@destination_root) { `bundle exec rails plugin new bukkits --mountable` } + end + + def teardown + FileUtils.rm_rf(@destination_root) + end + + def test_help_command_work_inside_engine + output = capture(:stderr) do + Dir.chdir(plugin_path) { `bin/rails --help` } + end + assert_no_match "NameError", output + end + + private + def plugin_path + "#{@destination_root}/bukkits" + end +end diff --git a/railties/test/engine_test.rb b/railties/test/engine_test.rb index f46fb748f5..248afa2d2c 100644 --- a/railties/test/engine_test.rb +++ b/railties/test/engine_test.rb @@ -1,4 +1,4 @@ -require 'abstract_unit' +require "abstract_unit" class EngineTest < ActiveSupport::TestCase test "reports routes as available only if they're actually present" do diff --git a/railties/test/env_helpers.rb b/railties/test/env_helpers.rb index 330fe150ca..1f64d5fda3 100644 --- a/railties/test/env_helpers.rb +++ b/railties/test/env_helpers.rb @@ -1,30 +1,30 @@ -require 'rails' +require "rails" module EnvHelpers private - def with_rails_env(env) - Rails.instance_variable_set :@_env, nil - switch_env 'RAILS_ENV', env do - switch_env 'RACK_ENV', nil do - yield + def with_rails_env(env) + Rails.instance_variable_set :@_env, nil + switch_env "RAILS_ENV", env do + switch_env "RACK_ENV", nil do + yield + end end end - end - def with_rack_env(env) - Rails.instance_variable_set :@_env, nil - switch_env 'RACK_ENV', env do - switch_env 'RAILS_ENV', nil do - yield + def with_rack_env(env) + Rails.instance_variable_set :@_env, nil + switch_env "RACK_ENV", env do + switch_env "RAILS_ENV", nil do + yield + end end end - end - def switch_env(key, value) - old, ENV[key] = ENV[key], value - yield - ensure - ENV[key] = old - end + def switch_env(key, value) + old, ENV[key] = ENV[key], value + yield + ensure + ENV[key] = old + end end diff --git a/railties/test/fixtures/about_yml_plugins/bad_about_yml/init.rb b/railties/test/fixtures/about_yml_plugins/bad_about_yml/init.rb index d4262f8971..636bc1a8ab 100644 --- a/railties/test/fixtures/about_yml_plugins/bad_about_yml/init.rb +++ b/railties/test/fixtures/about_yml_plugins/bad_about_yml/init.rb @@ -1 +1 @@ -# intentionally empty
\ No newline at end of file +# intentionally empty diff --git a/railties/test/fixtures/about_yml_plugins/plugin_without_about_yml/init.rb b/railties/test/fixtures/about_yml_plugins/plugin_without_about_yml/init.rb index d4262f8971..636bc1a8ab 100644 --- a/railties/test/fixtures/about_yml_plugins/plugin_without_about_yml/init.rb +++ b/railties/test/fixtures/about_yml_plugins/plugin_without_about_yml/init.rb @@ -1 +1 @@ -# intentionally empty
\ No newline at end of file +# intentionally empty diff --git a/railties/test/fixtures/lib/generators/active_record/fixjour_generator.rb b/railties/test/fixtures/lib/generators/active_record/fixjour_generator.rb index a7d079a1bc..1139350b94 100644 --- a/railties/test/fixtures/lib/generators/active_record/fixjour_generator.rb +++ b/railties/test/fixtures/lib/generators/active_record/fixjour_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators/active_record' +require "rails/generators/active_record" module ActiveRecord module Generators diff --git a/railties/test/fixtures/lib/generators/model_generator.rb b/railties/test/fixtures/lib/generators/model_generator.rb index 9098a8a354..0905fa9631 100644 --- a/railties/test/fixtures/lib/generators/model_generator.rb +++ b/railties/test/fixtures/lib/generators/model_generator.rb @@ -1 +1 @@ -raise "I should never be loaded"
\ No newline at end of file +raise "I should never be loaded" diff --git a/railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb b/railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb index 078b0f9412..21b0ff6c28 100644 --- a/railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb +++ b/railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb @@ -1,4 +1,4 @@ -require 'rails/generators' +require "rails/generators" class UsageTemplateGenerator < Rails::Generators::Base source_root File.expand_path("templates", File.dirname(__FILE__)) diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb index 3b2b3c37d0..0a26897a4d 100644 --- a/railties/test/generators/actions_test.rb +++ b/railties/test/generators/actions_test.rb @@ -1,6 +1,6 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/app/app_generator' -require 'env_helpers' +require "generators/generators_test_helper" +require "rails/generators/rails/app/app_generator" +require "env_helpers" class ActionsTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -19,98 +19,98 @@ class ActionsTest < Rails::Generators::TestCase end def test_invoke_other_generator_with_shortcut - action :invoke, 'model', ['my_model'] - assert_file 'app/models/my_model.rb', /MyModel/ + action :invoke, "model", ["my_model"] + assert_file "app/models/my_model.rb", /MyModel/ end def test_invoke_other_generator_with_full_namespace - action :invoke, 'rails:model', ['my_model'] - assert_file 'app/models/my_model.rb', /MyModel/ + action :invoke, "rails:model", ["my_model"] + assert_file "app/models/my_model.rb", /MyModel/ end def test_create_file_should_write_data_to_file_path - action :create_file, 'lib/test_file.rb', 'heres test data' - assert_file 'lib/test_file.rb', 'heres test data' + action :create_file, "lib/test_file.rb", "heres test data" + assert_file "lib/test_file.rb", "heres test data" end def test_create_file_should_write_block_contents_to_file_path - action(:create_file, 'lib/test_file.rb'){ 'heres block data' } - assert_file 'lib/test_file.rb', 'heres block data' + action(:create_file, "lib/test_file.rb") { "heres block data" } + assert_file "lib/test_file.rb", "heres block data" end def test_add_source_adds_source_to_gemfile run_generator - action :add_source, 'http://gems.github.com' - assert_file 'Gemfile', /source 'http:\/\/gems\.github\.com'/ + action :add_source, "http://gems.github.com" + assert_file "Gemfile", /source 'http:\/\/gems\.github\.com'/ end def test_add_source_with_block_adds_source_to_gemfile_with_gem run_generator - action :add_source, 'http://gems.github.com' do - gem 'rspec-rails' + action :add_source, "http://gems.github.com" do + gem "rspec-rails" end - assert_file 'Gemfile', /source 'http:\/\/gems\.github\.com' do\n gem 'rspec-rails'\nend/ + assert_file "Gemfile", /source 'http:\/\/gems\.github\.com' do\n gem 'rspec-rails'\nend/ end def test_add_source_with_block_adds_source_to_gemfile_after_gem run_generator - action :gem, 'will-paginate' - action :add_source, 'http://gems.github.com' do - gem 'rspec-rails' + action :gem, "will-paginate" + action :add_source, "http://gems.github.com" do + gem "rspec-rails" end - assert_file 'Gemfile', /gem 'will-paginate'\nsource 'http:\/\/gems\.github\.com' do\n gem 'rspec-rails'\nend/ + assert_file "Gemfile", /gem 'will-paginate'\nsource 'http:\/\/gems\.github\.com' do\n gem 'rspec-rails'\nend/ end def test_gem_should_put_gem_dependency_in_gemfile run_generator - action :gem, 'will-paginate' - assert_file 'Gemfile', /gem 'will\-paginate'/ + action :gem, "will-paginate" + assert_file "Gemfile", /gem 'will\-paginate'/ end def test_gem_with_version_should_include_version_in_gemfile run_generator - action :gem, 'rspec', '>=2.0.0.a5' + action :gem, "rspec", ">=2.0.0.a5" - assert_file 'Gemfile', /gem 'rspec', '>=2.0.0.a5'/ + assert_file "Gemfile", /gem 'rspec', '>=2.0.0.a5'/ end def test_gem_should_insert_on_separate_lines run_generator - File.open('Gemfile', 'a') {|f| f.write('# Some content...') } + File.open("Gemfile", "a") { |f| f.write("# Some content...") } - action :gem, 'rspec' - action :gem, 'rspec-rails' + action :gem, "rspec" + action :gem, "rspec-rails" - assert_file 'Gemfile', /^gem 'rspec'$/ - assert_file 'Gemfile', /^gem 'rspec-rails'$/ + assert_file "Gemfile", /^gem 'rspec'$/ + assert_file "Gemfile", /^gem 'rspec-rails'$/ end def test_gem_should_include_options run_generator - action :gem, 'rspec', github: 'dchelimsky/rspec', tag: '1.2.9.rc1' + action :gem, "rspec", github: "dchelimsky/rspec", tag: "1.2.9.rc1" - assert_file 'Gemfile', /gem 'rspec', github: 'dchelimsky\/rspec', tag: '1\.2\.9\.rc1'/ + 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] + 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\]$/ + 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 - action :gem, 'rspec', ">=2.0'0" + action :gem, "rspec", ">=2.0'0" - assert_file 'Gemfile', /^gem 'rspec', ">=2\.0'0"$/ + assert_file "Gemfile", /^gem 'rspec', ">=2\.0'0"$/ end def test_gem_works_even_if_frozen_string_is_passed_as_argument @@ -118,34 +118,34 @@ class ActionsTest < Rails::Generators::TestCase action :gem, "frozen_gem".freeze, "1.0.0".freeze - assert_file 'Gemfile', /^gem 'frozen_gem', '1.0.0'$/ + assert_file "Gemfile", /^gem 'frozen_gem', '1.0.0'$/ end def test_gem_group_should_wrap_gems_in_a_group run_generator action :gem_group, :development, :test do - gem 'rspec-rails' + gem "rspec-rails" end action :gem_group, :test do - gem 'fakeweb' + gem "fakeweb" end - assert_file 'Gemfile', /\ngroup :development, :test do\n gem 'rspec-rails'\nend\n\ngroup :test do\n gem 'fakeweb'\nend/ + assert_file "Gemfile", /\ngroup :development, :test do\n gem 'rspec-rails'\nend\n\ngroup :test do\n gem 'fakeweb'\nend/ end def test_environment_should_include_data_in_environment_initializer_block run_generator autoload_paths = 'config.autoload_paths += %w["#{Rails.root}/app/extras"]' action :environment, autoload_paths - assert_file 'config/application.rb', / class Application < Rails::Application\n #{Regexp.escape(autoload_paths)}/ + assert_file "config/application.rb", / class Application < Rails::Application\n #{Regexp.escape(autoload_paths)}/ end def test_environment_should_include_data_in_environment_initializer_block_with_env_option run_generator autoload_paths = 'config.autoload_paths += %w["#{Rails.root}/app/extras"]' - action :environment, autoload_paths, env: 'development' + action :environment, autoload_paths, env: "development" assert_file "config/environments/development.rb", /Rails\.application\.configure do\n #{Regexp.escape(autoload_paths)}/ end @@ -153,80 +153,80 @@ class ActionsTest < Rails::Generators::TestCase run_generator action :environment do - _ = '# This wont be added'# assignment to silence parse-time warning "unused literal ignored" - '# This will be added' + _ = "# This wont be added"# assignment to silence parse-time warning "unused literal ignored" + "# This will be added" end - assert_file 'config/application.rb' do |content| + assert_file "config/application.rb" do |content| assert_match(/# This will be added/, content) assert_no_match(/# This wont be added/, content) end end def test_git_with_symbol_should_run_command_using_git_scm - assert_called_with(generator, :run, ['git init']) do + assert_called_with(generator, :run, ["git init"]) do action :git, :init end end def test_git_with_hash_should_run_each_command_using_git_scm assert_called_with(generator, :run, [ ["git rm README"], ["git add ."] ]) do - action :git, rm: 'README', add: '.' + action :git, rm: "README", add: "." end end def test_vendor_should_write_data_to_file_in_vendor - action :vendor, 'vendor_file.rb', '# vendor data' - assert_file 'vendor/vendor_file.rb', '# vendor data' + action :vendor, "vendor_file.rb", "# vendor data" + assert_file "vendor/vendor_file.rb", "# vendor data" end def test_lib_should_write_data_to_file_in_lib - action :lib, 'my_library.rb', 'class MyLibrary' - assert_file 'lib/my_library.rb', 'class MyLibrary' + action :lib, "my_library.rb", "class MyLibrary" + assert_file "lib/my_library.rb", "class MyLibrary" end def test_rakefile_should_write_date_to_file_in_lib_tasks - action :rakefile, 'myapp.rake', 'task run: [:environment]' - assert_file 'lib/tasks/myapp.rake', 'task run: [:environment]' + action :rakefile, "myapp.rake", "task run: [:environment]" + assert_file "lib/tasks/myapp.rake", "task run: [:environment]" end def test_initializer_should_write_date_to_file_in_config_initializers - action :initializer, 'constants.rb', 'MY_CONSTANT = 42' - assert_file 'config/initializers/constants.rb', 'MY_CONSTANT = 42' + action :initializer, "constants.rb", "MY_CONSTANT = 42" + assert_file "config/initializers/constants.rb", "MY_CONSTANT = 42" end def test_generate_should_run_script_generate_with_argument_and_options - assert_called_with(generator, :run_ruby_script, ['bin/rails generate model MyModel', verbose: false]) do - action :generate, 'model', 'MyModel' + assert_called_with(generator, :run_ruby_script, ["bin/rails generate model MyModel", verbose: false]) do + action :generate, "model", "MyModel" end end def test_rails_should_run_rake_command_with_default_env assert_called_with(generator, :run, ["rake log:clear RAILS_ENV=development", verbose: false]) do with_rails_env nil do - action :rake, 'log:clear' + action :rake, "log:clear" end end end def test_rails_with_env_option_should_run_rake_command_in_env - assert_called_with(generator, :run, ['rake log:clear RAILS_ENV=production', verbose: false]) do - action :rake, 'log:clear', env: 'production' + assert_called_with(generator, :run, ["rake log:clear RAILS_ENV=production", verbose: false]) do + action :rake, "log:clear", env: "production" end end test "rails command with RAILS_ENV variable should run rake command in env" do - assert_called_with(generator, :run, ['rake log:clear RAILS_ENV=production', verbose: false]) do + assert_called_with(generator, :run, ["rake log:clear RAILS_ENV=production", verbose: false]) do with_rails_env "production" do - action :rake, 'log:clear' + action :rake, "log:clear" end end end test "env option should win over RAILS_ENV variable when running rake" do - assert_called_with(generator, :run, ['rake log:clear RAILS_ENV=production', verbose: false]) do + assert_called_with(generator, :run, ["rake log:clear RAILS_ENV=production", verbose: false]) do with_rails_env "staging" do - action :rake, 'log:clear', env: 'production' + action :rake, "log:clear", env: "production" end end end @@ -234,7 +234,7 @@ class ActionsTest < Rails::Generators::TestCase test "rails command with sudo option should run rake command with sudo" do assert_called_with(generator, :run, ["sudo rake log:clear RAILS_ENV=development", verbose: false]) do with_rails_env nil do - action :rake, 'log:clear', sudo: true + action :rake, "log:clear", sudo: true end end end @@ -242,29 +242,29 @@ class ActionsTest < Rails::Generators::TestCase test "rails command should run rails_command with default env" do assert_called_with(generator, :run, ["rails log:clear RAILS_ENV=development", verbose: false]) do with_rails_env nil do - action :rails_command, 'log:clear' + action :rails_command, "log:clear" end end end test "rails command with env option should run rails_command with same env" do - assert_called_with(generator, :run, ['rails log:clear RAILS_ENV=production', verbose: false]) do - action :rails_command, 'log:clear', env: 'production' + assert_called_with(generator, :run, ["rails log:clear RAILS_ENV=production", verbose: false]) do + action :rails_command, "log:clear", env: "production" end end test "rails command with RAILS_ENV variable should run rails_command in env" do - assert_called_with(generator, :run, ['rails log:clear RAILS_ENV=production', verbose: false]) do + assert_called_with(generator, :run, ["rails log:clear RAILS_ENV=production", verbose: false]) do with_rails_env "production" do - action :rails_command, 'log:clear' + action :rails_command, "log:clear" end end end def test_env_option_should_win_over_rails_env_variable_when_running_rails - assert_called_with(generator, :run, ['rails log:clear RAILS_ENV=production', verbose: false]) do + assert_called_with(generator, :run, ["rails log:clear RAILS_ENV=production", verbose: false]) do with_rails_env "staging" do - action :rails_command, 'log:clear', env: 'production' + action :rails_command, "log:clear", env: "production" end end end @@ -272,13 +272,13 @@ class ActionsTest < Rails::Generators::TestCase test "rails command with sudo option should run rails_command with sudo" do assert_called_with(generator, :run, ["sudo rails log:clear RAILS_ENV=development", verbose: false]) do with_rails_env nil do - action :rails_command, 'log:clear', sudo: true + action :rails_command, "log:clear", sudo: true end end end def test_capify_should_run_the_capify_command - assert_called_with(generator, :run, ['capify .', verbose: false]) do + assert_called_with(generator, :run, ["capify .", verbose: false]) do action :capify! end end @@ -287,12 +287,12 @@ class ActionsTest < Rails::Generators::TestCase run_generator route_command = "route '/login', controller: 'sessions', action: 'new'" action :route, route_command - assert_file 'config/routes.rb', /#{Regexp.escape(route_command)}/ + assert_file "config/routes.rb", /#{Regexp.escape(route_command)}/ end def test_route_should_be_idempotent run_generator - route_path = File.expand_path('config/routes.rb', destination_root) + route_path = File.expand_path("config/routes.rb", destination_root) # runs first time, not asserting action :route, "root 'welcome#index'" @@ -312,8 +312,8 @@ class ActionsTest < Rails::Generators::TestCase content = File.read(route_path) # Remove all of the comments and blank lines from the routes file - content.gsub!(/^ \#.*\n/, '') - content.gsub!(/^\n/, '') + content.gsub!(/^ \#.*\n/, "") + content.gsub!(/^\n/, "") File.open(route_path, "wb") { |file| file.write(content) } @@ -372,7 +372,6 @@ F protected def action(*args, &block) - capture(:stdout){ generator.send(*args, &block) } + capture(:stdout) { generator.send(*args, &block) } end - end diff --git a/railties/test/generators/api_app_generator_test.rb b/railties/test/generators/api_app_generator_test.rb index 8e1cd0891a..bbb814ef4e 100644 --- a/railties/test/generators/api_app_generator_test.rb +++ b/railties/test/generators/api_app_generator_test.rb @@ -1,11 +1,11 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/app/app_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/app/app_generator" class ApiAppGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper tests Rails::Generators::AppGenerator - arguments [destination_root, '--api'] + arguments [destination_root, "--api"] def setup Rails.application = TestApp::Application @@ -62,49 +62,61 @@ class ApiAppGeneratorTest < Rails::Generators::TestCase end end - private + def test_generator_skips_per_form_csrf_token_and_origin_check_configs_for_api_apps + run_generator - def default_files - files = %W( - .gitignore - Gemfile - Rakefile - config.ru - app/controllers - app/mailers - app/models - app/views/layouts/mailer.html.erb - app/views/layouts/mailer.text.erb - config/environments - config/initializers - config/locales - db - lib - lib/tasks - log - test/fixtures - test/controllers - test/integration - test/models - tmp - vendor - ) - files.concat %w(bin/bundle bin/rails bin/rake) - files + assert_file "config/initializers/new_framework_defaults.rb" do |initializer_content| + assert_no_match(/per_form_csrf_tokens/, initializer_content) + assert_no_match(/forgery_protection_origin_check/, initializer_content) + end end - def skipped_files - %w(app/assets - app/helpers - app/views/layouts/application.html.erb - config/initializers/assets.rb - config/initializers/cookies_serializer.rb - config/initializers/session_store.rb - config/initializers/request_forgery_protection.rb - config/initializers/per_form_csrf_tokens.rb - lib/assets - vendor/assets - test/helpers - tmp/cache/assets) - end + private + + def default_files + files = %W( + .gitignore + Gemfile + Rakefile + config.ru + app/controllers + app/mailers + app/models + app/views/layouts/mailer.html.erb + app/views/layouts/mailer.text.erb + config/environments + config/initializers + config/locales + db + lib + lib/tasks + log + test/fixtures + test/controllers + test/integration + test/models + tmp + vendor + ) + files.concat %w(bin/bundle bin/rails bin/rake) + files + end + + def skipped_files + %w(app/assets + app/helpers + app/views/layouts/application.html.erb + config/initializers/assets.rb + config/initializers/cookies_serializer.rb + lib/assets + vendor/assets + test/helpers + tmp/cache/assets + public/404.html + public/422.html + public/500.html + public/apple-touch-icon-precomposed.png + public/apple-touch-icon.png + public/favicon.ico) + end end diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 25a8635e7d..8f7fa1155f 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -1,6 +1,6 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/app/app_generator' -require 'generators/shared_generator_tests' +require "generators/generators_test_helper" +require "rails/generators/rails/app/app_generator" +require "generators/shared_generator_tests" DEFAULT_APP_FILES = %w( .gitignore @@ -77,7 +77,7 @@ class AppGeneratorTest < Rails::Generators::TestCase end def test_invalid_application_name_raises_an_error - content = capture(:stderr){ run_generator [File.join(destination_root, "43-things")] } + content = capture(:stderr) { run_generator [File.join(destination_root, "43-things")] } assert_equal "Invalid application name 43-things. Please give a name which does not start with numbers.\n", content end @@ -88,12 +88,12 @@ class AppGeneratorTest < Rails::Generators::TestCase end def test_application_new_exits_with_non_zero_code_on_invalid_application_name - quietly { system 'rails new test --no-rc' } + quietly { system "rails new test --no-rc" } assert_equal false, $?.success? end def test_application_new_exits_with_message_and_non_zero_code_when_generating_inside_existing_rails_directory - app_root = File.join(destination_root, 'myfirstapp') + app_root = File.join(destination_root, "myfirstapp") run_generator [app_root] output = nil Dir.chdir(app_root) do @@ -104,7 +104,7 @@ class AppGeneratorTest < Rails::Generators::TestCase end def test_application_new_show_help_message_inside_existing_rails_directory - app_root = File.join(destination_root, 'myfirstapp') + app_root = File.join(destination_root, "myfirstapp") run_generator [app_root] output = Dir.chdir(app_root) do `rails new --help` @@ -131,20 +131,18 @@ class AppGeneratorTest < Rails::Generators::TestCase generator.send(:app_const) quietly { generator.send(:update_config_files) } assert_file "myapp_moved/config/environment.rb", /Rails\.application\.initialize!/ - assert_file "myapp_moved/config/initializers/session_store.rb", /_myapp_session/ end end end def test_rails_update_generates_correct_session_key - app_root = File.join(destination_root, 'myapp') + app_root = File.join(destination_root, "myapp") run_generator [app_root] stub_rails_application(app_root) do generator = Rails::Generators::AppGenerator.new ["rails"], [], destination_root: app_root, shell: @shell generator.send(:app_const) quietly { generator.send(:update_config_files) } - assert_file "myapp/config/initializers/session_store.rb", /_myapp_session/ end end @@ -157,11 +155,11 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_new_application_not_include_api_initializers run_generator - assert_no_file 'config/initializers/cors.rb' + assert_no_file "config/initializers/cors.rb" end def test_rails_update_keep_the_cookie_serializer_if_it_is_already_configured - app_root = File.join(destination_root, 'myapp') + app_root = File.join(destination_root, "myapp") run_generator [app_root] stub_rails_application(app_root) do @@ -172,36 +170,8 @@ class AppGeneratorTest < Rails::Generators::TestCase end 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") - - stub_rails_application(app_root) do - generator = Rails::Generators::AppGenerator.new ["rails"], [], 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 - 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") - - stub_rails_application(app_root) do - generator = Rails::Generators::AppGenerator.new ["rails"], [], 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 - end - def test_rails_update_set_the_cookie_serializer_to_marshal_if_it_is_not_already_configured - app_root = File.join(destination_root, 'myapp') + app_root = File.join(destination_root, "myapp") run_generator [app_root] FileUtils.rm("#{app_root}/config/initializers/cookies_serializer.rb") @@ -216,7 +186,7 @@ class AppGeneratorTest < Rails::Generators::TestCase end def test_rails_update_dont_set_file_watcher - app_root = File.join(destination_root, 'myapp') + app_root = File.join(destination_root, "myapp") run_generator [app_root] stub_rails_application(app_root) do @@ -229,92 +199,27 @@ class AppGeneratorTest < Rails::Generators::TestCase end end - def test_rails_update_does_not_create_active_record_belongs_to_required_by_default - app_root = File.join(destination_root, 'myapp') + def test_rails_update_does_not_create_new_framework_defaults_by_default + app_root = File.join(destination_root, "myapp") run_generator [app_root] - FileUtils.rm("#{app_root}/config/initializers/active_record_belongs_to_required_by_default.rb") + FileUtils.rm("#{app_root}/config/initializers/new_framework_defaults.rb") stub_rails_application(app_root) do - generator = Rails::Generators::AppGenerator.new ["rails"], [], destination_root: app_root, shell: @shell + generator = Rails::Generators::AppGenerator.new ["rails"], { update: true }, destination_root: app_root, shell: @shell generator.send(:app_const) quietly { generator.send(:update_config_files) } - assert_no_file "#{app_root}/config/initializers/active_record_belongs_to_required_by_default.rb" - end - end - - def test_rails_update_does_not_remove_active_record_belongs_to_required_by_default_if_already_present - app_root = File.join(destination_root, 'myapp') - run_generator [app_root] - - FileUtils.touch("#{app_root}/config/initializers/active_record_belongs_to_required_by_default.rb") - stub_rails_application(app_root) do - generator = Rails::Generators::AppGenerator.new ["rails"], [], destination_root: app_root, shell: @shell - generator.send(:app_const) - quietly { generator.send(:update_config_files) } - assert_file "#{app_root}/config/initializers/active_record_belongs_to_required_by_default.rb" - end - end - - def test_rails_update_does_not_create_to_time_preserves_timezone - app_root = File.join(destination_root, 'myapp') - run_generator [app_root] - - FileUtils.rm("#{app_root}/config/initializers/to_time_preserves_timezone.rb") - - stub_rails_application(app_root) do - generator = Rails::Generators::AppGenerator.new ["rails"], [], destination_root: app_root, shell: @shell - generator.send(:app_const) - quietly { generator.send(:update_config_files) } - assert_no_file "#{app_root}/config/initializers/to_time_preserves_timezone.rb" - end - end - - def test_rails_update_does_not_remove_to_time_preserves_timezone_if_already_present - app_root = File.join(destination_root, 'myapp') - run_generator [app_root] - - FileUtils.touch("#{app_root}/config/initializers/to_time_preserves_timezone.rb") - - stub_rails_application(app_root) do - generator = Rails::Generators::AppGenerator.new ["rails"], [], destination_root: app_root, shell: @shell - generator.send(:app_const) - quietly { generator.send(:update_config_files) } - assert_file "#{app_root}/config/initializers/to_time_preserves_timezone.rb" - end - end - - def test_rails_update_does_not_create_ssl_options_by_default - app_root = File.join(destination_root, 'myapp') - run_generator [app_root] - - FileUtils.rm("#{app_root}/config/initializers/ssl_options.rb") - - stub_rails_application(app_root) do - generator = Rails::Generators::AppGenerator.new ["rails"], [], destination_root: app_root, shell: @shell - generator.send(:app_const) - quietly { generator.send(:update_config_files) } - assert_no_file "#{app_root}/config/initializers/ssl_options.rb" - end - end - - def test_rails_update_does_not_remove_ssl_options_if_already_present - app_root = File.join(destination_root, 'myapp') - run_generator [app_root] - - FileUtils.touch("#{app_root}/config/initializers/ssl_options.rb") - - stub_rails_application(app_root) do - generator = Rails::Generators::AppGenerator.new ["rails"], [], destination_root: app_root, shell: @shell - generator.send(:app_const) - quietly { generator.send(:update_config_files) } - assert_file "#{app_root}/config/initializers/ssl_options.rb" + assert_file "#{app_root}/config/initializers/new_framework_defaults.rb" do |content| + assert_match(/ActiveSupport\.halt_callback_chains_on_return_false = true/, content) + assert_match(/Rails\.application\.config.active_record\.belongs_to_required_by_default = false/, content) + assert_no_match(/Rails\.application\.config\.ssl_options/, content) + end end end def test_rails_update_does_not_create_rack_cors - app_root = File.join(destination_root, 'myapp') + app_root = File.join(destination_root, "myapp") run_generator [app_root] stub_rails_application(app_root) do @@ -326,7 +231,7 @@ class AppGeneratorTest < Rails::Generators::TestCase end def test_rails_update_does_not_remove_rack_cors_if_already_present - app_root = File.join(destination_root, 'myapp') + app_root = File.join(destination_root, "myapp") run_generator [app_root] FileUtils.touch("#{app_root}/config/initializers/cors.rb") @@ -347,7 +252,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_gemfile_has_no_whitespace_errors run_generator absolute = File.expand_path("Gemfile", destination_root) - File.open(absolute, 'r') do |f| + File.open(absolute, "r") do |f| f.each_line do |line| assert_no_match %r{/^[ \t]+$/}, line end @@ -452,12 +357,15 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_generator_if_skip_active_record_is_given run_generator [destination_root, "--skip-active-record"] assert_no_file "config/database.yml" - assert_no_file "config/initializers/active_record_belongs_to_required_by_default.rb" assert_no_file "app/models/application_record.rb" assert_file "config/application.rb", /#\s+require\s+["']active_record\/railtie["']/ assert_file "test/test_helper.rb" do |helper_content| assert_no_match(/fixtures :all/, helper_content) end + + assert_file "config/initializers/new_framework_defaults.rb" do |initializer_content| + assert_no_match(/belongs_to_required_by_default/, initializer_content) + end end def test_generator_if_skip_action_mailer_is_given @@ -472,13 +380,15 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "config/environments/production.rb" do |content| assert_no_match(/config\.action_mailer/, content) end + assert_no_directory "app/mailers" + assert_no_directory "test/mailers" end def test_generator_has_assets_gems run_generator - assert_gem 'sass-rails' - assert_gem 'uglifier' + assert_gem "sass-rails" + assert_gem "uglifier" end def test_generator_if_skip_sprockets_is_given @@ -538,7 +448,7 @@ class AppGeneratorTest < Rails::Generators::TestCase end def test_other_javascript_libraries - run_generator [destination_root, '-j', 'prototype'] + run_generator [destination_root, "-j", "prototype"] assert_file "app/assets/javascripts/application.js" do |contents| assert_match %r{^//= require prototype}, contents assert_match %r{^//= require prototype_ujs}, contents @@ -560,12 +470,17 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "Gemfile" do |content| assert_no_match(/coffee-rails/, content) assert_no_match(/jquery-rails/, content) + assert_no_match(/uglifier/, content) + end + + assert_file "config/environments/production.rb" do |content| + assert_no_match(/config\.assets\.js_compressor = :uglifier/, content) end end def test_inclusion_of_jbuilder run_generator - assert_gem 'jbuilder' + assert_gem "jbuilder" end def test_inclusion_of_a_debugger @@ -575,13 +490,13 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_no_match(/byebug/, content) end else - assert_gem 'byebug' + assert_gem "byebug" end end def test_inclusion_of_listen_related_configuration_by_default run_generator - if RbConfig::CONFIG['host_os'] =~ /darwin|linux/ + if RbConfig::CONFIG["host_os"] =~ /darwin|linux/ assert_listen_related_configuration else assert_no_listen_related_configuration @@ -589,14 +504,14 @@ class AppGeneratorTest < Rails::Generators::TestCase end def test_non_inclusion_of_listen_related_configuration_if_skip_listen - run_generator [destination_root, '--skip-listen'] + run_generator [destination_root, "--skip-listen"] assert_no_listen_related_configuration end def test_evented_file_update_checker_config run_generator - assert_file 'config/environments/development.rb' do |content| - if RbConfig::CONFIG['host_os'] =~ /darwin|linux/ + assert_file "config/environments/development.rb" do |content| + if RbConfig::CONFIG["host_os"] =~ /darwin|linux/ assert_match(/^\s*config.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content) else assert_match(/^\s*# config.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content) @@ -626,8 +541,8 @@ class AppGeneratorTest < Rails::Generators::TestCase end def test_file_is_added_for_backwards_compatibility - action :file, 'lib/test_file.rb', 'heres test data' - assert_file 'lib/test_file.rb', 'heres test data' + action :file, "lib/test_file.rb", "heres test data" + assert_file "lib/test_file.rb", "heres test data" end def test_tests_are_removed_from_frameworks_if_skip_test_is_given @@ -642,13 +557,6 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "config/application.rb", /\s+require\s+["']active_job\/railtie["']/ end - def test_new_hash_style - run_generator - assert_file "config/initializers/session_store.rb" do |file| - assert_match(/config.session_store :cookie_store, key: '_.+_session'/, file) - end - end - def test_pretend_option output = run_generator [File.join(destination_root, "myapp"), "--pretend"] assert_no_match(/run bundle install/, output) @@ -658,15 +566,14 @@ class AppGeneratorTest < Rails::Generators::TestCase path = File.join(destination_root, "foo bar") # This also applies to MySQL apps but not with SQLite - run_generator [path, "-d", 'postgresql'] + run_generator [path, "-d", "postgresql"] assert_file "foo bar/config/database.yml", /database: foo_bar_development/ - assert_file "foo bar/config/initializers/session_store.rb", /key: '_foo_bar/ end def test_web_console run_generator - assert_gem 'web-console' + assert_gem "web-console" end def test_web_console_with_dev_option @@ -674,7 +581,7 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "Gemfile" do |content| assert_match(/gem 'web-console',\s+github: 'rails\/web-console'/, content) - assert_no_match(/\Agem 'web-console'\z/, content) + assert_no_match(/\Agem 'web-console', '>= 3.3.0'\z/, content) end end @@ -683,13 +590,28 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "Gemfile" do |content| assert_match(/gem 'web-console',\s+github: 'rails\/web-console'/, content) - assert_no_match(/\Agem 'web-console'\z/, content) + assert_no_match(/\Agem 'web-console', '>= 3.3.0'\z/, content) end end + def test_generation_runs_bundle_install + assert_generates_with_bundler + end + + def test_dev_option + assert_generates_with_bundler dev: true + rails_path = File.expand_path("../../..", Rails.root) + assert_file "Gemfile", /^gem\s+["']rails["'],\s+path:\s+["']#{Regexp.escape(rails_path)}["']$/ + end + + def test_edge_option + assert_generates_with_bundler edge: true + assert_file "Gemfile", %r{^gem\s+["']rails["'],\s+github:\s+["']#{Regexp.escape("rails/rails")}["']$} + end + def test_spring run_generator - assert_gem 'spring' + assert_gem "spring" end def test_spring_binstubs @@ -698,9 +620,9 @@ class AppGeneratorTest < Rails::Generators::TestCase @binstub_called ||= 0 case command - when 'install' + when "install" # Called when running bundle, we just want to stub it so nothing to do here. - when 'exec spring binstub --all' + when "exec spring binstub --all" @binstub_called += 1 assert_equal 1, @binstub_called, "exec spring binstub --all expected to be called once, but was called #{@install_called} times." end @@ -725,7 +647,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_skip_spring run_generator [destination_root, "--skip-spring"] - assert_no_file 'config/spring.rb' + assert_no_file "config/spring.rb" assert_file "Gemfile" do |content| assert_no_match(/spring/, content) end @@ -756,15 +678,15 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_gitignore_when_sqlite3 run_generator - assert_file '.gitignore' do |content| + assert_file ".gitignore" do |content| assert_match(/sqlite3/, content) end end def test_gitignore_when_no_active_record - run_generator [destination_root, '--skip-active-record'] + run_generator [destination_root, "--skip-active-record"] - assert_file '.gitignore' do |content| + assert_file ".gitignore" do |content| assert_no_match(/sqlite/i, content) end end @@ -772,7 +694,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_gitignore_when_non_sqlite3_db run_generator([destination_root, "-d", "mysql"]) - assert_file '.gitignore' do |content| + assert_file ".gitignore" do |content| assert_no_match(/sqlite/i, content) end end @@ -815,17 +737,17 @@ class AppGeneratorTest < Rails::Generators::TestCase end def test_after_bundle_callback - path = 'http://example.org/rails_template' + 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 check_open = -> *args do - assert_equal [ path, 'Accept' => 'application/x-thor-template' ], args + assert_equal [ path, "Accept" => "application/x-thor-template" ], args template end - sequence = ['install', 'exec spring binstub --all', 'echo ran after_bundle'] - @sequence_step ||= 0 + sequence = ["install", "exec spring binstub --all", "echo ran after_bundle"] + @sequence_step ||= 0 ensure_bundler_first = -> command do assert_equal sequence[@sequence_step], command, "commands should be called in sequence #{sequence}" @sequence_step += 1 @@ -844,41 +766,61 @@ class AppGeneratorTest < Rails::Generators::TestCase protected - def stub_rails_application(root) - Rails.application.config.root = root - Rails.application.class.stub(:name, "Myapp") do - yield + def stub_rails_application(root) + Rails.application.config.root = root + Rails.application.class.stub(:name, "Myapp") do + yield + end end - end - def action(*args, &block) - capture(:stdout) { generator.send(*args, &block) } - end + def action(*args, &block) + capture(:stdout) { generator.send(*args, &block) } + end - def assert_gem(gem, constraint = nil) - if constraint - assert_file "Gemfile", /^\s*gem\s+["']#{gem}["'], #{constraint}$*/ - else - assert_file "Gemfile", /^\s*gem\s+["']#{gem}["']$*/ + def assert_gem(gem, constraint = nil) + if constraint + assert_file "Gemfile", /^\s*gem\s+["']#{gem}["'], #{constraint}$*/ + else + assert_file "Gemfile", /^\s*gem\s+["']#{gem}["']$*/ + end end - end - def assert_listen_related_configuration - assert_gem 'listen' - assert_gem 'spring-watcher-listen' + def assert_listen_related_configuration + assert_gem "listen" + assert_gem "spring-watcher-listen" - assert_file 'config/environments/development.rb' do |content| - assert_match(/^\s*config.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content) + assert_file "config/environments/development.rb" do |content| + assert_match(/^\s*config.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content) + end end - end - def assert_no_listen_related_configuration - assert_file 'Gemfile' do |content| - assert_no_match(/listen/, content) + def assert_no_listen_related_configuration + assert_file "Gemfile" do |content| + assert_no_match(/listen/, content) + end + + assert_file "config/environments/development.rb" do |content| + assert_match(/^\s*# config.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content) + end end - assert_file 'config/environments/development.rb' do |content| - assert_match(/^\s*# config.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content) + def assert_generates_with_bundler(options = {}) + generator([destination_root], options) + + command_check = -> command do + @install_called ||= 0 + + case command + when "install" + @install_called += 1 + assert_equal 1, @install_called, "install expected to be called once, but was called #{@install_called} times" + when "exec spring binstub --all" + # Called when running tests with spring, let through unscathed. + end + end + + generator.stub :bundle_command, command_check do + quietly { generator.invoke_all } + end end - end end diff --git a/railties/test/generators/argv_scrubber_test.rb b/railties/test/generators/argv_scrubber_test.rb index 31e07bc8da..7f4295a20f 100644 --- a/railties/test/generators/argv_scrubber_test.rb +++ b/railties/test/generators/argv_scrubber_test.rb @@ -1,7 +1,7 @@ -require 'active_support/test_case' -require 'active_support/testing/autorun' -require 'rails/generators/rails/app/app_generator' -require 'tempfile' +require "active_support/test_case" +require "active_support/testing/autorun" +require "rails/generators/rails/app/app_generator" +require "tempfile" module Rails module Generators @@ -11,7 +11,7 @@ module Rails # *must* act this way, I just want to prevent regressions. def test_version - ['-v', '--version'].each do |str| + ["-v", "--version"].each do |str| scrubber = ARGVScrubber.new [str] output = nil exit_code = nil @@ -26,37 +26,37 @@ module Rails end def test_default_help - argv = ['zomg', 'how', 'are', 'you'] + argv = ["zomg", "how", "are", "you"] scrubber = ARGVScrubber.new argv args = scrubber.prepare! - assert_equal ['--help'] + argv.drop(1), args + assert_equal ["--help"] + argv.drop(1), args end def test_prepare_returns_args - scrubber = ARGVScrubber.new ['hi mom'] + scrubber = ARGVScrubber.new ["hi mom"] args = scrubber.prepare! - assert_equal '--help', args.first + assert_equal "--help", args.first end def test_no_mutations - scrubber = ARGVScrubber.new ['hi mom'].freeze + scrubber = ARGVScrubber.new ["hi mom"].freeze args = scrubber.prepare! - assert_equal '--help', args.first + assert_equal "--help", args.first end def test_new_command_no_rc scrubber = Class.new(ARGVScrubber) { def self.default_rc_file - File.join(Dir.tmpdir, 'whatever') + File.join(Dir.tmpdir, "whatever") end - }.new ['new'] + }.new ["new"] args = scrubber.prepare! assert_equal [], args end def test_new_homedir_rc - file = Tempfile.new 'myrcfile' - file.puts '--hello-world' + file = Tempfile.new "myrcfile" + file.puts "--hello-world" file.flush message = nil @@ -65,10 +65,10 @@ module Rails file.path end define_method(:puts) { |msg| message = msg } - }.new ['new'] + }.new ["new"] args = scrubber.prepare! - assert_equal ['--hello-world'], args - assert_match 'hello-world', message + assert_equal ["--hello-world"], args + assert_match "hello-world", message assert_match file.path, message ensure file.close @@ -76,33 +76,33 @@ module Rails end def test_rc_whitespace_separated - file = Tempfile.new 'myrcfile' - file.puts '--hello --world' + file = Tempfile.new "myrcfile" + file.puts "--hello --world" file.flush message = nil scrubber = Class.new(ARGVScrubber) { define_method(:puts) { |msg| message = msg } - }.new ['new', "--rc=#{file.path}"] + }.new ["new", "--rc=#{file.path}"] args = scrubber.prepare! - assert_equal ['--hello', '--world'], args + assert_equal ["--hello", "--world"], args ensure file.close file.unlink end def test_new_rc_option - file = Tempfile.new 'myrcfile' - file.puts '--hello-world' + file = Tempfile.new "myrcfile" + file.puts "--hello-world" file.flush message = nil scrubber = Class.new(ARGVScrubber) { define_method(:puts) { |msg| message = msg } - }.new ['new', "--rc=#{file.path}"] + }.new ["new", "--rc=#{file.path}"] args = scrubber.prepare! - assert_equal ['--hello-world'], args - assert_match 'hello-world', message + assert_equal ["--hello-world"], args + assert_match "hello-world", message assert_match file.path, message ensure file.close @@ -110,14 +110,14 @@ module Rails end def test_new_rc_option_and_custom_options - file = Tempfile.new 'myrcfile' - file.puts '--hello' - file.puts '--world' + file = Tempfile.new "myrcfile" + file.puts "--hello" + file.puts "--world" file.flush scrubber = Class.new(ARGVScrubber) { define_method(:puts) { |msg| } - }.new ['new', 'tenderapp', '--love', "--rc=#{file.path}"] + }.new ["new", "tenderapp", "--love", "--rc=#{file.path}"] args = scrubber.prepare! assert_equal ["tenderapp", "--hello", "--world", "--love"], args @@ -127,7 +127,7 @@ module Rails end def test_no_rc - scrubber = ARGVScrubber.new ['new', '--no-rc'] + scrubber = ARGVScrubber.new ["new", "--no-rc"] args = scrubber.prepare! assert_equal [], args end diff --git a/railties/test/generators/assets_generator_test.rb b/railties/test/generators/assets_generator_test.rb index a2b94f2e50..1c02c67e42 100644 --- a/railties/test/generators/assets_generator_test.rb +++ b/railties/test/generators/assets_generator_test.rb @@ -1,5 +1,5 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/assets/assets_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/assets/assets_generator" class AssetsGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper diff --git a/railties/test/generators/channel_generator_test.rb b/railties/test/generators/channel_generator_test.rb index d58b54ac24..a1d54200ba 100644 --- a/railties/test/generators/channel_generator_test.rb +++ b/railties/test/generators/channel_generator_test.rb @@ -1,12 +1,12 @@ -require 'generators/generators_test_helper' -require 'rails/generators/channel/channel_generator' +require "generators/generators_test_helper" +require "rails/generators/channel/channel_generator" class ChannelGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper tests Rails::Generators::ChannelGenerator def test_application_cable_skeleton_is_created - run_generator ['books'] + run_generator ["books"] assert_file "app/channels/application_cable/channel.rb" do |cable| assert_match(/module ApplicationCable\n class Channel < ActionCable::Channel::Base\n/, cable) @@ -18,41 +18,57 @@ class ChannelGeneratorTest < Rails::Generators::TestCase end def test_channel_is_created - run_generator ['chat'] + run_generator ["chat"] assert_file "app/channels/chat_channel.rb" do |channel| assert_match(/class ChatChannel < ApplicationCable::Channel/, channel) end - assert_file "app/assets/javascripts/channels/chat.coffee" do |channel| - assert_match(/App.cable.subscriptions.create "ChatChannel"/, channel) + assert_file "app/assets/javascripts/channels/chat.js" do |channel| + assert_match(/App.chat = App.cable.subscriptions.create\("ChatChannel/, channel) + end + end + + def test_channel_with_multiple_actions_is_created + run_generator ["chat", "speak", "mute"] + + assert_file "app/channels/chat_channel.rb" do |channel| + assert_match(/class ChatChannel < ApplicationCable::Channel/, channel) + assert_match(/def speak/, channel) + assert_match(/def mute/, channel) + end + + assert_file "app/assets/javascripts/channels/chat.js" do |channel| + assert_match(/App.chat = App.cable.subscriptions.create\("ChatChannel/, channel) + assert_match(/,\n\n speak/, channel) + assert_match(/,\n\n mute: function\(\) \{\n return this\.perform\('mute'\);\n \}\n\}\);/, channel) end end def test_channel_asset_is_not_created_when_skip_assets_is_passed - run_generator ['chat', '--skip-assets'] + run_generator ["chat", "--skip-assets"] assert_file "app/channels/chat_channel.rb" do |channel| assert_match(/class ChatChannel < ApplicationCable::Channel/, channel) end - assert_no_file "app/assets/javascripts/channels/chat.coffee" + assert_no_file "app/assets/javascripts/channels/chat.js" end def test_cable_js_is_created_if_not_present_already - run_generator ['chat'] + run_generator ["chat"] FileUtils.rm("#{destination_root}/app/assets/javascripts/cable.js") - run_generator ['camp'] + run_generator ["camp"] assert_file "app/assets/javascripts/cable.js" end def test_channel_on_revoke - run_generator ['chat'] - run_generator ['chat'], behavior: :revoke + run_generator ["chat"] + run_generator ["chat"], behavior: :revoke assert_no_file "app/channels/chat_channel.rb" - assert_no_file "app/assets/javascripts/channels/chat.coffee" + assert_no_file "app/assets/javascripts/channels/chat.js" assert_file "app/channels/application_cable/channel.rb" assert_file "app/channels/application_cable/connection.rb" diff --git a/railties/test/generators/controller_generator_test.rb b/railties/test/generators/controller_generator_test.rb index 1351151afb..9b986a636a 100644 --- a/railties/test/generators/controller_generator_test.rb +++ b/railties/test/generators/controller_generator_test.rb @@ -1,5 +1,5 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/controller/controller_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/controller/controller_generator" class ControllerGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -19,7 +19,7 @@ class ControllerGeneratorTest < Rails::Generators::TestCase def test_check_class_collision Object.send :const_set, :ObjectController, Class.new - content = capture(:stderr){ run_generator ["object"] } + content = capture(:stderr) { run_generator ["object"] } assert_match(/The name 'ObjectController' is either already used in your application or reserved/, content) ensure Object.send :remove_const, :ObjectController diff --git a/railties/test/generators/create_migration_test.rb b/railties/test/generators/create_migration_test.rb index e16a77479a..ddd40e4d02 100644 --- a/railties/test/generators/create_migration_test.rb +++ b/railties/test/generators/create_migration_test.rb @@ -1,5 +1,5 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/migration/migration_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/migration/migration_generator" class CreateMigrationTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -19,12 +19,12 @@ class CreateMigrationTest < Rails::Generators::TestCase end def create_migration(destination_path = default_destination_path, config = {}, generator_options = {}, &block) - migration_name = File.basename(destination_path, '.rb') + migration_name = File.basename(destination_path, ".rb") generator([migration_name], generator_options) generator.set_migration_assigns!(destination_path) dir, base = File.split(destination_path) - timestamped_destination_path = File.join(dir, ["%migration_number%", base].join('_')) + timestamped_destination_path = File.join(dir, ["%migration_number%", base].join("_")) @migration = Rails::Generators::Actions::CreateMigration.new(generator, timestamped_destination_path, block || "contents", config) end @@ -51,7 +51,7 @@ class CreateMigrationTest < Rails::Generators::TestCase end def test_invoke_pretended - create_migration(default_destination_path, {}, { pretend: true }) + create_migration(default_destination_path, {}, pretend: true) assert_no_file @migration.destination end @@ -92,7 +92,7 @@ class CreateMigrationTest < Rails::Generators::TestCase def test_invoke_forced_pretended_when_exists_not_identical migration_exists! - create_migration(default_destination_path, { force: true }, { pretend: true }) do + create_migration(default_destination_path, { force: true }, pretend: true) do "different content" end @@ -104,7 +104,7 @@ class CreateMigrationTest < Rails::Generators::TestCase def test_invoke_skipped_when_exists_not_identical migration_exists! - create_migration(default_destination_path, {}, { skip: true }) { "different content" } + create_migration(default_destination_path, {}, skip: true) { "different content" } assert_match(/skip db\/migrate\/2_create_articles.rb\n/, invoke!) assert_no_file @migration.destination @@ -120,7 +120,7 @@ class CreateMigrationTest < Rails::Generators::TestCase def test_revoke_pretended migration_exists! - create_migration(default_destination_path, {}, { pretend: true }) + create_migration(default_destination_path, {}, pretend: true) assert_match(/remove db\/migrate\/1_create_articles.rb\n/, revoke!) assert_file @existing_migration.destination diff --git a/railties/test/generators/generated_attribute_test.rb b/railties/test/generators/generated_attribute_test.rb index ee7c009305..97847c8624 100644 --- a/railties/test/generators/generated_attribute_test.rb +++ b/railties/test/generators/generated_attribute_test.rb @@ -1,5 +1,5 @@ -require 'generators/generators_test_helper' -require 'rails/generators/generated_attribute' +require "generators/generators_test_helper" +require "rails/generators/generated_attribute" class GeneratedAttributeTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -51,7 +51,7 @@ class GeneratedAttributeTest < Rails::Generators::TestCase end def test_default_value_is_decimal - assert_field_default_value :decimal, '9.99' + assert_field_default_value :decimal, "9.99" end def test_default_value_is_datetime @@ -65,7 +65,7 @@ class GeneratedAttributeTest < Rails::Generators::TestCase end def test_default_value_is_string - assert_field_default_value :string, 'MyString' + assert_field_default_value :string, "MyString" end def test_default_value_for_type @@ -74,7 +74,7 @@ class GeneratedAttributeTest < Rails::Generators::TestCase end def test_default_value_is_text - assert_field_default_value :text, 'MyText' + assert_field_default_value :text, "MyText" end def test_default_value_is_boolean @@ -89,14 +89,14 @@ class GeneratedAttributeTest < Rails::Generators::TestCase def test_default_value_is_empty_string %w(foo bar baz).each do |attribute_type| - assert_field_default_value attribute_type, '' + assert_field_default_value attribute_type, "" end end def test_human_name assert_equal( - 'Full name', - create_generated_attribute(:string, 'full_name').human_name + "Full name", + create_generated_attribute(:string, "full_name").human_name ) end @@ -125,21 +125,21 @@ class GeneratedAttributeTest < Rails::Generators::TestCase end def test_blank_type_defaults_to_string_raises_exception - assert_equal :string, create_generated_attribute(nil, 'title').type - assert_equal :string, create_generated_attribute("", 'title').type + assert_equal :string, create_generated_attribute(nil, "title").type + assert_equal :string, create_generated_attribute("", "title").type end def test_handles_index_names_for_references - assert_equal "post", create_generated_attribute('string', 'post').index_name - assert_equal "post_id", create_generated_attribute('references', 'post').index_name - assert_equal "post_id", create_generated_attribute('belongs_to', 'post').index_name - assert_equal ["post_id", "post_type"], create_generated_attribute('references{polymorphic}', 'post').index_name + assert_equal "post", create_generated_attribute("string", "post").index_name + assert_equal "post_id", create_generated_attribute("references", "post").index_name + assert_equal "post_id", create_generated_attribute("belongs_to", "post").index_name + assert_equal ["post_id", "post_type"], create_generated_attribute("references{polymorphic}", "post").index_name end def test_handles_column_names_for_references - assert_equal "post", create_generated_attribute('string', 'post').column_name - assert_equal "post_id", create_generated_attribute('references', 'post').column_name - assert_equal "post_id", create_generated_attribute('belongs_to', 'post').column_name + assert_equal "post", create_generated_attribute("string", "post").column_name + 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 diff --git a/railties/test/generators/generator_generator_test.rb b/railties/test/generators/generator_generator_test.rb index dcfeaaa8e0..5ff8bb0357 100644 --- a/railties/test/generators/generator_generator_test.rb +++ b/railties/test/generators/generator_generator_test.rb @@ -1,5 +1,5 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/generator/generator_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/generator/generator_generator" class GeneratorGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -12,7 +12,7 @@ class GeneratorGeneratorTest < Rails::Generators::TestCase lib/generators/awesome lib/generators/awesome/USAGE lib/generators/awesome/templates - ).each{ |path| assert_file path } + ).each { |path| assert_file path } assert_file "lib/generators/awesome/awesome_generator.rb", /class AwesomeGenerator < Rails::Generators::NamedBase/ @@ -28,7 +28,7 @@ class GeneratorGeneratorTest < Rails::Generators::TestCase lib/generators/rails/awesome lib/generators/rails/awesome/USAGE lib/generators/rails/awesome/templates - ).each{ |path| assert_file path } + ).each { |path| assert_file path } assert_file "lib/generators/rails/awesome/awesome_generator.rb", /class Rails::AwesomeGenerator < Rails::Generators::NamedBase/ @@ -44,7 +44,7 @@ class GeneratorGeneratorTest < Rails::Generators::TestCase lib/generators/ lib/generators/USAGE lib/generators/templates - ).each{ |path| assert_file path } + ).each { |path| assert_file path } assert_file "lib/generators/awesome_generator.rb", /class AwesomeGenerator < Rails::Generators::NamedBase/ @@ -60,7 +60,7 @@ class GeneratorGeneratorTest < Rails::Generators::TestCase lib/generators/rails lib/generators/rails/USAGE lib/generators/rails/templates - ).each{ |path| assert_file path } + ).each { |path| assert_file path } assert_file "lib/generators/rails/awesome_generator.rb", /class Rails::AwesomeGenerator < Rails::Generators::NamedBase/ diff --git a/railties/test/generators/generator_test.rb b/railties/test/generators/generator_test.rb index 8ef44a8dcb..c4e4747468 100644 --- a/railties/test/generators/generator_test.rb +++ b/railties/test/generators/generator_test.rb @@ -1,6 +1,6 @@ -require 'active_support/test_case' -require 'active_support/testing/autorun' -require 'rails/generators/app_base' +require "active_support/test_case" +require "active_support/testing/autorun" +require "rails/generators/app_base" module Rails module Generators @@ -21,46 +21,46 @@ module Rails def test_construction klass = make_builder_class - assert klass.start(['new', 'blah']) + assert klass.start(["new", "blah"]) end def test_add_gem klass = make_builder_class - generator = klass.start(['new', 'blah']) - generator.gemfile_entry 'tenderlove' - assert_includes generator.gemfile_entries.map(&:name), 'tenderlove' + generator = klass.start(["new", "blah"]) + generator.gemfile_entry "tenderlove" + assert_includes generator.gemfile_entries.map(&:name), "tenderlove" end def test_add_gem_with_version klass = make_builder_class - generator = klass.start(['new', 'blah']) - generator.gemfile_entry 'tenderlove', '2.0.0' + generator = klass.start(["new", "blah"]) + generator.gemfile_entry "tenderlove", "2.0.0" assert generator.gemfile_entries.find { |gfe| - gfe.name == 'tenderlove' && gfe.version == '2.0.0' + gfe.name == "tenderlove" && gfe.version == "2.0.0" } end def test_add_github_gem klass = make_builder_class - generator = klass.start(['new', 'blah']) - generator.gemfile_entry 'tenderlove', github: 'hello world' + generator = klass.start(["new", "blah"]) + generator.gemfile_entry "tenderlove", github: "hello world" assert generator.gemfile_entries.find { |gfe| - gfe.name == 'tenderlove' && gfe.options[:github] == 'hello world' + gfe.name == "tenderlove" && gfe.options[:github] == "hello world" } end def test_add_path_gem klass = make_builder_class - generator = klass.start(['new', 'blah']) - generator.gemfile_entry 'tenderlove', path: 'hello world' + generator = klass.start(["new", "blah"]) + generator.gemfile_entry "tenderlove", path: "hello world" assert generator.gemfile_entries.find { |gfe| - gfe.name == 'tenderlove' && gfe.options[:path] == 'hello world' + gfe.name == "tenderlove" && gfe.options[:path] == "hello world" } end def test_filter klass = make_builder_class - generator = klass.start(['new', 'blah']) + generator = klass.start(["new", "blah"]) gems = generator.gemfile_entries generator.add_gem_entry_filter { |gem| gem.name != gems.first.name @@ -70,7 +70,7 @@ module Rails def test_two_filters klass = make_builder_class - generator = klass.start(['new', 'blah']) + generator = klass.start(["new", "blah"]) gems = generator.gemfile_entries generator.add_gem_entry_filter { |gem| gem.name != gems.first.name @@ -83,17 +83,17 @@ module Rails def test_recommended_rails_versions klass = make_builder_class - generator = klass.start(['new', 'blah']) + generator = klass.start(["new", "blah"]) specifier_for = -> v { generator.send(:rails_version_specifier, Gem::Version.new(v)) } - assert_equal '~> 4.1.13', specifier_for['4.1.13'] - assert_equal ['>= 4.1.6.rc1', '< 4.2'], specifier_for['4.1.6.rc1'] - assert_equal ['~> 4.1.7', '>= 4.1.7.1'], specifier_for['4.1.7.1'] - assert_equal ['~> 4.1.7', '>= 4.1.7.1.2'], specifier_for['4.1.7.1.2'] - assert_equal ['>= 4.1.7.1.rc2', '< 4.2'], specifier_for['4.1.7.1.rc2'] - assert_equal ['>= 4.2.0.beta1', '< 4.3'], specifier_for['4.2.0.beta1'] - assert_equal ['>= 5.0.0.beta1', '< 5.1'], specifier_for['5.0.0.beta1'] + assert_equal "~> 4.1.13", specifier_for["4.1.13"] + assert_equal [">= 4.1.6.rc1", "< 4.2"], specifier_for["4.1.6.rc1"] + assert_equal ["~> 4.1.7", ">= 4.1.7.1"], specifier_for["4.1.7.1"] + assert_equal ["~> 4.1.7", ">= 4.1.7.1.2"], specifier_for["4.1.7.1.2"] + assert_equal [">= 4.1.7.1.rc2", "< 4.2"], specifier_for["4.1.7.1.rc2"] + assert_equal [">= 4.2.0.beta1", "< 4.3"], specifier_for["4.2.0.beta1"] + assert_equal [">= 5.0.0.beta1", "< 5.1"], specifier_for["5.0.0.beta1"] end end end diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb index b19a5a7144..2cdddc8713 100644 --- a/railties/test/generators/generators_test_helper.rb +++ b/railties/test/generators/generators_test_helper.rb @@ -1,15 +1,15 @@ -require 'abstract_unit' -require 'active_support/core_ext/module/remove_method' -require 'active_support/testing/stream' -require 'active_support/testing/method_call_assertions' -require 'rails/generators' -require 'rails/generators/test_case' +require "abstract_unit" +require "active_support/core_ext/module/remove_method" +require "active_support/testing/stream" +require "active_support/testing/method_call_assertions" +require "rails/generators" +require "rails/generators/test_case" module Rails class << self remove_possible_method :root def root - @root ||= Pathname.new(File.expand_path('../../fixtures', __FILE__)) + @root ||= Pathname.new(File.expand_path("../../fixtures", __FILE__)) end end end @@ -20,9 +20,9 @@ Rails.application.config.generators.templates = [File.join(Rails.root, "lib", "t # Rails.application.config.generators to Rails::Generators Rails.application.load_generators -require 'active_record' -require 'action_dispatch' -require 'action_view' +require "active_record" +require "action_dispatch" +require "action_view" module GeneratorsTestHelper include ActiveSupport::Testing::Stream @@ -34,7 +34,7 @@ module GeneratorsTestHelper setup :prepare_destination begin - base.tests Rails::Generators.const_get(base.name.sub(/Test$/, '')) + base.tests Rails::Generators.const_get(base.name.sub(/Test$/, "")) rescue end end @@ -46,5 +46,4 @@ module GeneratorsTestHelper FileUtils.mkdir_p(destination) FileUtils.cp routes, destination end - end diff --git a/railties/test/generators/helper_generator_test.rb b/railties/test/generators/helper_generator_test.rb index add04f21a4..d9e6e0a85a 100644 --- a/railties/test/generators/helper_generator_test.rb +++ b/railties/test/generators/helper_generator_test.rb @@ -1,5 +1,5 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/helper/helper_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/helper/helper_generator" ObjectHelper = Class.new AnotherObjectHelperTest = Class.new @@ -14,7 +14,7 @@ class HelperGeneratorTest < Rails::Generators::TestCase end def test_check_class_collision - content = capture(:stderr){ run_generator ["object"] } + content = capture(:stderr) { run_generator ["object"] } assert_match(/The name 'ObjectHelper' is either already used in your application or reserved/, content) end diff --git a/railties/test/generators/integration_test_generator_test.rb b/railties/test/generators/integration_test_generator_test.rb index d05ed76d24..8bcc02440a 100644 --- a/railties/test/generators/integration_test_generator_test.rb +++ b/railties/test/generators/integration_test_generator_test.rb @@ -1,5 +1,5 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/integration_test/integration_test_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/integration_test/integration_test_generator" class IntegrationTestGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper diff --git a/railties/test/generators/job_generator_test.rb b/railties/test/generators/job_generator_test.rb index dbff0ab704..68d158eb39 100644 --- a/railties/test/generators/job_generator_test.rb +++ b/railties/test/generators/job_generator_test.rb @@ -1,5 +1,5 @@ -require 'generators/generators_test_helper' -require 'rails/generators/job/job_generator' +require "generators/generators_test_helper" +require "rails/generators/job/job_generator" class JobGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb index 8728b39dae..7d69d7470d 100644 --- a/railties/test/generators/mailer_generator_test.rb +++ b/railties/test/generators/mailer_generator_test.rb @@ -1,5 +1,5 @@ -require 'generators/generators_test_helper' -require 'rails/generators/mailer/mailer_generator' +require "generators/generators_test_helper" +require "rails/generators/mailer/mailer_generator" class MailerGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -13,7 +13,7 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_no_match(/layout :mailer_notifier/, mailer) end - assert_file 'app/mailers/application_mailer.rb' do |mailer| + 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) @@ -30,7 +30,7 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_check_class_collision Object.send :const_set, :NotifierMailer, Class.new - content = capture(:stderr){ run_generator } + content = capture(:stderr) { run_generator } assert_match(/The name 'NotifierMailer' is either already used in your application or reserved/, content) ensure Object.send :remove_const, :NotifierMailer @@ -59,7 +59,7 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_check_test_class_collision Object.send :const_set, :NotifierMailerTest, Class.new - content = capture(:stderr){ run_generator } + content = capture(:stderr) { run_generator } assert_match(/The name 'NotifierMailerTest' is either already used in your application or reserved/, content) ensure Object.send :remove_const, :NotifierMailerTest @@ -67,7 +67,7 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_check_preview_class_collision Object.send :const_set, :NotifierMailerPreview, Class.new - content = capture(:stderr){ run_generator } + content = capture(:stderr) { run_generator } assert_match(/The name 'NotifierMailerPreview' is either already used in your application or reserved/, content) ensure Object.send :remove_const, :NotifierMailerPreview @@ -84,6 +84,10 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_match(%r(\sapp/views/notifier_mailer/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 @@ -97,6 +101,10 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_match(%r(\sapp/views/notifier_mailer/bar\.html\.erb), view) assert_match(/<%= @greeting %>/, view) end + + assert_file "app/views/layouts/mailer.html.erb" do |view| + assert_match(%r{<body>\n <%= yield %>\n </body>}, view) + end end def test_invokes_default_template_engine_even_with_no_action diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb index 46154b7db2..6e1d1b70a9 100644 --- a/railties/test/generators/migration_generator_test.rb +++ b/railties/test/generators/migration_generator_test.rb @@ -1,5 +1,5 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/migration/migration_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/migration/migration_generator" class MigrationGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -17,7 +17,7 @@ class MigrationGeneratorTest < Rails::Generators::TestCase run_generator [migration] file_name = migration_file_name "db/migrate/#{migration}.rb" - File.basename(file_name).split('_').first + File.basename(file_name).split("_").first end assert_not_equal first_migration_number, second_migration_number @@ -248,7 +248,7 @@ class MigrationGeneratorTest < Rails::Generators::TestCase def test_migration_with_singular_table_name with_singular_table_name do migration = "add_title_body_to_post" - run_generator [migration, 'title:string'] + run_generator [migration, "title:string"] assert_migration "db/migrate/#{migration}.rb" do |content| assert_method :change, content do |change| assert_match(/add_column :post, :title, :string/, change) diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb index ed6846abc3..701d3ceaf2 100644 --- a/railties/test/generators/model_generator_test.rb +++ b/railties/test/generators/model_generator_test.rb @@ -1,18 +1,18 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/model/model_generator' -require 'active_support/core_ext/string/strip' +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 arguments %w(Account name:string age:integer) - def test_application_record_skeleton_is_created - run_generator - assert_file "app/models/application_record.rb" do |record| - assert_match(/class ApplicationRecord < ActiveRecord::Base/, record) - assert_match(/self.abstract_class = true/, record) - end - end + def test_application_record_skeleton_is_created + run_generator + assert_file "app/models/application_record.rb" do |record| + assert_match(/class ApplicationRecord < ActiveRecord::Base/, record) + assert_match(/self.abstract_class = true/, record) + end + end def test_help_shows_invoked_generators_options content = run_generator ["--help"] @@ -34,7 +34,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase def test_invokes_default_orm run_generator - assert_file "app/models/account.rb", /class Account < ActiveRecord::Base/ + assert_file "app/models/account.rb", /class Account < ApplicationRecord/ end def test_model_with_parent_option @@ -56,7 +56,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase def test_plural_names_are_singularized content = run_generator ["accounts".freeze] - assert_file "app/models/account.rb", /class Account < ActiveRecord::Base/ + assert_file "app/models/account.rb", /class Account < ApplicationRecord/ assert_file "test/models/account_test.rb", /class AccountTest/ assert_match(/\[WARNING\] The model name 'accounts' was recognized as a plural, using the singular 'account' instead\. Override with --force-plural or setup custom inflection rules for this noun before running the generator\./, content) end @@ -71,7 +71,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase assert_file "app/models/admin.rb", /module Admin/ assert_file "app/models/admin.rb", /def self\.table_name_prefix/ assert_file "app/models/admin.rb", /'admin_'/ - assert_file "app/models/admin/account.rb", /class Admin::Account < ActiveRecord::Base/ + assert_file "app/models/admin/account.rb", /class Admin::Account < ApplicationRecord/ end def test_migration @@ -275,7 +275,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase def test_migration_error_is_not_shown_on_revoke run_generator - error = capture(:stderr){ run_generator ["Account"], behavior: :revoke } + error = capture(:stderr) { run_generator ["Account"], behavior: :revoke } assert_no_match(/Another migration is already named create_accounts/, error) end @@ -300,7 +300,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase assert_file "test/fixtures/accounts.yml", /name: MyString/, /age: 1/ assert_generated_fixture("test/fixtures/accounts.yml", - {"one"=>{"name"=>"MyString", "age"=>1}, "two"=>{"name"=>"MyString", "age"=>1}}) + "one"=>{ "name"=>"MyString", "age"=>1 }, "two"=>{ "name"=>"MyString", "age"=>1 }) end def test_fixtures_use_the_references_ids @@ -308,7 +308,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase assert_file "test/fixtures/line_items.yml", /product: one\n cart: one/ assert_generated_fixture("test/fixtures/line_items.yml", - {"one"=>{"product"=>"one", "cart"=>"one"}, "two"=>{"product"=>"two", "cart"=>"two"}}) + "one"=>{ "product"=>"one", "cart"=>"one" }, "two"=>{ "product"=>"two", "cart"=>"two" }) end def test_fixtures_use_the_references_ids_and_type @@ -316,15 +316,15 @@ class ModelGeneratorTest < Rails::Generators::TestCase assert_file "test/fixtures/line_items.yml", /product: one\n product_type: Product\n cart: one/ assert_generated_fixture("test/fixtures/line_items.yml", - {"one"=>{"product"=>"one", "product_type"=>"Product", "cart"=>"one"}, - "two"=>{"product"=>"two", "product_type"=>"Product", "cart"=>"two"}}) + "one"=>{ "product"=>"one", "product_type"=>"Product", "cart"=>"one" }, + "two"=>{ "product"=>"two", "product_type"=>"Product", "cart"=>"two" }) end def test_fixtures_respect_reserved_yml_keywords run_generator ["LineItem", "no:integer", "Off:boolean", "ON:boolean"] assert_generated_fixture("test/fixtures/line_items.yml", - {"one"=>{"no"=>1, "Off"=>false, "ON"=>false}, "two"=>{"no"=>1, "Off"=>false, "ON"=>false}}) + "one"=>{ "no"=>1, "Off"=>false, "ON"=>false }, "two"=>{ "no"=>1, "Off"=>false, "ON"=>false }) end def test_fixture_is_skipped @@ -343,13 +343,13 @@ class ModelGeneratorTest < Rails::Generators::TestCase ActiveRecord::Base.pluralize_table_names = false run_generator assert_generated_fixture("test/fixtures/account.yml", - {"one"=>{"name"=>"MyString", "age"=>1}, "two"=>{"name"=>"MyString", "age"=>1}}) + "one"=>{ "name"=>"MyString", "age"=>1 }, "two"=>{ "name"=>"MyString", "age"=>1 }) ensure ActiveRecord::Base.pluralize_table_names = original_pluralize_table_name end def test_check_class_collision - content = capture(:stderr){ run_generator ["object"] } + content = capture(:stderr) { run_generator ["object"] } assert_match(/The name 'Object' is either already used in your application or reserved/, content) end @@ -386,7 +386,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase run_generator ["account", "supplier:references{required}"] expected_file = <<-FILE.strip_heredoc - class Account < ActiveRecord::Base + class Account < ApplicationRecord belongs_to :supplier, required: true end FILE @@ -397,7 +397,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase run_generator ["account", "supplier:references{required,polymorphic}"] expected_file = <<-FILE.strip_heredoc - class Account < ActiveRecord::Base + class Account < ApplicationRecord belongs_to :supplier, polymorphic: true, required: true end FILE @@ -408,7 +408,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase run_generator ["account", "supplier:references{polymorphic.required}"] expected_file = <<-FILE.strip_heredoc - class Account < ActiveRecord::Base + class Account < ApplicationRecord belongs_to :supplier, polymorphic: true, required: true end FILE @@ -459,7 +459,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase def test_token_option_adds_has_secure_token run_generator ["user", "token:token", "auth_token:token"] expected_file = <<-FILE.strip_heredoc - class User < ActiveRecord::Base + class User < ApplicationRecord has_secure_token has_secure_token :auth_token end diff --git a/railties/test/generators/named_base_test.rb b/railties/test/generators/named_base_test.rb index 291f5e06c3..0258b3b9d7 100644 --- a/railties/test/generators/named_base_test.rb +++ b/railties/test/generators/named_base_test.rb @@ -1,84 +1,84 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/scaffold_controller/scaffold_controller_generator" class NamedBaseTest < Rails::Generators::TestCase include GeneratorsTestHelper tests Rails::Generators::ScaffoldControllerGenerator def test_named_generator_with_underscore - g = generator ['line_item'] - assert_name g, 'line_item', :name + g = generator ["line_item"] + assert_name g, "line_item", :name assert_name g, %w(), :class_path - assert_name g, 'LineItem', :class_name - assert_name g, 'line_item', :file_path - assert_name g, 'line_item', :file_name - assert_name g, 'Line item', :human_name - assert_name g, 'line_item', :singular_name - assert_name g, 'line_items', :plural_name - assert_name g, 'line_item', :i18n_scope - assert_name g, 'line_items', :table_name + assert_name g, "LineItem", :class_name + assert_name g, "line_item", :file_path + assert_name g, "line_item", :file_name + assert_name g, "Line item", :human_name + assert_name g, "line_item", :singular_name + assert_name g, "line_items", :plural_name + assert_name g, "line_item", :i18n_scope + assert_name g, "line_items", :table_name end def test_named_generator_attributes - g = generator ['admin/foo'] - assert_name g, 'admin/foo', :name + g = generator ["admin/foo"] + assert_name g, "admin/foo", :name assert_name g, %w(admin), :class_path - assert_name g, 'Admin::Foo', :class_name - assert_name g, 'admin/foo', :file_path - assert_name g, 'foo', :file_name - assert_name g, 'Foo', :human_name - assert_name g, 'foo', :singular_name - assert_name g, 'foos', :plural_name - assert_name g, 'admin.foo', :i18n_scope - assert_name g, 'admin_foos', :table_name + assert_name g, "Admin::Foo", :class_name + assert_name g, "admin/foo", :file_path + assert_name g, "foo", :file_name + assert_name g, "Foo", :human_name + assert_name g, "foo", :singular_name + assert_name g, "foos", :plural_name + assert_name g, "admin.foo", :i18n_scope + assert_name g, "admin_foos", :table_name end def test_named_generator_attributes_as_ruby - g = generator ['Admin::Foo'] - assert_name g, 'Admin::Foo', :name + g = generator ["Admin::Foo"] + assert_name g, "Admin::Foo", :name assert_name g, %w(admin), :class_path - assert_name g, 'Admin::Foo', :class_name - assert_name g, 'admin/foo', :file_path - assert_name g, 'foo', :file_name - assert_name g, 'foo', :singular_name - assert_name g, 'Foo', :human_name - assert_name g, 'foos', :plural_name - assert_name g, 'admin.foo', :i18n_scope - assert_name g, 'admin_foos', :table_name + assert_name g, "Admin::Foo", :class_name + assert_name g, "admin/foo", :file_path + assert_name g, "foo", :file_name + assert_name g, "foo", :singular_name + assert_name g, "Foo", :human_name + assert_name g, "foos", :plural_name + assert_name g, "admin.foo", :i18n_scope + assert_name g, "admin_foos", :table_name end def test_named_generator_attributes_without_pluralized original_pluralize_table_names = ActiveRecord::Base.pluralize_table_names ActiveRecord::Base.pluralize_table_names = false - g = generator ['admin/foo'] - assert_name g, 'admin_foo', :table_name + g = generator ["admin/foo"] + assert_name g, "admin_foo", :table_name ensure ActiveRecord::Base.pluralize_table_names = original_pluralize_table_names end def test_scaffold_plural_names - g = generator ['admin/foo'] - assert_name g, 'admin/foos', :controller_name + g = generator ["admin/foo"] + assert_name g, "admin/foos", :controller_name assert_name g, %w(admin), :controller_class_path - assert_name g, 'Admin::Foos', :controller_class_name - assert_name g, 'admin/foos', :controller_file_path - assert_name g, 'foos', :controller_file_name - assert_name g, 'admin.foos', :controller_i18n_scope + assert_name g, "Admin::Foos", :controller_class_name + assert_name g, "admin/foos", :controller_file_path + assert_name g, "foos", :controller_file_name + assert_name g, "admin.foos", :controller_i18n_scope end def test_scaffold_plural_names_as_ruby - g = generator ['Admin::Foo'] - assert_name g, 'Admin::Foos', :controller_name + g = generator ["Admin::Foo"] + assert_name g, "Admin::Foos", :controller_name assert_name g, %w(admin), :controller_class_path - assert_name g, 'Admin::Foos', :controller_class_name - assert_name g, 'admin/foos', :controller_file_path - assert_name g, 'foos', :controller_file_name - assert_name g, 'admin.foos', :controller_i18n_scope + assert_name g, "Admin::Foos", :controller_class_name + assert_name g, "admin/foos", :controller_file_path + assert_name g, "foos", :controller_file_name + assert_name g, "admin.foos", :controller_i18n_scope end def test_application_name - g = generator ['Admin::Foo'] + g = generator ["Admin::Foo"] Rails.stub(:application, Object.new) do assert_name g, "object", :application_name end @@ -89,46 +89,46 @@ class NamedBaseTest < Rails::Generators::TestCase end def test_index_helper - g = generator ['Post'] - assert_name g, 'posts', :index_helper + g = generator ["Post"] + assert_name g, "posts", :index_helper end def test_index_helper_to_pluralize_once - g = generator ['Stadium'] - assert_name g, 'stadia', :index_helper + g = generator ["Stadium"] + assert_name g, "stadia", :index_helper end def test_index_helper_with_uncountable - g = generator ['Sheep'] - assert_name g, 'sheep_index', :index_helper + g = generator ["Sheep"] + assert_name g, "sheep_index", :index_helper end def test_hide_namespace - g = generator ['Hidden'] - g.class.stub(:namespace, 'hidden') do - assert !Rails::Generators.hidden_namespaces.include?('hidden') + g = generator ["Hidden"] + g.class.stub(:namespace, "hidden") do + assert_not_includes Rails::Generators.hidden_namespaces, "hidden" g.class.hide! - assert Rails::Generators.hidden_namespaces.include?('hidden') + assert_includes Rails::Generators.hidden_namespaces, "hidden" end end def test_scaffold_plural_names_with_model_name_option - g = generator ['Admin::Foo'], model_name: 'User' - assert_name g, 'user', :singular_name - assert_name g, 'User', :name - assert_name g, 'user', :file_path - assert_name g, 'User', :class_name - assert_name g, 'user', :file_name - assert_name g, 'User', :human_name - assert_name g, 'users', :plural_name - assert_name g, 'user', :i18n_scope - assert_name g, 'users', :table_name - assert_name g, 'Admin::Foos', :controller_name + g = generator ["Admin::Foo"], model_name: "User" + assert_name g, "user", :singular_name + assert_name g, "User", :name + assert_name g, "user", :file_path + assert_name g, "User", :class_name + assert_name g, "user", :file_name + assert_name g, "User", :human_name + assert_name g, "users", :plural_name + assert_name g, "user", :i18n_scope + assert_name g, "users", :table_name + assert_name g, "Admin::Foos", :controller_name assert_name g, %w(admin), :controller_class_path - assert_name g, 'Admin::Foos', :controller_class_name - assert_name g, 'admin/foos', :controller_file_path - assert_name g, 'foos', :controller_file_name - assert_name g, 'admin.foos', :controller_i18n_scope + assert_name g, "Admin::Foos", :controller_class_name + assert_name g, "admin/foos", :controller_file_path + assert_name g, "foos", :controller_file_name + assert_name g, "admin.foos", :controller_i18n_scope end protected diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb index d76759a7d1..1caabbe6b1 100644 --- a/railties/test/generators/namespaced_generators_test.rb +++ b/railties/test/generators/namespaced_generators_test.rb @@ -1,8 +1,8 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/controller/controller_generator' -require 'rails/generators/rails/model/model_generator' -require 'rails/generators/mailer/mailer_generator' -require 'rails/generators/rails/scaffold/scaffold_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/controller/controller_generator" +require "rails/generators/rails/model/model_generator" +require "rails/generators/mailer/mailer_generator" +require "rails/generators/rails/scaffold/scaffold_generator" class NamespacedGeneratorTestCase < Rails::Generators::TestCase include GeneratorsTestHelper @@ -91,7 +91,7 @@ class NamespacedModelGeneratorTest < NamespacedGeneratorTestCase def test_adds_namespace_to_model run_generator - assert_file "app/models/test_app/account.rb", /module TestApp/, / class Account < ActiveRecord::Base/ + assert_file "app/models/test_app/account.rb", /module TestApp/, / class Account < ApplicationRecord/ end def test_model_with_namespace @@ -99,7 +99,7 @@ class NamespacedModelGeneratorTest < NamespacedGeneratorTestCase assert_file "app/models/test_app/admin.rb", /module TestApp/, /module Admin/ assert_file "app/models/test_app/admin.rb", /def self\.table_name_prefix/ assert_file "app/models/test_app/admin.rb", /'test_app_admin_'/ - assert_file "app/models/test_app/admin/account.rb", /module TestApp/, /class Admin::Account < ActiveRecord::Base/ + assert_file "app/models/test_app/admin/account.rb", /module TestApp/, /class Admin::Account < ApplicationRecord/ end def test_migration @@ -201,7 +201,7 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase run_generator # Model - assert_file "app/models/test_app/product_line.rb", /module TestApp\n class ProductLine < ActiveRecord::Base/ + assert_file "app/models/test_app/product_line.rb", /module TestApp\n class ProductLine < ApplicationRecord/ assert_file "test/models/test_app/product_line_test.rb", /module TestApp\n class ProductLineTest < ActiveSupport::TestCase/ assert_file "test/fixtures/test_app/product_lines.yml" assert_migration "db/migrate/create_test_app_product_lines.rb" @@ -268,7 +268,7 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase # Model assert_file "app/models/test_app/admin.rb", /module TestApp\n module Admin/ - assert_file "app/models/test_app/admin/role.rb", /module TestApp\n class Admin::Role < ActiveRecord::Base/ + assert_file "app/models/test_app/admin/role.rb", /module TestApp\n class Admin::Role < ApplicationRecord/ assert_file "test/models/test_app/admin/role_test.rb", /module TestApp\n class Admin::RoleTest < ActiveSupport::TestCase/ assert_file "test/fixtures/test_app/admin/roles.yml" assert_migration "db/migrate/create_test_app_admin_roles.rb" @@ -336,7 +336,7 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase # Model assert_file "app/models/test_app/admin/user/special.rb", /module TestApp\n module Admin/ - assert_file "app/models/test_app/admin/user/special/role.rb", /module TestApp\n class Admin::User::Special::Role < ActiveRecord::Base/ + assert_file "app/models/test_app/admin/user/special/role.rb", /module TestApp\n class Admin::User::Special::Role < ApplicationRecord/ assert_file "test/models/test_app/admin/user/special/role_test.rb", /module TestApp\n class Admin::User::Special::RoleTest < ActiveSupport::TestCase/ assert_file "test/fixtures/test_app/admin/user/special/roles.yml" assert_migration "db/migrate/create_test_app_admin_user_special_roles.rb" @@ -402,7 +402,7 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase # Model assert_file "app/models/test_app/admin.rb", /module TestApp\n module Admin/ - assert_file "app/models/test_app/admin/role.rb", /module TestApp\n class Admin::Role < ActiveRecord::Base/ + assert_file "app/models/test_app/admin/role.rb", /module TestApp\n class Admin::Role < ApplicationRecord/ assert_file "test/models/test_app/admin/role_test.rb", /module TestApp\n class Admin::RoleTest < ActiveSupport::TestCase/ assert_file "test/fixtures/test_app/admin/roles.yml" assert_migration "db/migrate/create_test_app_admin_roles.rb" diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb index 3cc8e1de55..15079f2735 100644 --- a/railties/test/generators/plugin_generator_test.rb +++ b/railties/test/generators/plugin_generator_test.rb @@ -1,6 +1,6 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/plugin/plugin_generator' -require 'generators/shared_generator_tests' +require "generators/generators_test_helper" +require "rails/generators/rails/plugin/plugin_generator" +require "generators/shared_generator_tests" DEFAULT_PLUGIN_FILES = %w( .gitignore @@ -27,19 +27,19 @@ class PluginGeneratorTest < Rails::Generators::TestCase include SharedGeneratorTests def test_invalid_plugin_name_raises_an_error - content = capture(:stderr){ run_generator [File.join(destination_root, "my_plugin-31fr-extension")] } + content = capture(:stderr) { run_generator [File.join(destination_root, "my_plugin-31fr-extension")] } assert_equal "Invalid plugin name my_plugin-31fr-extension. Please give a name which does not contain a namespace starting with numeric characters.\n", content - content = capture(:stderr){ run_generator [File.join(destination_root, "things4.3")] } + content = capture(:stderr) { run_generator [File.join(destination_root, "things4.3")] } assert_equal "Invalid plugin name things4.3. Please give a name which uses only alphabetic, numeric, \"_\" or \"-\" characters.\n", content - content = capture(:stderr){ run_generator [File.join(destination_root, "43things")] } + content = capture(:stderr) { run_generator [File.join(destination_root, "43things")] } assert_equal "Invalid plugin name 43things. Please give a name which does not start with numbers.\n", content - content = capture(:stderr){ run_generator [File.join(destination_root, "plugin")] } + content = capture(:stderr) { run_generator [File.join(destination_root, "plugin")] } assert_equal "Invalid plugin name plugin. Please give a name which does not match one of the reserved rails words: application, destroy, plugin, runner, test\n", content - content = capture(:stderr){ run_generator [File.join(destination_root, "Digest")] } + content = capture(:stderr) { run_generator [File.join(destination_root, "Digest")] } assert_equal "Invalid plugin name Digest, constant Digest is already in use. Please choose another plugin name.\n", content end @@ -68,8 +68,8 @@ class PluginGeneratorTest < Rails::Generators::TestCase assert_match(/Rails::TestUnitReporter\.executable = 'bin\/test'/, content) end assert_file "test/bukkits_test.rb", /assert_kind_of Module, Bukkits/ - assert_file 'bin/test' - assert_no_file 'bin/rails' + assert_file "bin/test" + assert_no_file "bin/rails" end def test_generating_test_files_in_full_mode @@ -80,7 +80,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase end def test_inclusion_of_a_debugger - run_generator [destination_root, '--full'] + run_generator [destination_root, "--full"] if defined?(JRUBY_VERSION) || RUBY_ENGINE == "rbx" assert_file "Gemfile" do |content| assert_no_match(/byebug/, content) @@ -101,7 +101,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase end def test_generating_adds_dummy_app_rake_tasks_without_unit_test_files - run_generator [destination_root, "-T", "--mountable", '--dummy-path', 'my_dummy_app'] + run_generator [destination_root, "-T", "--mountable", "--dummy-path", "my_dummy_app"] assert_file "Rakefile", /APP_RAKEFILE/ end @@ -193,13 +193,24 @@ class PluginGeneratorTest < Rails::Generators::TestCase assert_file "test/dummy/config/database.yml", /postgres/ end - def test_generation_runs_bundle_install_with_full_and_mountable - result = run_generator [destination_root, "--mountable", "--full", "--dev"] - assert_match(/run bundle install/, result) - assert $?.success?, "Command failed: #{result}" - assert_file "#{destination_root}/Gemfile.lock" do |contents| - assert_match(/bukkits/, contents) - end + def test_generation_runs_bundle_install + assert_generates_without_bundler + end + + def test_dev_option + assert_generates_without_bundler(dev: true) + rails_path = File.expand_path("../../..", Rails.root) + assert_file "Gemfile", /^gem\s+["']rails["'],\s+path:\s+["']#{Regexp.escape(rails_path)}["']$/ + end + + def test_edge_option + assert_generates_without_bundler(edge: true) + assert_file "Gemfile", %r{^gem\s+["']rails["'],\s+github:\s+["']#{Regexp.escape("rails/rails")}["']$} + end + + def test_generation_does_not_run_bundle_install_with_full_and_mountable + assert_generates_without_bundler(mountable: true, full: true, dev: true) + assert_no_file "#{destination_root}/Gemfile.lock" end def test_skipping_javascripts_without_mountable_option @@ -225,21 +236,21 @@ class PluginGeneratorTest < Rails::Generators::TestCase def test_ensure_that_tests_work run_generator FileUtils.cd destination_root - quietly { system 'bundle install' } + quietly { system "bundle install" } assert_match(/1 runs, 1 assertions, 0 failures, 0 errors/, `bin/test 2>&1`) end def test_ensure_that_tests_works_in_full_mode run_generator [destination_root, "--full", "--skip_active_record"] FileUtils.cd destination_root - quietly { system 'bundle install' } + quietly { system "bundle install" } assert_match(/1 runs, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test 2>&1`) end def test_ensure_that_migration_tasks_work_with_mountable_option run_generator [destination_root, "--mountable"] FileUtils.cd destination_root - quietly { system 'bundle install' } + quietly { system "bundle install" } output = `bin/rails db:migrate 2>&1` assert $?.success?, "Command failed: #{output}" end @@ -322,7 +333,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase assert_match(/ActionDispatch::IntegrationTest\.fixture_path = ActiveSupport::TestCase\.fixture_pat/, content) assert_no_match(/Rails::TestUnitReporter\.executable = 'bin\/test'/, content) end - assert_no_file 'bin/test' + assert_no_file "bin/test" end def test_create_mountable_application_with_mountable_option_and_hypenated_name @@ -439,7 +450,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase assert_file "spec/dummy/config/application.rb" assert_no_file "test" assert_no_file "test/test_helper.rb" - assert_file '.gitignore' do |contents| + assert_file ".gitignore" do |contents| assert_match(/spec\/dummy/, contents) end end @@ -447,7 +458,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase def test_dummy_appplication_skip_listen_by_default run_generator - assert_file 'test/dummy/config/environments/development.rb' do |contents| + assert_file "test/dummy/config/environments/development.rb" do |contents| assert_match(/^\s*# config.file_watcher = ActiveSupport::EventedFileUpdateChecker/, contents) end end @@ -462,21 +473,21 @@ class PluginGeneratorTest < Rails::Generators::TestCase def test_unnecessary_files_are_not_generated_in_dummy_application run_generator - assert_no_file 'test/dummy/.gitignore' - assert_no_file 'test/dummy/db/seeds.rb' - assert_no_file 'test/dummy/Gemfile' - assert_no_file 'test/dummy/public/robots.txt' - assert_no_file 'test/dummy/README.md' - assert_no_directory 'test/dummy/lib/tasks' - assert_no_directory 'test/dummy/doc' - assert_no_directory 'test/dummy/test' - assert_no_directory 'test/dummy/vendor' + assert_no_file "test/dummy/.gitignore" + assert_no_file "test/dummy/db/seeds.rb" + assert_no_file "test/dummy/Gemfile" + assert_no_file "test/dummy/public/robots.txt" + assert_no_file "test/dummy/README.md" + assert_no_directory "test/dummy/lib/tasks" + assert_no_directory "test/dummy/doc" + assert_no_directory "test/dummy/test" + assert_no_directory "test/dummy/vendor" end def test_skipping_test_files run_generator [destination_root, "--skip-test"] assert_no_file "test" - assert_file '.gitignore' do |contents| + assert_file ".gitignore" do |contents| assert_no_match(/test\dummy/, contents) end end @@ -485,7 +496,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase run_generator [destination_root, "--skip-gemspec"] assert_no_file "bukkits.gemspec" assert_file "Gemfile" do |contents| - assert_no_match('gemspec', contents) + assert_no_match("gemspec", contents) assert_match(/gem 'rails'/, contents) assert_match_sqlite3(contents) assert_no_match(/# gem "jquery-rails"/, contents) @@ -496,7 +507,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase run_generator [destination_root, "--skip-gemspec", "--full"] assert_no_file "bukkits.gemspec" assert_file "Gemfile" do |contents| - assert_no_match('gemspec', contents) + assert_no_match("gemspec", contents) assert_match(/gem 'rails'/, contents) assert_match_sqlite3(contents) end @@ -505,21 +516,21 @@ class PluginGeneratorTest < Rails::Generators::TestCase def test_creating_plugin_in_app_directory_adds_gemfile_entry # simulate application existence gemfile_path = "#{Rails.root}/Gemfile" - Object.const_set('APP_PATH', Rails.root) + Object.const_set("APP_PATH", Rails.root) FileUtils.touch gemfile_path run_generator assert_file gemfile_path, /gem 'bukkits', path: 'tmp\/bukkits'/ ensure - Object.send(:remove_const, 'APP_PATH') + Object.send(:remove_const, "APP_PATH") FileUtils.rm gemfile_path end def test_skipping_gemfile_entry # simulate application existence gemfile_path = "#{Rails.root}/Gemfile" - Object.const_set('APP_PATH', Rails.root) + Object.const_set("APP_PATH", Rails.root) FileUtils.touch gemfile_path run_generator [destination_root, "--skip-gemfile-entry"] @@ -528,7 +539,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase assert_no_match(/gem 'bukkits', path: 'tmp\/bukkits'/, contents) end ensure - Object.send(:remove_const, 'APP_PATH') + Object.send(:remove_const, "APP_PATH") FileUtils.rm gemfile_path end @@ -569,7 +580,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase name = "TODO: Write your name" email = "TODO: Write your email address" - run_generator [destination_root, '--skip-git'] + run_generator [destination_root, "--skip-git"] assert_file "MIT-LICENSE" do |contents| assert_match name, contents end @@ -580,8 +591,8 @@ class PluginGeneratorTest < Rails::Generators::TestCase end def test_skipping_useless_folders_generation_for_api_engines - ['--full', '--mountable'].each do |option| - run_generator [destination_root, option, '--api'] + ["--full", "--mountable"].each do |option| + run_generator [destination_root, option, "--api"] assert_no_directory "app/assets" assert_no_directory "app/helpers" @@ -592,7 +603,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase end def test_application_controller_parent_for_mountable_api_plugins - run_generator [destination_root, '--mountable', '--api'] + run_generator [destination_root, "--mountable", "--api"] assert_file "app/controllers/bukkits/application_controller.rb" do |content| assert_match "ApplicationController < ActionController::API", content @@ -600,16 +611,15 @@ class PluginGeneratorTest < Rails::Generators::TestCase end def test_dummy_api_application_for_api_plugins - run_generator [destination_root, '--api'] + run_generator [destination_root, "--api"] assert_file "test/dummy/config/application.rb" do |content| assert_match "config.api_only = true", content end end - def test_api_generators_configuration_for_api_engines - run_generator [destination_root, '--full', '--api'] + run_generator [destination_root, "--full", "--api"] assert_file "lib/bukkits/engine.rb" do |content| assert_match "config.generators.api_only = true", content @@ -617,7 +627,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase end def test_scaffold_generator_for_mountable_api_plugins - run_generator [destination_root, '--mountable', '--api'] + run_generator [destination_root, "--mountable", "--api"] capture(:stdout) do `#{destination_root}/bin/rails g scaffold article` @@ -634,7 +644,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase end def test_model_with_existent_application_record_in_mountable_engine - run_generator [destination_root, '--mountable'] + run_generator [destination_root, "--mountable"] capture(:stdout) do `#{destination_root}/bin/rails g model article` end @@ -643,7 +653,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase end def test_generate_application_record_when_does_not_exist_in_mountable_engine - run_generator [destination_root, '--mountable'] + run_generator [destination_root, "--mountable"] FileUtils.rm "#{destination_root}/app/models/bukkits/application_record.rb" capture(:stdout) do `#{destination_root}/bin/rails g model article` @@ -657,7 +667,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase end def test_generate_application_mailer_when_does_not_exist_in_mountable_engine - run_generator [destination_root, '--mountable'] + run_generator [destination_root, "--mountable"] FileUtils.rm "#{destination_root}/app/mailers/bukkits/application_mailer.rb" capture(:stdout) do `#{destination_root}/bin/rails g mailer User` @@ -669,8 +679,23 @@ class PluginGeneratorTest < Rails::Generators::TestCase end end + def test_generate_mailer_layouts_when_does_not_exist_in_mountable_engine + run_generator [destination_root, "--mountable"] + capture(:stdout) do + `#{destination_root}/bin/rails g mailer User` + end + + assert_file "#{destination_root}/app/views/layouts/bukkits/mailer.text.erb" do |view| + assert_match(/<%= yield %>/, view) + end + + assert_file "#{destination_root}/app/views/layouts/bukkits/mailer.html.erb" do |view| + assert_match(%r{<body>\n <%= yield %>\n </body>}, view) + end + end + def test_generate_application_job_when_does_not_exist_in_mountable_engine - run_generator [destination_root, '--mountable'] + run_generator [destination_root, "--mountable"] FileUtils.rm "#{destination_root}/app/jobs/bukkits/application_job.rb" capture(:stdout) do `#{destination_root}/bin/rails g job refresh_counters` @@ -682,48 +707,38 @@ class PluginGeneratorTest < 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 + protected - check_open = -> *args do - assert_equal [ path, 'Accept' => 'application/x-thor-template' ], args - template + def action(*args, &block) + silence(:stdout) { generator.send(*args, &block) } end - sequence = ['install', 'echo ran after_bundle'] - @sequence_step ||= 0 - ensure_bundler_first = -> command do - assert_equal sequence[@sequence_step], command, "commands should be called in sequence #{sequence}" - @sequence_step += 1 + def default_files + ::DEFAULT_PLUGIN_FILES end - generator([destination_root], template: path).stub(:open, check_open, template) do - generator.stub(:bundle_command, ensure_bundler_first) do - generator.stub(:run, ensure_bundler_first) do - quietly { generator.invoke_all } - end + def assert_match_sqlite3(contents) + 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 - assert_equal 2, @sequence_step - end + def assert_generates_without_bundler(options = {}) + generator([destination_root], options) -protected - def action(*args, &block) - silence(:stdout){ generator.send(*args, &block) } - end - - def default_files - ::DEFAULT_PLUGIN_FILES - end + command_check = -> command do + case command + when "install" + flunk "install expected to not be called" + when "exec spring binstub --all" + # Called when running tests with spring, let through unscathed. + end + end - def assert_match_sqlite3(contents) - 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) + generator.stub :bundle_command, command_check do + quietly { generator.invoke_all } + end end - end end diff --git a/railties/test/generators/plugin_test_helper.rb b/railties/test/generators/plugin_test_helper.rb index 96c1b1d31f..8ac90e3484 100644 --- a/railties/test/generators/plugin_test_helper.rb +++ b/railties/test/generators/plugin_test_helper.rb @@ -1,5 +1,5 @@ -require 'abstract_unit' -require 'tmpdir' +require "abstract_unit" +require "tmpdir" module PluginTestHelper def create_test_file(name, pass: true) @@ -15,7 +15,7 @@ module PluginTestHelper RUBY end - def plugin_file(path, contents, mode: 'w') + def plugin_file(path, contents, mode: "w") FileUtils.mkdir_p File.dirname("#{plugin_path}/#{path}") File.open("#{plugin_path}/#{path}", mode) do |f| f.puts contents diff --git a/railties/test/generators/plugin_test_runner_test.rb b/railties/test/generators/plugin_test_runner_test.rb index ef6359fece..7a10a2afa9 100644 --- a/railties/test/generators/plugin_test_runner_test.rb +++ b/railties/test/generators/plugin_test_runner_test.rb @@ -1,12 +1,12 @@ -require 'generators/plugin_test_helper' +require "generators/plugin_test_helper" class PluginTestRunnerTest < ActiveSupport::TestCase include PluginTestHelper def setup - @destination_root = Dir.mktmpdir('bukkits') + @destination_root = Dir.mktmpdir("bukkits") Dir.chdir(@destination_root) { `bundle exec rails plugin new bukkits --skip-bundle` } - plugin_file 'test/dummy/db/schema.rb', '' + plugin_file "test/dummy/db/schema.rb", "" end def teardown @@ -14,20 +14,20 @@ class PluginTestRunnerTest < ActiveSupport::TestCase end def test_run_single_file - create_test_file 'foo' - create_test_file 'bar' + create_test_file "foo" + create_test_file "bar" assert_match "1 runs, 1 assertions, 0 failures", run_test_command("test/foo_test.rb") end def test_run_multiple_files - create_test_file 'foo' - create_test_file 'bar' + create_test_file "foo" + create_test_file "bar" assert_match "2 runs, 2 assertions, 0 failures", run_test_command("test/foo_test.rb test/bar_test.rb") end def test_mix_files_and_line_filters - create_test_file 'account' - plugin_file 'test/post_test.rb', <<-RUBY + create_test_file "account" + plugin_file "test/post_test.rb", <<-RUBY require 'test_helper' class PostTest < ActiveSupport::TestCase @@ -42,50 +42,56 @@ class PluginTestRunnerTest < ActiveSupport::TestCase end RUBY - run_test_command('test/account_test.rb test/post_test.rb:4').tap do |output| - assert_match 'AccountTest', output - assert_match 'PostTest', output - assert_match '2 runs, 2 assertions', output + run_test_command("test/account_test.rb test/post_test.rb:4").tap do |output| + assert_match "AccountTest", output + assert_match "PostTest", output + assert_match "2 runs, 2 assertions", output end end def test_multiple_line_filters - create_test_file 'account' - create_test_file 'post' + create_test_file "account" + create_test_file "post" - run_test_command('test/account_test.rb:4 test/post_test.rb:4').tap do |output| - assert_match 'AccountTest', output - assert_match 'PostTest', output + run_test_command("test/account_test.rb:4 test/post_test.rb:4").tap do |output| + assert_match "AccountTest", output + assert_match "PostTest", output end end def test_output_inline_by_default - create_test_file 'post', pass: false + create_test_file "post", pass: false - output = run_test_command('test/post_test.rb') + output = run_test_command("test/post_test.rb") expect = %r{Running:\n\nPostTest\nF\n\nFailure:\nPostTest#test_truth \[[^\]]+test/post_test.rb:6\]:\nwups!\n\nbin/test (/private)?#{plugin_path}/test/post_test.rb:4} assert_match expect, output end def test_only_inline_failure_output - create_test_file 'post', pass: false + create_test_file "post", pass: false - output = run_test_command('test/post_test.rb') + output = run_test_command("test/post_test.rb") assert_match %r{Finished in.*\n\n1 runs, 1 assertions}, output end def test_fail_fast - create_test_file 'post', pass: false + create_test_file "post", pass: false assert_match(/Interrupt/, - capture(:stderr) { run_test_command('test/post_test.rb --fail-fast') }) + capture(:stderr) { run_test_command("test/post_test.rb --fail-fast") }) end def test_raise_error_when_specified_file_does_not_exist - error = capture(:stderr) { run_test_command('test/not_exists.rb') } + error = capture(:stderr) { run_test_command("test/not_exists.rb") } assert_match(%r{cannot load such file.+test/not_exists\.rb}, error) end + def test_executed_only_once + create_test_file "foo" + result = run_test_command("test/foo_test.rb") + assert_equal 1, result.scan(/1 runs, 1 assertions, 0 failures/).length + end + private def plugin_path "#{@destination_root}/bukkits" diff --git a/railties/test/generators/resource_generator_test.rb b/railties/test/generators/resource_generator_test.rb index addaf83bc8..e976e58180 100644 --- a/railties/test/generators/resource_generator_test.rb +++ b/railties/test/generators/resource_generator_test.rb @@ -1,5 +1,5 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/resource/resource_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/resource/resource_generator" class ResourceGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -60,14 +60,14 @@ class ResourceGeneratorTest < Rails::Generators::TestCase def test_plural_names_are_singularized content = run_generator ["accounts".freeze] - assert_file "app/models/account.rb", /class Account < ActiveRecord::Base/ + assert_file "app/models/account.rb", /class Account < ApplicationRecord/ assert_file "test/models/account_test.rb", /class AccountTest/ assert_match(/\[WARNING\] The model name 'accounts' was recognized as a plural, using the singular 'account' instead\. Override with --force-plural or setup custom inflection rules for this noun before running the generator\./, content) end def test_plural_names_can_be_forced content = run_generator ["accounts", "--force-plural"] - assert_file "app/models/accounts.rb", /class Accounts < ActiveRecord::Base/ + assert_file "app/models/accounts.rb", /class Accounts < ApplicationRecord/ assert_file "test/models/accounts_test.rb", /class AccountsTest/ assert_no_match(/\[WARNING\]/, content) end diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb index c37e289f4b..bd23faf268 100644 --- a/railties/test/generators/scaffold_controller_generator_test.rb +++ b/railties/test/generators/scaffold_controller_generator_test.rb @@ -1,5 +1,5 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/scaffold_controller/scaffold_controller_generator" module Unknown module Generators @@ -238,8 +238,8 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase assert_file "test/controllers/users_controller_test.rb" do |content| assert_match(/class UsersControllerTest < ActionDispatch::IntegrationTest/, content) assert_match(/test "should get index"/, content) - assert_match(/post users_url, params: \{ user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}/, content) - assert_match(/patch user_url\(@user\), params: \{ user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}/, content) + assert_match(/post users_url, params: \{ user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}, as: :json/, content) + assert_match(/patch user_url\(@user\), params: \{ user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}, as: :json/, content) assert_no_match(/assert_redirected_to/, content) end end diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb index 5e45120704..6b7e2c91d7 100644 --- a/railties/test/generators/scaffold_generator_test.rb +++ b/railties/test/generators/scaffold_generator_test.rb @@ -1,5 +1,5 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/scaffold/scaffold_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/scaffold/scaffold_generator" class ScaffoldGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -11,7 +11,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase run_generator # Model - assert_file "app/models/product_line.rb", /class ProductLine < ActiveRecord::Base/ + assert_file "app/models/product_line.rb", /class ProductLine < ApplicationRecord/ assert_file "test/models/product_line_test.rb", /class ProductLineTest < ActiveSupport::TestCase/ assert_file "test/fixtures/product_lines.yml" assert_migration "db/migrate/create_product_lines.rb", /belongs_to :product/ @@ -74,8 +74,8 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase end assert_file "app/views/product_lines/_form.html.erb" do |test| - assert_match 'product_line', test - assert_no_match '@product_line', test + assert_match "product_line", test + assert_no_match "@product_line", test end # Helpers @@ -91,7 +91,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase run_generator %w(product_line title:string product:belongs_to user:references --api --no-template-engine --no-helper --no-assets) # Model - assert_file "app/models/product_line.rb", /class ProductLine < ActiveRecord::Base/ + assert_file "app/models/product_line.rb", /class ProductLine < ApplicationRecord/ assert_file "test/models/product_line_test.rb", /class ProductLineTest < ActiveSupport::TestCase/ assert_file "test/fixtures/product_lines.yml" assert_migration "db/migrate/create_product_lines.rb", /belongs_to :product/ @@ -205,7 +205,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase # Model assert_file "app/models/admin.rb", /module Admin/ - assert_file "app/models/admin/role.rb", /class Admin::Role < ActiveRecord::Base/ + assert_file "app/models/admin/role.rb", /class Admin::Role < ApplicationRecord/ assert_file "test/models/admin/role_test.rb", /class Admin::RoleTest < ActiveSupport::TestCase/ assert_file "test/fixtures/admin/roles.yml" assert_migration "db/migrate/create_admin_roles.rb" @@ -269,7 +269,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase def test_scaffold_with_namespace_on_revoke run_generator [ "admin/role", "name:string", "description:string" ] - run_generator [ "admin/role" ], :behavior => :revoke + run_generator [ "admin/role" ], behavior: :revoke # Model assert_file "app/models/admin.rb" # ( should not be remove ) @@ -310,7 +310,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase end File.open(route_path, "wb") { |file| file.write(content) } - run_generator ["product_line"], :behavior => :revoke + run_generator ["product_line"], behavior: :revoke assert_file "config/routes.rb", /\.routes\.draw do\s*\|map\|\s*$/ end @@ -322,13 +322,13 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase content = File.read(route_path) # Remove all of the comments and blank lines from the routes file - content.gsub!(/^ \#.*\n/, '') - content.gsub!(/^\n/, '') + content.gsub!(/^ \#.*\n/, "") + content.gsub!(/^\n/, "") File.open(route_path, "wb") { |file| file.write(content) } assert_file "config/routes.rb", /\.routes\.draw do\n resources :product_lines\nend\n\z/ - run_generator ["product_line"], :behavior => :revoke + run_generator ["product_line"], behavior: :revoke assert_file "config/routes.rb", /\.routes\.draw do\nend\n\z/ end @@ -488,7 +488,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase `bin/rails g scaffold User name:string age:integer; bin/rails db:migrate` end - assert_match(/8 runs, 13 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`) + assert_match(/8 runs, 10 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`) end end @@ -502,7 +502,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase `bin/rails g scaffold User name:string age:integer; bin/rails db:migrate` end - assert_match(/8 runs, 13 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`) + assert_match(/8 runs, 10 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`) end end diff --git a/railties/test/generators/shared_generator_tests.rb b/railties/test/generators/shared_generator_tests.rb index e83d54890a..27b2fc8955 100644 --- a/railties/test/generators/shared_generator_tests.rb +++ b/railties/test/generators/shared_generator_tests.rb @@ -5,7 +5,7 @@ module SharedGeneratorTests def setup Rails.application = TestApp::Application super - Rails::Generators::AppGenerator.instance_variable_set('@desc', nil) + Rails::Generators::AppGenerator.instance_variable_set("@desc", nil) Kernel::silence_warnings do Thor::Base.shell.send(:attr_accessor, :always_force) @@ -16,7 +16,7 @@ module SharedGeneratorTests def teardown super - Rails::Generators::AppGenerator.instance_variable_set('@desc', nil) + Rails::Generators::AppGenerator.instance_variable_set("@desc", nil) Rails.application = TestApp::Application.instance end @@ -26,37 +26,13 @@ module SharedGeneratorTests default_files.each { |path| assert_file path } end - def assert_generates_with_bundler(options = {}) - generator([destination_root], options) - - command_check = -> command do - @install_called ||= 0 - - case command - when 'install' - @install_called += 1 - assert_equal 1, @install_called, "install expected to be called once, but was called #{@install_called} times" - when 'exec spring binstub --all' - # Called when running tests with spring, let through unscathed. - end - end - - generator.stub :bundle_command, command_check do - quietly { generator.invoke_all } - end - end - - def test_generation_runs_bundle_install - assert_generates_with_bundler - end - def test_plugin_new_generate_pretend run_generator ["testapp", "--pretend"] - default_files.each{ |path| assert_no_file File.join("testapp",path) } + default_files.each { |path| assert_no_file File.join("testapp",path) } end def test_invalid_database_option_raises_an_error - content = capture(:stderr){ run_generator([destination_root, "-d", "unknown"]) } + content = capture(:stderr) { run_generator([destination_root, "-d", "unknown"]) } assert_match(/Invalid value for \-\-database option/, content) end @@ -68,14 +44,14 @@ module SharedGeneratorTests def test_name_collision_raises_an_error reserved_words = %w[application destroy plugin runner test] reserved_words.each do |reserved| - content = capture(:stderr){ run_generator [File.join(destination_root, reserved)] } + content = capture(:stderr) { run_generator [File.join(destination_root, reserved)] } assert_match(/Invalid \w+ name #{reserved}. Please give a name which does not match one of the reserved rails words: application, destroy, plugin, runner, test\n/, content) end end def test_name_raises_an_error_if_name_already_used_constant %w{ String Hash Class Module Set Symbol }.each do |ruby_class| - content = capture(:stderr){ run_generator [File.join(destination_root, ruby_class)] } + content = capture(:stderr) { run_generator [File.join(destination_root, ruby_class)] } assert_match(/Invalid \w+ name #{ruby_class}, constant #{ruby_class} is already in use. Please choose another \w+ name.\n/, content) end end @@ -92,7 +68,7 @@ module SharedGeneratorTests def test_template_raises_an_error_with_invalid_path quietly do - content = capture(:stderr){ run_generator([destination_root, "-m", "non/existent/path"]) } + content = capture(:stderr) { run_generator([destination_root, "-m", "non/existent/path"]) } assert_match(/The template \[.*\] could not be loaded/, content) assert_match(/non\/existent\/path/, content) @@ -105,7 +81,7 @@ module SharedGeneratorTests template.instance_eval "def read; self; end" # Make the string respond to read check_open = -> *args do - assert_equal [ path, 'Accept' => 'application/x-thor-template' ], args + assert_equal [ path, "Accept" => "application/x-thor-template" ], args template end @@ -114,21 +90,10 @@ module SharedGeneratorTests end end - def test_dev_option - assert_generates_with_bundler dev: true - rails_path = File.expand_path('../../..', Rails.root) - assert_file 'Gemfile', /^gem\s+["']rails["'],\s+path:\s+["']#{Regexp.escape(rails_path)}["']$/ - end - - def test_edge_option - assert_generates_with_bundler edge: true - assert_file 'Gemfile', %r{^gem\s+["']rails["'],\s+github:\s+["']#{Regexp.escape("rails/rails")}["']$} - end - def test_skip_gemfile assert_not_called(generator([destination_root], skip_gemfile: true), :bundle_command) do quietly { generator.invoke_all } - assert_no_file 'Gemfile' + assert_no_file "Gemfile" end end @@ -137,22 +102,22 @@ module SharedGeneratorTests quietly { generator.invoke_all } # skip_bundle is only about running bundle install, ensure the Gemfile is still # generated. - assert_file 'Gemfile' + assert_file "Gemfile" end end def test_skip_git - run_generator [destination_root, '--skip-git', '--full'] - assert_no_file('.gitignore') + run_generator [destination_root, "--skip-git", "--full"] + assert_no_file(".gitignore") end def test_skip_keeps - run_generator [destination_root, '--skip-keeps', '--full'] + run_generator [destination_root, "--skip-keeps", "--full"] - assert_file '.gitignore' do |content| + assert_file ".gitignore" do |content| assert_no_match(/\.keep/, content) end - assert_no_file('app/models/concerns/.keep') + assert_no_file("app/models/concerns/.keep") end end diff --git a/railties/test/generators/task_generator_test.rb b/railties/test/generators/task_generator_test.rb index d5bd44b9db..2285534bb9 100644 --- a/railties/test/generators/task_generator_test.rb +++ b/railties/test/generators/task_generator_test.rb @@ -1,5 +1,5 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/task/task_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/task/task_generator" class TaskGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -15,10 +15,10 @@ class TaskGeneratorTest < Rails::Generators::TestCase end def test_task_on_revoke - task_path = 'lib/tasks/feeds.rake' + task_path = "lib/tasks/feeds.rake" run_generator assert_file task_path - run_generator ['feeds'], behavior: :revoke + run_generator ["feeds"], behavior: :revoke assert_no_file task_path end end diff --git a/railties/test/generators/test_runner_in_engine_test.rb b/railties/test/generators/test_runner_in_engine_test.rb index d37e261fbb..4b5fb3ba3f 100644 --- a/railties/test/generators/test_runner_in_engine_test.rb +++ b/railties/test/generators/test_runner_in_engine_test.rb @@ -1,12 +1,12 @@ -require 'generators/plugin_test_helper' +require "generators/plugin_test_helper" class TestRunnerInEngineTest < ActiveSupport::TestCase include PluginTestHelper def setup - @destination_root = Dir.mktmpdir('bukkits') + @destination_root = Dir.mktmpdir("bukkits") Dir.chdir(@destination_root) { `bundle exec rails plugin new bukkits --full --skip-bundle` } - plugin_file 'test/dummy/db/schema.rb', '' + plugin_file "test/dummy/db/schema.rb", "" end def teardown @@ -14,9 +14,9 @@ class TestRunnerInEngineTest < ActiveSupport::TestCase end def test_rerun_snippet_is_relative_path - create_test_file 'post', pass: false + create_test_file "post", pass: false - output = run_test_command('test/post_test.rb') + output = run_test_command("test/post_test.rb") expect = %r{Running:\n\nPostTest\nF\n\nFailure:\nPostTest#test_truth \[[^\]]+test/post_test.rb:6\]:\nwups!\n\nbin/rails test test/post_test.rb:4} assert_match expect, output end diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index 291415858c..68ba435393 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -1,6 +1,6 @@ -require 'generators/generators_test_helper' -require 'rails/generators/rails/model/model_generator' -require 'rails/generators/test_unit/model/model_generator' +require "generators/generators_test_helper" +require "rails/generators/rails/model/model_generator" +require "rails/generators/test_unit/model/model_generator" class GeneratorsTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -15,7 +15,7 @@ class GeneratorsTest < Rails::Generators::TestCase end def test_simple_invoke - assert File.exist?(File.join(@path, 'generators', 'model_generator.rb')) + assert File.exist?(File.join(@path, "generators", "model_generator.rb")) assert_called_with(TestUnit::Generators::ModelGenerator, :start, [["Account"], {}]) do Rails::Generators.invoke("test_unit:model", ["Account"]) end @@ -23,32 +23,32 @@ class GeneratorsTest < Rails::Generators::TestCase def test_invoke_when_generator_is_not_found name = :unknown - output = capture(:stdout){ Rails::Generators.invoke name } + output = capture(:stdout) { Rails::Generators.invoke name } assert_match "Could not find generator '#{name}'", output assert_match "`rails generate --help`", output end def test_generator_suggestions name = :migrationz - output = capture(:stdout){ Rails::Generators.invoke name } + output = capture(:stdout) { Rails::Generators.invoke name } assert_match "Maybe you meant 'migration'", output end def test_generator_multiple_suggestions name = :tas - output = capture(:stdout){ Rails::Generators.invoke name } + output = capture(:stdout) { Rails::Generators.invoke name } assert_match "Maybe you meant 'task', 'job' or", output end def test_help_when_a_generator_with_required_arguments_is_invoked_without_arguments - output = capture(:stdout){ Rails::Generators.invoke :model, [] } + output = capture(:stdout) { Rails::Generators.invoke :model, [] } assert_match(/Description:/, output) end def test_should_give_higher_preference_to_rails_generators - assert File.exist?(File.join(@path, 'generators', 'model_generator.rb')) + assert File.exist?(File.join(@path, "generators", "model_generator.rb")) assert_called_with(Rails::Generators::ModelGenerator, :start, [["Account"], {}]) do - warnings = capture(:stderr){ Rails::Generators.invoke :model, ["Account"] } + warnings = capture(:stderr) { Rails::Generators.invoke :model, ["Account"] } assert warnings.empty? end end @@ -108,14 +108,14 @@ class GeneratorsTest < Rails::Generators::TestCase def test_invoke_with_nested_namespaces model_generator = Minitest::Mock.new model_generator.expect(:start, nil, [["Account"], {}]) - assert_called_with(Rails::Generators, :find_by_namespace, ['namespace', 'my:awesome'], returns: model_generator) do - Rails::Generators.invoke 'my:awesome:namespace', ["Account"] + assert_called_with(Rails::Generators, :find_by_namespace, ["namespace", "my:awesome"], returns: model_generator) do + Rails::Generators.invoke "my:awesome:namespace", ["Account"] end model_generator.verify end def test_rails_generators_help_with_builtin_information - output = capture(:stdout){ Rails::Generators.help } + output = capture(:stdout) { Rails::Generators.help } assert_match(/Rails:/, output) assert_match(/^ model$/, output) assert_match(/^ scaffold_controller$/, output) @@ -123,19 +123,19 @@ class GeneratorsTest < Rails::Generators::TestCase end def test_rails_generators_help_does_not_include_app_nor_plugin_new - output = capture(:stdout){ Rails::Generators.help } + output = capture(:stdout) { Rails::Generators.help } assert_no_match(/app/, output) assert_no_match(/[^:]plugin/, output) end def test_rails_generators_with_others_information - output = capture(:stdout){ Rails::Generators.help } + output = capture(:stdout) { Rails::Generators.help } assert_match(/Fixjour:/, output) assert_match(/^ fixjour$/, output) end def test_rails_generators_does_not_show_active_record_hooks - output = capture(:stdout){ Rails::Generators.help } + output = capture(:stdout) { Rails::Generators.help } assert_match(/ActiveRecord:/, output) assert_match(/^ active_record:fixjour$/, output) end @@ -214,7 +214,7 @@ class GeneratorsTest < Rails::Generators::TestCase # Create template mkdir_p(File.dirname(template)) - File.open(template, 'w'){ |f| f.write "empty" } + File.open(template, "w") { |f| f.write "empty" } capture(:stdout) do Rails::Generators.invoke :model, ["user"], destination_root: destination_root @@ -229,18 +229,18 @@ class GeneratorsTest < Rails::Generators::TestCase def test_source_paths_for_not_namespaced_generators mspec = Rails::Generators.find_by_namespace :fixjour - assert mspec.source_paths.include?(File.join(Rails.root, "lib", "templates", "fixjour")) + assert_includes mspec.source_paths, File.join(Rails.root, "lib", "templates", "fixjour") end def test_usage_with_embedded_ruby require File.expand_path("fixtures/lib/generators/usage_template/usage_template_generator", File.dirname(__FILE__)) - output = capture(:stdout) { Rails::Generators.invoke :usage_template, ['--help'] } + output = capture(:stdout) { Rails::Generators.invoke :usage_template, ["--help"] } assert_match(/:: 2 ::/, output) end def test_hide_namespace - assert !Rails::Generators.hidden_namespaces.include?("special:namespace") + assert_not_includes Rails::Generators.hidden_namespaces, "special:namespace" Rails::Generators.hide_namespace("special:namespace") - assert Rails::Generators.hidden_namespaces.include?("special:namespace") + assert_includes Rails::Generators.hidden_namespaces, "special:namespace" end end diff --git a/railties/test/initializable_test.rb b/railties/test/initializable_test.rb index ed9573453b..4b67c91cc5 100644 --- a/railties/test/initializable_test.rb +++ b/railties/test/initializable_test.rb @@ -1,8 +1,7 @@ -require 'abstract_unit' -require 'rails/initializable' +require "abstract_unit" +require "rails/initializable" module InitializableTests - class Foo include Rails::Initializable attr_accessor :foo, :bar @@ -174,6 +173,11 @@ module InitializableTests end end end + + test "Initializer provides context's class name" do + foo = Foo.new + assert_equal foo.class, foo.initializers.first.context_class + end end class BeforeAfter < ActiveSupport::TestCase @@ -215,8 +219,8 @@ module InitializableTests class WithArgsTest < ActiveSupport::TestCase test "running initializers with args" do $with_arg = nil - WithArgs.new.run_initializers(:default, 'foo') - assert_equal 'foo', $with_arg + WithArgs.new.run_initializers(:default, "foo") + assert_equal "foo", $with_arg end end diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index 52e0277633..8c1fe43a10 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -1,31 +1,32 @@ # Note: # It is important to keep this file as light as possible # the goal for tests that require this is to test booting up -# rails from an empty state, so anything added here could +# Rails from an empty state, so anything added here could # hide potential failures # # It is also good to know what is the bare minimum to get # Rails booted up. -require 'fileutils' +require "fileutils" -require 'bundler/setup' unless defined?(Bundler) -require 'active_support' -require 'active_support/testing/autorun' -require 'active_support/testing/stream' -require 'active_support/test_case' +require "bundler/setup" unless defined?(Bundler) +require "active_support" +require "active_support/testing/autorun" +require "active_support/testing/stream" +require "active_support/test_case" RAILS_FRAMEWORK_ROOT = File.expand_path("#{File.dirname(__FILE__)}/../../..") # These files do not require any others and are needed # to run the tests +require "active_support/core_ext/object/blank" require "active_support/testing/isolation" require "active_support/core_ext/kernel/reporting" -require 'tmpdir' +require "tmpdir" module TestHelpers module Paths def app_template_path - File.join Dir.tmpdir, 'app_template' + File.join Dir.tmpdir, "app_template" end def tmp_path(*args) @@ -65,7 +66,7 @@ module TestHelpers def extract_body(response) "".tap do |body| - response[2].each {|chunk| body << chunk } + response[2].each { |chunk| body << chunk } end end @@ -77,8 +78,8 @@ module TestHelpers resp = Array(resp) assert_equal 200, resp[0] - assert_match 'text/html', resp[1]["Content-Type"] - assert_match 'charset=utf-8', resp[1]["Content-Type"] + assert_match "text/html", resp[1]["Content-Type"] + assert_match "charset=utf-8", resp[1]["Content-Type"] assert extract_body(resp).match(/Yay! You.*re on Rails!/) end @@ -102,28 +103,23 @@ module TestHelpers module Generation # Build an application by invoking the generator and going through the whole stack. def build_app(options = {}) - @prev_rails_env = ENV['RAILS_ENV'] - ENV['RAILS_ENV'] = "development" - ENV['SECRET_KEY_BASE'] ||= SecureRandom.hex(16) + @prev_rails_env = ENV["RAILS_ENV"] + ENV["RAILS_ENV"] = "development" + ENV["SECRET_KEY_BASE"] ||= SecureRandom.hex(16) FileUtils.rm_rf(app_path) FileUtils.cp_r(app_template_path, app_path) # Delete the initializers unless requested unless options[:initializers] - Dir["#{app_path}/config/initializers/*.rb"].each do |initializer| + Dir["#{app_path}/config/initializers/**/*.rb"].each do |initializer| File.delete(initializer) end end - gemfile_path = "#{app_path}/Gemfile" - if options[:gemfile].blank? && File.exist?(gemfile_path) - File.delete gemfile_path - end - routes = File.read("#{app_path}/config/routes.rb") if routes =~ /(\n\s*end\s*)\Z/ - File.open("#{app_path}/config/routes.rb", 'w') do |f| + File.open("#{app_path}/config/routes.rb", "w") do |f| f.puts $` + "\nActiveSupport::Deprecation.silence { match ':controller(/:action(/:id))(.:format)', via: :all }\n" + $1 end end @@ -157,7 +153,7 @@ module TestHelpers end def teardown_app - ENV['RAILS_ENV'] = @prev_rails_env if @prev_rails_env + ENV["RAILS_ENV"] = @prev_rails_env if @prev_rails_env end # Make a very basic app, without creating the whole directory structure. @@ -166,7 +162,7 @@ module TestHelpers require "rails" require "action_controller/railtie" require "action_view/railtie" - require 'action_dispatch/middleware/flash' + require "action_dispatch/middleware/flash" @app = Class.new(Rails::Application) @app.config.eager_load = false @@ -183,7 +179,7 @@ module TestHelpers get "/" => "omg#index" end - require 'rack/test' + require "rack/test" extend ::Rack::Test::Methods end @@ -196,7 +192,7 @@ module TestHelpers end RUBY - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get ':controller(/:action)' end @@ -213,7 +209,7 @@ module TestHelpers def write(file, string) path = "#{@path}/#{file}" FileUtils.mkdir_p(File.dirname(path)) - File.open(path, "w") {|f| f.puts string } + File.open(path, "w") { |f| f.puts string } end def delete(file) @@ -229,7 +225,7 @@ module TestHelpers app.insert(2, "$:.unshift(\"#{dir}/lib\")") app.insert(3, "require #{name.inspect}") - File.open("#{app_path}/config/application.rb", 'r+') do |f| + File.open("#{app_path}/config/application.rb", "r+") do |f| f.puts app end @@ -247,7 +243,7 @@ module TestHelpers 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| + File.open("#{app_path}/config/application.rb", "w") do |f| f.puts $` + $1 + "\n#{str}\n" + $' end end @@ -256,7 +252,7 @@ module TestHelpers def add_to_config(str) environment = File.read("#{app_path}/config/application.rb") if environment =~ /(\n\s*end\s*end\s*)\Z/ - File.open("#{app_path}/config/application.rb", 'w') do |f| + File.open("#{app_path}/config/application.rb", "w") do |f| f.puts $` + "\n#{str}\n" + $1 end end @@ -265,7 +261,7 @@ module TestHelpers def add_to_env_config(env, str) environment = File.read("#{app_path}/config/environments/#{env}.rb") if environment =~ /(\n\s*end\s*)\Z/ - File.open("#{app_path}/config/environments/#{env}.rb", 'w') do |f| + File.open("#{app_path}/config/environments/#{env}.rb", "w") do |f| f.puts $` + "\n#{str}\n" + $1 end end @@ -281,11 +277,11 @@ module TestHelpers def remove_from_file(file, str) contents = File.read(file) - contents.sub!(/#{str}/, '') + contents.sub!(/#{str}/, "") File.write(file, contents) end - def app_file(path, contents, mode = 'w') + def app_file(path, contents, mode = "w") FileUtils.mkdir_p File.dirname("#{app_path}/#{path}") File.open("#{app_path}/#{path}", mode) do |f| f.puts contents @@ -304,13 +300,10 @@ module TestHelpers to_remove = [:actionmailer, :activerecord] - arr if to_remove.include?(:activerecord) - remove_from_config 'config.active_record.*' + remove_from_config "config.active_record.*" end - $:.reject! {|path| path =~ %r'/(#{to_remove.join('|')})/' } - end - - def boot_rails + $:.reject! { |path| path =~ %r'/(#{to_remove.join('|')})/' } end end end @@ -333,7 +326,7 @@ Module.new do FileUtils.mkdir(app_template_path) `#{Gem.ruby} #{RAILS_FRAMEWORK_ROOT}/railties/exe/rails new #{app_template_path} --skip-gemfile --skip-listen --no-rc` - File.open("#{app_template_path}/config/boot.rb", 'w') do |f| + File.open("#{app_template_path}/config/boot.rb", "w") do |f| f.puts "require 'rails/all'" end end unless defined?(RAILS_ISOLATED_ENGINE) diff --git a/railties/test/json_params_parsing_test.rb b/railties/test/json_params_parsing_test.rb new file mode 100644 index 0000000000..7fff3bb465 --- /dev/null +++ b/railties/test/json_params_parsing_test.rb @@ -0,0 +1,49 @@ +require "abstract_unit" +require "action_dispatch" +require "active_record" + +class JsonParamsParsingTest < ActionDispatch::IntegrationTest + def test_prevent_null_query + # Make sure we have data to find + klass = Class.new(ActiveRecord::Base) do + def self.name; "Foo"; end + establish_connection adapter: "sqlite3", database: ":memory:" + connection.create_table "foos" do |t| + t.string :title + t.timestamps null: false + end + end + klass.create + assert klass.first + + app = ->(env) { + request = ActionDispatch::Request.new env + params = ActionController::Parameters.new request.parameters + if params[:t] + klass.find_by_title(params[:t]) + else + nil + end + } + + assert_nil app.call(make_env("t" => nil)) + assert_nil app.call(make_env("t" => [nil])) + + [[[nil]], [[[nil]]]].each do |data| + assert_nil app.call(make_env("t" => data)) + end + ensure + klass.connection.drop_table("foos") + end + + private + def make_env(json) + data = JSON.dump json + content_length = data.length + { + "CONTENT_LENGTH" => content_length, + "CONTENT_TYPE" => "application/json", + "rack.input" => StringIO.new(data) + } + end +end diff --git a/railties/test/path_generation_test.rb b/railties/test/path_generation_test.rb index a16adc72a6..579e50ac95 100644 --- a/railties/test/path_generation_test.rb +++ b/railties/test/path_generation_test.rb @@ -1,6 +1,6 @@ -require 'abstract_unit' -require 'active_support/core_ext/object/with_options' -require 'active_support/core_ext/object/json' +require "abstract_unit" +require "active_support/core_ext/object/with_options" +require "active_support/core_ext/object/json" class PathGenerationTest < ActiveSupport::TestCase attr_reader :app @@ -30,7 +30,7 @@ class PathGenerationTest < ActiveSupport::TestCase end def make_request(env) - Request.new super, self.url_helpers, @block + Request.new(super, url_helpers, @block) end end @@ -38,11 +38,11 @@ class PathGenerationTest < ActiveSupport::TestCase host = uri_or_host.host unless path path ||= uri_or_host.path - params = {'PATH_INFO' => path, - 'REQUEST_METHOD' => method, - 'HTTP_HOST' => host } + params = { "PATH_INFO" => path, + "REQUEST_METHOD" => method, + "HTTP_HOST" => host } - params['SCRIPT_NAME'] = script_name if script_name + params["SCRIPT_NAME"] = script_name if script_name status, headers, body = app.call(params) new_body = [] @@ -72,11 +72,11 @@ class PathGenerationTest < ActiveSupport::TestCase 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, "/FOO") + assert_equal "/FOO/blogs", app.instance.controller.blogs_path - send_request(url, 'GET', nil) - assert_equal '/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 diff --git a/railties/test/paths_test.rb b/railties/test/paths_test.rb index 96b54c7264..7b2551062a 100644 --- a/railties/test/paths_test.rb +++ b/railties/test/paths_test.rb @@ -1,6 +1,6 @@ -require 'abstract_unit' -require 'rails/paths' -require 'minitest/mock' +require "abstract_unit" +require "rails/paths" +require "minitest/mock" class PathsTest < ActiveSupport::TestCase def setup @@ -103,7 +103,7 @@ class PathsTest < ActiveSupport::TestCase @root.add "app", with: "/app" @root["app"].autoload_once! assert @root["app"].autoload_once? - assert @root.autoload_once.include?(@root["app"].expanded.first) + assert_includes @root.autoload_once, @root["app"].expanded.first end end @@ -114,14 +114,14 @@ class PathsTest < ActiveSupport::TestCase @root["app"].skip_autoload_once! assert !@root["app"].autoload_once? - assert !@root.autoload_once.include?(@root["app"].expanded.first) + assert_not_includes @root.autoload_once, @root["app"].expanded.first end test "it is possible to add a path without assignment and specify it should be loaded only once" do File.stub(:exist?, true) do @root.add "app", with: "/app", autoload_once: true assert @root["app"].autoload_once? - assert @root.autoload_once.include?("/app") + assert_includes @root.autoload_once, "/app" end end @@ -129,8 +129,8 @@ class PathsTest < ActiveSupport::TestCase File.stub(:exist?, true) do @root.add "app", with: ["/app", "/app2"], autoload_once: true assert @root["app"].autoload_once? - assert @root.autoload_once.include?("/app") - assert @root.autoload_once.include?("/app2") + assert_includes @root.autoload_once, "/app" + assert_includes @root.autoload_once, "/app2" end end @@ -139,7 +139,7 @@ class PathsTest < ActiveSupport::TestCase @root["app"] = "/app" @root["app"].autoload_once! @root["app"].autoload_once! - assert_equal 1, @root.autoload_once.select {|p| p == @root["app"].expanded.first }.size + assert_equal 1, @root.autoload_once.select { |p| p == @root["app"].expanded.first }.size end end @@ -157,7 +157,7 @@ class PathsTest < ActiveSupport::TestCase @root["app"] = "/app" @root["app"].eager_load! assert @root["app"].eager_load? - assert @root.eager_load.include?(@root["app"].to_a.first) + assert_includes @root.eager_load, @root["app"].to_a.first end end @@ -168,14 +168,14 @@ class PathsTest < ActiveSupport::TestCase @root["app"].skip_eager_load! assert !@root["app"].eager_load? - assert !@root.eager_load.include?(@root["app"].to_a.first) + assert_not_includes @root.eager_load, @root["app"].to_a.first end test "it is possible to add a path without assignment and mark it as eager" do File.stub(:exist?, true) do @root.add "app", with: "/app", eager_load: true assert @root["app"].eager_load? - assert @root.eager_load.include?("/app") + assert_includes @root.eager_load, "/app" end end @@ -183,8 +183,8 @@ class PathsTest < ActiveSupport::TestCase File.stub(:exist?, true) do @root.add "app", with: ["/app", "/app2"], eager_load: true assert @root["app"].eager_load? - assert @root.eager_load.include?("/app") - assert @root.eager_load.include?("/app2") + assert_includes @root.eager_load, "/app" + assert_includes @root.eager_load, "/app2" end end @@ -193,8 +193,8 @@ class PathsTest < ActiveSupport::TestCase @root.add "app", with: "/app", eager_load: true, autoload_once: true assert @root["app"].eager_load? assert @root["app"].autoload_once? - assert @root.eager_load.include?("/app") - assert @root.autoload_once.include?("/app") + assert_includes @root.eager_load, "/app" + assert_includes @root.autoload_once, "/app" end end @@ -203,7 +203,7 @@ class PathsTest < ActiveSupport::TestCase @root["app"] = "/app" @root["app"].eager_load! @root["app"].eager_load! - assert_equal 1, @root.eager_load.select {|p| p == @root["app"].expanded.first }.size + assert_equal 1, @root.eager_load.select { |p| p == @root["app"].expanded.first }.size end end diff --git a/railties/test/rack_logger_test.rb b/railties/test/rack_logger_test.rb index fcc79b57fb..7dd91a2465 100644 --- a/railties/test/rack_logger_test.rb +++ b/railties/test/rack_logger_test.rb @@ -1,8 +1,8 @@ -require 'abstract_unit' -require 'active_support/testing/autorun' -require 'active_support/test_case' -require 'rails/rack/logger' -require 'logger' +require "abstract_unit" +require "active_support/testing/autorun" +require "active_support/test_case" +require "rails/rack/logger" +require "logger" module Rails module Rack @@ -39,7 +39,7 @@ module Rails def setup @subscriber = Subscriber.new @notifier = ActiveSupport::Notifications.notifier - @subscription = notifier.subscribe 'request.action_dispatch', subscriber + @subscription = notifier.subscribe "request.action_dispatch", subscriber end def teardown @@ -47,11 +47,11 @@ module Rails end def test_notification - logger = TestLogger.new { } + logger = TestLogger.new {} - assert_difference('subscriber.starts.length') do - assert_difference('subscriber.finishes.length') do - logger.call('REQUEST_METHOD' => 'GET').last.close + assert_difference("subscriber.starts.length") do + assert_difference("subscriber.finishes.length") do + logger.call("REQUEST_METHOD" => "GET").last.close end end end @@ -62,10 +62,10 @@ module Rails raise NotImplementedError end - assert_difference('subscriber.starts.length') do - assert_difference('subscriber.finishes.length') do + assert_difference("subscriber.starts.length") do + assert_difference("subscriber.finishes.length") do assert_raises(NotImplementedError) do - logger.call 'REQUEST_METHOD' => 'GET' + logger.call "REQUEST_METHOD" => "GET" end end end diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb index c51503c2b7..d795629ccd 100644 --- a/railties/test/rails_info_controller_test.rb +++ b/railties/test/rails_info_controller_test.rb @@ -1,4 +1,4 @@ -require 'abstract_unit' +require "abstract_unit" module ActionController class Base @@ -11,8 +11,8 @@ class InfoControllerTest < ActionController::TestCase def setup Rails.application.routes.draw do - get '/rails/info/properties' => "rails/info#properties" - get '/rails/info/routes' => "rails/info#routes" + get "/rails/info/properties" => "rails/info#properties" + get "/rails/info/routes" => "rails/info#routes" end @routes = Rails.application.routes @@ -30,7 +30,7 @@ class InfoControllerTest < ActionController::TestCase test "info controller renders an error message when request was forbidden" do @request.env["REMOTE_ADDR"] = "example.org" get :properties - assert_select 'p' + assert_select "p" end test "info controller allows requests when all requests are considered local" do @@ -45,7 +45,7 @@ class InfoControllerTest < ActionController::TestCase test "info controller renders a table with properties" do get :properties - assert_select 'table' + assert_select "table" end test "info controller renders with routes" do @@ -54,28 +54,34 @@ class InfoControllerTest < ActionController::TestCase end test "info controller returns exact matches" do - exact_count = -> { JSON(response.body)['exact'].size } + exact_count = -> { JSON(response.body)["exact"].size } - get :routes, params: { path: 'rails/info/route' } - assert exact_count.call == 0, 'should not match incomplete routes' + get :routes, params: { path: "rails/info/route" } + assert exact_count.call == 0, "should not match incomplete routes" - get :routes, params: { path: 'rails/info/routes' } - assert exact_count.call == 1, 'should match complete routes' + get :routes, params: { path: "rails/info/routes" } + assert exact_count.call == 1, "should match complete routes" - get :routes, params: { path: 'rails/info/routes.html' } - assert exact_count.call == 1, 'should match complete routes with optional parts' + get :routes, params: { path: "rails/info/routes.html" } + assert exact_count.call == 1, "should match complete routes with optional parts" end test "info controller returns fuzzy matches" do - fuzzy_count = -> { JSON(response.body)['fuzzy'].size } + fuzzy_count = -> { JSON(response.body)["fuzzy"].size } - get :routes, params: { path: 'rails/info' } - assert fuzzy_count.call == 2, 'should match incomplete routes' + get :routes, params: { path: "rails/info" } + assert fuzzy_count.call == 2, "should match incomplete routes" - get :routes, params: { path: 'rails/info/routes' } - assert fuzzy_count.call == 1, 'should match complete routes' + get :routes, params: { path: "rails/info/routes" } + assert fuzzy_count.call == 1, "should match complete routes" - get :routes, params: { path: 'rails/info/routes.html' } - assert fuzzy_count.call == 0, 'should match optional parts of route literally' + get :routes, params: { path: "rails/info/routes.html" } + assert fuzzy_count.call == 0, "should match optional parts of route literally" + end + + test "internal routes do not have a default params[:internal] value" do + get :properties + assert_response :success + assert_nil @controller.params[:internal] end end diff --git a/railties/test/rails_info_test.rb b/railties/test/rails_info_test.rb index 92e4af25b5..59e79de41a 100644 --- a/railties/test/rails_info_test.rb +++ b/railties/test/rails_info_test.rb @@ -1,4 +1,4 @@ -require 'abstract_unit' +require "abstract_unit" unless defined?(Rails) && defined?(Rails::Info) module Rails @@ -11,46 +11,46 @@ require "active_support/core_ext/kernel/reporting" class InfoTest < ActiveSupport::TestCase def setup Rails.send :remove_const, :Info - silence_warnings { load 'rails/info.rb' } + silence_warnings { load "rails/info.rb" } end def test_property_with_block_swallows_exceptions_and_ignores_property assert_nothing_raised do Rails::Info.module_eval do - property('Bogus') {raise} + property("Bogus") { raise } end end - assert !property_defined?('Bogus') + assert !property_defined?("Bogus") end def test_property_with_string Rails::Info.module_eval do - property 'Hello', 'World' + property "Hello", "World" end - assert_property 'Hello', 'World' + assert_property "Hello", "World" end def test_property_with_block Rails::Info.module_eval do - property('Goodbye') {'World'} + property("Goodbye") { "World" } end - assert_property 'Goodbye', 'World' + assert_property "Goodbye", "World" end def test_rails_version - assert_property 'Rails version', - File.read(File.realpath('../../../RAILS_VERSION', __FILE__)).chomp + assert_property "Rails version", + File.read(File.realpath("../../../RAILS_VERSION", __FILE__)).chomp end def test_html_includes_middleware Rails::Info.module_eval do - property 'Middleware', ['Rack::Lock', 'Rack::Static'] + property "Middleware", ["Rack::Lock", "Rack::Static"] end html = Rails::Info.to_html - assert html.include?('<tr><td class="name">Middleware</td>') - properties.value_for('Middleware').each do |value| - assert html.include?("<li>#{CGI.escapeHTML(value)}</li>") + assert_includes html, '<tr><td class="name">Middleware</td>' + properties.value_for("Middleware").each do |value| + assert_includes html, "<li>#{CGI.escapeHTML(value)}</li>" end end diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb index 4a47ab32b4..0c8896a715 100644 --- a/railties/test/railties/engine_test.rb +++ b/railties/test/railties/engine_test.rb @@ -4,7 +4,6 @@ require "rack/test" module RailtiesTest class EngineTest < ActiveSupport::TestCase - include ActiveSupport::Testing::Isolation include Rack::Test::Methods @@ -28,7 +27,6 @@ module RailtiesTest end def boot_rails - super require "#{app_path}/config/environment" end @@ -37,8 +35,6 @@ module RailtiesTest add_to_env_config "development", "config.assets.digest = false" boot_rails - require 'rack/test' - extend Rack::Test::Methods get "/assets/engine.js" assert_match "alert()", last_response.body @@ -102,7 +98,7 @@ module RailtiesTest assert_no_match(/2_create_users/, output.join("\n")) - bukkits_migration_order = output.index(output.detect{|o| /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/ =~ o }) + bukkits_migration_order = output.index(output.detect { |o| /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/ =~ o }) assert_not_nil bukkits_migration_order, "Expected migration to be skipped" migrations_count = Dir["#{app_path}/db/migrate/*.rb"].length @@ -112,7 +108,7 @@ module RailtiesTest end end - test 'respects the order of railties when installing migrations' do + test "respects the order of railties when installing migrations" do @blog = engine "blog" do |plugin| plugin.write "lib/blog.rb", <<-RUBY module Blog @@ -213,11 +209,11 @@ module RailtiesTest test "no rake task without migrations" do boot_rails - require 'rake' - require 'rdoc/task' - require 'rake/testtask' + require "rake" + require "rdoc/task" + require "rake/testtask" Rails.application.load_tasks - assert !Rake::Task.task_defined?('bukkits:install:migrations') + assert !Rake::Task.task_defined?("bukkits:install:migrations") end test "puts its lib directory on load path" do @@ -322,8 +318,6 @@ module RailtiesTest RUBY boot_rails - require 'rack/test' - extend Rack::Test::Methods get "/sprokkit" assert_equal "I am a Sprokkit", last_response.body @@ -360,14 +354,12 @@ module RailtiesTest RUBY boot_rails - require 'rack/test' - extend Rack::Test::Methods - get '/foo' - assert_equal 'foo', last_response.body + get "/foo" + assert_equal "foo", last_response.body - get '/bar' - assert_equal 'bar', last_response.body + get "/bar" + assert_equal "bar", last_response.body end test "rake tasks lib tasks are loaded" do @@ -379,9 +371,9 @@ module RailtiesTest RUBY boot_rails - require 'rake' - require 'rdoc/task' - require 'rake/testtask' + require "rake" + require "rdoc/task" + require "rake/testtask" Rails.application.load_tasks Rake::Task[:foo].invoke assert $executed @@ -392,18 +384,18 @@ module RailtiesTest config.i18n.load_path << "#{app_path}/app/locales/en.yml" RUBY - app_file 'app/locales/en.yml', <<-YAML + app_file "app/locales/en.yml", <<-YAML en: bar: "1" YAML - app_file 'config/locales/en.yml', <<-YAML + app_file "config/locales/en.yml", <<-YAML en: foo: "2" bar: "2" YAML - @plugin.write 'config/locales/en.yml', <<-YAML + @plugin.write "config/locales/en.yml", <<-YAML en: foo: "3" YAML @@ -450,8 +442,6 @@ YAML RUBY boot_rails - require 'rack/test' - extend Rack::Test::Methods get "/admin/foo/bar" assert_equal 200, last_response.status @@ -481,7 +471,7 @@ YAML end RUBY - add_to_config "config.middleware.use \"Bukkits\"" + add_to_config "config.middleware.use Bukkits" boot_rails end @@ -637,11 +627,11 @@ YAML env = Rack::MockRequest.env_for("/") Bukkits::Engine.call(env) - assert_equal Bukkits::Engine.routes, env['action_dispatch.routes'] + assert_equal Bukkits::Engine.routes, env["action_dispatch.routes"] env = Rack::MockRequest.env_for("/") Rails.application.call(env) - assert_equal Rails.application.routes, env['action_dispatch.routes'] + assert_equal Rails.application.routes, env["action_dispatch.routes"] end test "isolated engine should include only its own routes and helpers" do @@ -1028,7 +1018,7 @@ YAML # check expanding paths engine_dir = @plugin.path.chomp("/").split("/").last - engine_path = File.join(@plugin.path, '..', engine_dir) + engine_path = File.join(@plugin.path, "..", engine_dir) assert_equal Bukkits::Engine.instance, Rails::Engine.find(engine_path) end @@ -1155,10 +1145,10 @@ YAML assert_equal "App's bar partial", last_response.body.strip get("/assets/foo.js") - assert_equal "// Bukkit's foo js", last_response.body.strip + assert_match "// Bukkit's foo js", last_response.body.strip get("/assets/bar.js") - assert_equal "// App's bar js", last_response.body.strip + assert_match "// App's bar js", last_response.body.strip # ensure that railties are not added twice railties = Rails.application.send(:ordered_railties).map(&:class) @@ -1236,7 +1226,6 @@ YAML end RUBY - app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do mount Bukkits::Engine => "/" @@ -1286,7 +1275,6 @@ YAML end RUBY - @plugin.write "app/controllers/bukkits/bukkit_controller.rb", <<-RUBY class Bukkits::BukkitController < ActionController::Base def index @@ -1297,11 +1285,11 @@ YAML boot_rails - get("/bukkits/bukkit", {}, {'SCRIPT_NAME' => '/foo'}) - assert_equal '/foo/bar', last_response.body + get("/bukkits/bukkit", {}, "SCRIPT_NAME" => "/foo") + assert_equal "/foo/bar", last_response.body - get("/bar", {}, {'SCRIPT_NAME' => '/foo'}) - assert_equal '/foo/bukkits/bukkit', last_response.body + get("/bar", {}, "SCRIPT_NAME" => "/foo") + assert_equal "/foo/bukkits/bukkit", last_response.body end test "paths are properly generated when application is mounted at sub-path and relative_url_root is set" do @@ -1346,11 +1334,11 @@ YAML boot_rails - get("/bukkits/bukkit", {}, {'SCRIPT_NAME' => '/foo'}) - assert_equal '/foo/bar', last_response.body + get("/bukkits/bukkit", {}, "SCRIPT_NAME" => "/foo") + assert_equal "/foo/bar", last_response.body - get("/bar", {}, {'SCRIPT_NAME' => '/foo'}) - assert_equal '/foo/bukkits/bukkit', last_response.body + get("/bar", {}, "SCRIPT_NAME" => "/foo") + assert_equal "/foo/bukkits/bukkit", last_response.body end private diff --git a/railties/test/railties/generators_test.rb b/railties/test/railties/generators_test.rb index b85e16c040..732898d0c0 100644 --- a/railties/test/railties/generators_test.rb +++ b/railties/test/railties/generators_test.rb @@ -1,7 +1,7 @@ RAILS_ISOLATED_ENGINE = true require "isolation/abstract_unit" -require 'generators/generators_test_helper' +require "generators/generators_test_helper" require "rails/generators/test_case" module RailtiesTests @@ -9,7 +9,7 @@ module RailtiesTests include ActiveSupport::Testing::Isolation def destination_root - tmp_path 'foo_bar' + tmp_path "foo_bar" end def tmp_path(*args) @@ -18,7 +18,7 @@ module RailtiesTests end def engine_path - tmp_path('foo_bar') + tmp_path("foo_bar") end def bundled_rails(cmd) @@ -39,7 +39,7 @@ module RailtiesTests Dir.chdir(engine_path) do File.open("Gemfile", "w") do |f| - f.write <<-GEMFILE.gsub(/^ {12}/, '') + f.write <<-GEMFILE.gsub(/^ {12}/, "") source "https://rubygems.org" gem 'rails', path: '#{RAILS_FRAMEWORK_ROOT}' diff --git a/railties/test/railties/mounted_engine_test.rb b/railties/test/railties/mounted_engine_test.rb index fb2071c7c3..9db42c0c38 100644 --- a/railties/test/railties/mounted_engine_test.rb +++ b/railties/test/railties/mounted_engine_test.rb @@ -1,10 +1,10 @@ -require 'isolation/abstract_unit' +require "isolation/abstract_unit" module ApplicationTests class ApplicationRoutingTest < ActiveSupport::TestCase - require 'rack/test' - include Rack::Test::Methods - include ActiveSupport::Testing::Isolation + require "rack/test" + include Rack::Test::Methods + include ActiveSupport::Testing::Isolation def setup build_app @@ -15,7 +15,7 @@ module ApplicationTests @plugin = engine "blog" @metrics_plugin = engine "metrics" - app_file 'config/routes.rb', <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do mount Weblog::Engine, :at => '/', :as => 'weblog' resources :posts @@ -34,7 +34,6 @@ module ApplicationTests end RUBY - @simple_plugin.write "lib/weblog.rb", <<-RUBY module Weblog class Engine < ::Rails::Engine @@ -179,8 +178,6 @@ module ApplicationTests end end RUBY - - boot_rails end def teardown @@ -200,7 +197,7 @@ module ApplicationTests assert_equal "/john/blog/posts/1", last_response.body # test generating engine's route from engine with default_url_options - get "/john/blog/posts", {}, 'SCRIPT_NAME' => "/foo" + get "/john/blog/posts", {}, "SCRIPT_NAME" => "/foo" assert_equal "/foo/john/blog/posts/1", last_response.body # test generating engine's route from application @@ -214,10 +211,10 @@ module ApplicationTests assert_equal "/john/blog/posts", last_response.body # test generating engine's route from application with default_url_options - get "/engine_route", {}, 'SCRIPT_NAME' => "/foo" + get "/engine_route", {}, "SCRIPT_NAME" => "/foo" assert_equal "/foo/anonymous/blog/posts", last_response.body - get "/url_for_engine_route", {}, 'SCRIPT_NAME' => "/foo" + get "/url_for_engine_route", {}, "SCRIPT_NAME" => "/foo" assert_equal "/foo/john/blog/posts", last_response.body # test generating application's route from engine @@ -229,21 +226,20 @@ module ApplicationTests # test generating engine's route from other engine get "/metrics/generate_blog_route" - assert_equal '/anonymous/blog/posts/1', last_response.body + assert_equal "/anonymous/blog/posts/1", last_response.body get "/metrics/generate_blog_route_in_view" - assert_equal '/anonymous/blog/posts/1', last_response.body + assert_equal "/anonymous/blog/posts/1", last_response.body # test generating engine's route from other engine with default_url_options - get "/metrics/generate_blog_route", {}, 'SCRIPT_NAME' => '/foo' - assert_equal '/foo/anonymous/blog/posts/1', last_response.body - - get "/metrics/generate_blog_route_in_view", {}, 'SCRIPT_NAME' => '/foo' - assert_equal '/foo/anonymous/blog/posts/1', last_response.body + get "/metrics/generate_blog_route", {}, "SCRIPT_NAME" => "/foo" + assert_equal "/foo/anonymous/blog/posts/1", last_response.body + get "/metrics/generate_blog_route_in_view", {}, "SCRIPT_NAME" => "/foo" + assert_equal "/foo/anonymous/blog/posts/1", last_response.body # test generating application's route from engine with default_url_options - get "/someone/blog/generate_application_route", {}, 'SCRIPT_NAME' => '/foo' + get "/someone/blog/generate_application_route", {}, "SCRIPT_NAME" => "/foo" assert_equal "/foo/", last_response.body # test polymorphic routes diff --git a/railties/test/railties/railtie_test.rb b/railties/test/railties/railtie_test.rb index 5042d628cf..30cd525266 100644 --- a/railties/test/railties/railtie_test.rb +++ b/railties/test/railties/railtie_test.rb @@ -6,7 +6,6 @@ module RailtiesTest def setup build_app - boot_rails FileUtils.rm_rf("#{app_path}/config/environments") require "rails/all" end @@ -80,6 +79,13 @@ module RailtiesTest assert_equal app_path, $before_configuration end + test "before_configuration callbacks run as soon as the application constant inherits from Rails::Application" do + $before_configuration = false + class Foo < Rails::Railtie ; config.before_configuration { $before_configuration = true } ; end + class Application < Rails::Application ; end + assert $before_configuration + end + test "railtie can add after_initialize callbacks" do $after_initialize = false class Foo < Rails::Railtie ; config.after_initialize { $after_initialize = true } ; end @@ -100,9 +106,9 @@ module RailtiesTest require "#{app_path}/config/environment" assert !$ran_block - require 'rake' - require 'rake/testtask' - require 'rdoc/task' + require "rake" + require "rake/testtask" + require "rdoc/task" Rails.application.load_tasks assert $ran_block @@ -124,12 +130,12 @@ module RailtiesTest require "#{app_path}/config/environment" assert_equal [], $ran_block - require 'rake' - require 'rake/testtask' - require 'rdoc/task' + require "rake" + require "rake/testtask" + require "rdoc/task" Rails.application.load_tasks - assert $ran_block.include?("my_tie") + assert_includes $ran_block, "my_tie" end test "generators block is executed when MyApp.load_generators is called" do @@ -197,8 +203,8 @@ module RailtiesTest test "we can change our environment if we want to" do begin original_env = Rails.env - Rails.env = 'foo' - assert_equal('foo', Rails.env) + Rails.env = "foo" + assert_equal("foo", Rails.env) ensure Rails.env = original_env assert_equal(original_env, Rails.env) diff --git a/railties/test/test_unit/reporter_test.rb b/railties/test/test_unit/reporter_test.rb index 0d64b48550..e22c939981 100644 --- a/railties/test/test_unit/reporter_test.rb +++ b/railties/test/test_unit/reporter_test.rb @@ -1,6 +1,6 @@ -require 'abstract_unit' -require 'rails/test_unit/reporter' -require 'minitest/mock' +require "abstract_unit" +require "rails/test_unit/reporter" +require "minitest/mock" class TestUnitReporterTest < ActiveSupport::TestCase class ExampleTest < Minitest::Test @@ -33,7 +33,7 @@ class TestUnitReporterTest < ActiveSupport::TestCase @reporter.record(passing_test) @reporter.record(skipped_test) @reporter.report - assert_no_match 'Failed tests:', @output.string + assert_no_match "Failed tests:", @output.string assert_rerun_snippet_count 0 end @@ -87,7 +87,7 @@ class TestUnitReporterTest < ActiveSupport::TestCase @reporter.record(failed_test) @reporter.report - assert_no_match 'Failed tests:', @output.string + assert_no_match "Failed tests:", @output.string end test "fail fast interrupts run on failure" do @@ -100,7 +100,7 @@ class TestUnitReporterTest < ActiveSupport::TestCase rescue Interrupt interrupt_raised = true ensure - assert interrupt_raised, 'Expected Interrupt to be raised.' + assert interrupt_raised, "Expected Interrupt to be raised." end end @@ -114,7 +114,7 @@ class TestUnitReporterTest < ActiveSupport::TestCase rescue Interrupt interrupt_raised = true ensure - assert interrupt_raised, 'Expected Interrupt to be raised.' + assert interrupt_raised, "Expected Interrupt to be raised." end end @@ -122,7 +122,7 @@ class TestUnitReporterTest < ActiveSupport::TestCase fail_fast = Rails::TestUnitReporter.new @output, fail_fast: true fail_fast.record(skipped_test) - assert_no_match 'Failed tests:', @output.string + assert_no_match "Failed tests:", @output.string end test "outputs colored passing results" do @@ -156,38 +156,38 @@ class TestUnitReporterTest < ActiveSupport::TestCase end private - def assert_rerun_snippet_count(snippet_count) - assert_equal snippet_count, @output.string.scan(%r{^bin/rails test }).size - end + def assert_rerun_snippet_count(snippet_count) + assert_equal snippet_count, @output.string.scan(%r{^bin/rails test }).size + end - def failed_test - ft = ExampleTest.new(:woot) - ft.failures << begin - raise Minitest::Assertion, "boo" - rescue Minitest::Assertion => e - e - end - ft - end + def failed_test + ft = ExampleTest.new(:woot) + ft.failures << begin + raise Minitest::Assertion, "boo" + rescue Minitest::Assertion => e + e + end + ft + end - def errored_test - et = ExampleTest.new(:woot) - et.failures << Minitest::UnexpectedError.new(ArgumentError.new("wups")) - et - end + def errored_test + et = ExampleTest.new(:woot) + et.failures << Minitest::UnexpectedError.new(ArgumentError.new("wups")) + et + end - def passing_test - ExampleTest.new(:woot) - end + def passing_test + ExampleTest.new(:woot) + end - def skipped_test - st = ExampleTest.new(:woot) - st.failures << begin - raise Minitest::Skip, "skipchurches, misstemples" - rescue Minitest::Assertion => e - e - end - st.time = 10 - st - end + def skipped_test + st = ExampleTest.new(:woot) + st.failures << begin + raise Minitest::Skip, "skipchurches, misstemples" + rescue Minitest::Assertion => e + e + end + st.time = 10 + st + end end diff --git a/railties/test/version_test.rb b/railties/test/version_test.rb index f270d8f0c9..86a482e091 100644 --- a/railties/test/version_test.rb +++ b/railties/test/version_test.rb @@ -1,4 +1,4 @@ -require 'abstract_unit' +require "abstract_unit" class VersionTest < ActiveSupport::TestCase def test_rails_version_returns_a_string |