aboutsummaryrefslogtreecommitdiffstats
path: root/railties/test
diff options
context:
space:
mode:
Diffstat (limited to 'railties/test')
-rw-r--r--railties/test/abstract_unit.rb26
-rw-r--r--railties/test/app_loader_test.rb16
-rw-r--r--railties/test/application/asset_debugging_test.rb127
-rw-r--r--railties/test/application/assets_test.rb200
-rw-r--r--railties/test/application/bin_setup_test.rb19
-rw-r--r--railties/test/application/configuration/custom_test.rb14
-rw-r--r--railties/test/application/configuration_test.rb695
-rw-r--r--railties/test/application/console_test.rb26
-rw-r--r--railties/test/application/generators_test.rb38
-rw-r--r--railties/test/application/initializers/frameworks_test.rb43
-rw-r--r--railties/test/application/initializers/hooks_test.rb7
-rw-r--r--railties/test/application/initializers/i18n_test.rb108
-rw-r--r--railties/test/application/initializers/load_path_test.rb5
-rw-r--r--railties/test/application/initializers/notifications_test.rb9
-rw-r--r--railties/test/application/integration_test_case_test.rb73
-rw-r--r--railties/test/application/loading_test.rb77
-rw-r--r--railties/test/application/mailer_previews_test.rb161
-rw-r--r--railties/test/application/middleware/cache_test.rb21
-rw-r--r--railties/test/application/middleware/cookies_test.rb21
-rw-r--r--railties/test/application/middleware/exceptions_test.rb27
-rw-r--r--railties/test/application/middleware/remote_ip_test.rb18
-rw-r--r--railties/test/application/middleware/sendfile_test.rb9
-rw-r--r--railties/test/application/middleware/session_test.rb202
-rw-r--r--railties/test/application/middleware/static_test.rb43
-rw-r--r--railties/test/application/middleware_test.rb125
-rw-r--r--railties/test/application/multiple_applications_test.rb11
-rw-r--r--railties/test/application/paths_test.rb7
-rw-r--r--railties/test/application/per_request_digest_cache_test.rb66
-rw-r--r--railties/test/application/rack/logger_test.rb4
-rw-r--r--railties/test/application/rackup_test.rb5
-rw-r--r--railties/test/application/rake/dbs_test.rb147
-rw-r--r--railties/test/application/rake/dev_test.rb43
-rw-r--r--railties/test/application/rake/framework_test.rb11
-rw-r--r--railties/test/application/rake/log_test.rb33
-rw-r--r--railties/test/application/rake/migrations_test.rb157
-rw-r--r--railties/test/application/rake/notes_test.rb70
-rw-r--r--railties/test/application/rake/restart_test.rb24
-rw-r--r--railties/test/application/rake_test.rb217
-rw-r--r--railties/test/application/rendering_test.rb15
-rw-r--r--railties/test/application/routing_test.rb241
-rw-r--r--railties/test/application/runner_test.rb34
-rw-r--r--railties/test/application/test_runner_test.rb378
-rw-r--r--railties/test/application/test_test.rb119
-rw-r--r--railties/test/application/url_generation_test.rb10
-rw-r--r--railties/test/backtrace_cleaner_test.rb30
-rw-r--r--railties/test/code_statistics_calculator_test.rb58
-rw-r--r--railties/test/code_statistics_test.rb24
-rw-r--r--railties/test/commands/console_test.rb103
-rw-r--r--railties/test/commands/dbconsole_test.rb222
-rw-r--r--railties/test/commands/server_test.rb124
-rw-r--r--railties/test/configuration/middleware_stack_proxy_test.rb22
-rw-r--r--railties/test/engine/commands_tasks_test.rb24
-rw-r--r--railties/test/engine_test.rb2
-rw-r--r--railties/test/env_helpers.rb38
-rw-r--r--railties/test/fixtures/about_yml_plugins/bad_about_yml/init.rb2
-rw-r--r--railties/test/fixtures/about_yml_plugins/plugin_without_about_yml/init.rb2
-rw-r--r--railties/test/fixtures/lib/generators/active_record/fixjour_generator.rb2
-rw-r--r--railties/test/fixtures/lib/generators/model_generator.rb2
-rw-r--r--railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb2
-rw-r--r--railties/test/generators/actions_test.rb249
-rw-r--r--railties/test/generators/api_app_generator_test.rb115
-rw-r--r--railties/test/generators/app_generator_test.rb507
-rw-r--r--railties/test/generators/argv_scrubber_test.rb64
-rw-r--r--railties/test/generators/assets_generator_test.rb4
-rw-r--r--railties/test/generators/channel_generator_test.rb77
-rw-r--r--railties/test/generators/controller_generator_test.rb8
-rw-r--r--railties/test/generators/create_migration_test.rb16
-rw-r--r--railties/test/generators/generated_attribute_test.rb34
-rw-r--r--railties/test/generators/generator_generator_test.rb12
-rw-r--r--railties/test/generators/generator_test.rb53
-rw-r--r--railties/test/generators/generators_test_helper.rb23
-rw-r--r--railties/test/generators/helper_generator_test.rb6
-rw-r--r--railties/test/generators/integration_test_generator_test.rb4
-rw-r--r--railties/test/generators/job_generator_test.rb11
-rw-r--r--railties/test/generators/mailer_generator_test.rb23
-rw-r--r--railties/test/generators/migration_generator_test.rb33
-rw-r--r--railties/test/generators/model_generator_test.rb104
-rw-r--r--railties/test/generators/named_base_test.rb147
-rw-r--r--railties/test/generators/namespaced_generators_test.rb59
-rw-r--r--railties/test/generators/plugin_generator_test.rb306
-rw-r--r--railties/test/generators/plugin_test_helper.rb24
-rw-r--r--railties/test/generators/plugin_test_runner_test.rb103
-rw-r--r--railties/test/generators/resource_generator_test.rb10
-rw-r--r--railties/test/generators/scaffold_controller_generator_test.rb28
-rw-r--r--railties/test/generators/scaffold_generator_test.rb88
-rw-r--r--railties/test/generators/shared_generator_tests.rb76
-rw-r--r--railties/test/generators/task_generator_test.rb8
-rw-r--r--railties/test/generators/test_runner_in_engine_test.rb32
-rw-r--r--railties/test/generators_test.rb64
-rw-r--r--railties/test/initializable_test.rb14
-rw-r--r--railties/test/isolation/abstract_unit.rb121
-rw-r--r--railties/test/json_params_parsing_test.rb49
-rw-r--r--railties/test/path_generation_test.rb40
-rw-r--r--railties/test/paths_test.rb47
-rw-r--r--railties/test/rack_logger_test.rb26
-rw-r--r--railties/test/rails_info_controller_test.rb44
-rw-r--r--railties/test/rails_info_test.rb30
-rw-r--r--railties/test/railties/engine_test.rb157
-rw-r--r--railties/test/railties/generators_test.rb16
-rw-r--r--railties/test/railties/mounted_engine_test.rb54
-rw-r--r--railties/test/railties/railtie_test.rb26
-rw-r--r--railties/test/test_unit/reporter_test.rb159
-rw-r--r--railties/test/version_test.rb2
103 files changed, 4918 insertions, 2514 deletions
diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb
index 794d180e5d..fd1e1b9662 100644
--- a/railties/test/abstract_unit.rb
+++ b/railties/test/abstract_unit.rb
@@ -1,30 +1,28 @@
ENV["RAILS_ENV"] ||= "test"
-require File.expand_path("../../../load_paths", __FILE__)
+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..85f5502b4d 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
@@ -17,7 +17,7 @@ class AppLoaderTest < ActiveSupport::TestCase
end
end
- def write(filename, contents=nil)
+ def write(filename, contents = nil)
FileUtils.mkdir_p(File.dirname(filename))
File.write(filename, contents)
end
@@ -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 36ab8109a7..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
@@ -7,7 +7,10 @@ module ApplicationTests
include Rack::Test::Methods
def setup
- build_app(initializers: true)
+ # FIXME: shush Sass warning spam, not relevant to testing Railties
+ Kernel.silence_warnings do
+ build_app(initializers: true)
+ end
app_file "app/assets/javascripts/application.js", "//= require_tree ."
app_file "app/assets/javascripts/xmlhr.js", "function f1() { alert(); }"
@@ -25,25 +28,30 @@ module ApplicationTests
RUBY
ENV["RAILS_ENV"] = "production"
-
- boot_rails
end
def teardown
teardown_app
end
+ # FIXME: shush Sass warning spam, not relevant to testing Railties
+ def get(*)
+ Kernel.silence_warnings { super }
+ end
+
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/rake assets:precompile --trace 2>&1` }
+ output = Dir.chdir(app_path) { `bin/rails assets:precompile --trace 2>&1` }
assert $?.success?, output
- require "#{app_path}/config/environment"
+
+ # Load app env
+ app "production"
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
@@ -51,14 +59,111 @@ module ApplicationTests
test "assets aren't concatenated when compile is true is on and debug_assets params is true" do
add_to_env_config "production", "config.assets.compile = true"
- ENV["RAILS_ENV"] = "production"
- require "#{app_path}/config/environment"
+ # Load app env
+ app "production"
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 6952472ff5..f38cacd6da 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
@@ -17,22 +16,32 @@ module ApplicationTests
end
def precompile!(env = nil)
- quietly do
- precompile_task = "bin/rake assets:precompile #{env} --trace 2>&1"
- output = Dir.chdir(app_path) { %x[ #{precompile_task} ] }
- assert $?.success?, output
- output
+ with_env env.to_h do
+ quietly do
+ precompile_task = "bin/rails assets:precompile --trace 2>&1"
+ output = Dir.chdir(app_path) { %x[ #{precompile_task} ] }
+ assert $?.success?, output
+ output
+ end
end
end
+ def with_env(env)
+ env.each { |k, v| ENV[k.to_s] = v }
+ yield
+ ensure
+ env.each_key { |k| ENV.delete k.to_s }
+ end
+
def clean_assets!
quietly do
- assert Dir.chdir(app_path) { system('bin/rake assets:clobber') }
+ assert Dir.chdir(app_path) { system("bin/rails assets:clobber") }
end
end
def assert_file_exists(filename)
- assert Dir[filename].first, "missing #{filename}"
+ globbed = Dir[filename]
+ assert globbed.one?, "Found #{globbed.size} files matching #{filename}. All files in the directory: #{Dir.entries(File.dirname(filename)).inspect}"
end
def assert_no_file_exists(filename)
@@ -43,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
@@ -51,7 +60,10 @@ module ApplicationTests
add_to_env_config "development", "config.assets.digest = false"
- require "#{app_path}/config/environment"
+ # FIXME: shush Sass warning spam, not relevant to testing Railties
+ Kernel.silence_warnings do
+ require "#{app_path}/config/environment"
+ end
get "/assets/demo.js"
assert_equal 'a = "/assets/rails.png";', last_response.body.strip
@@ -60,9 +72,10 @@ module ApplicationTests
test "assets do not require compressors until it is used" do
app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();"
add_to_env_config "production", "config.assets.compile = true"
+ add_to_env_config "production", "config.assets.precompile = []"
- ENV["RAILS_ENV"] = "production"
- require "#{app_path}/config/environment"
+ # Load app env
+ app "production"
assert !defined?(Uglifier)
get "/assets/demo.js"
@@ -71,10 +84,10 @@ module ApplicationTests
end
test "precompile creates the file, gives it the original asset's content and run in production as default" do
+ app_file "app/assets/config/manifest.js", "//= link_tree ../javascripts"
app_file "app/assets/javascripts/application.js", "alert();"
app_file "app/assets/javascripts/foo/application.js", "alert();"
- ENV["RAILS_ENV"] = nil
precompile!
files = Dir["#{app_path}/public/assets/application-*.js"]
@@ -86,6 +99,7 @@ module ApplicationTests
end
def test_precompile_does_not_hit_the_database
+ app_file "app/assets/config/manifest.js", "//= link_tree ../javascripts"
app_file "app/assets/javascripts/application.js", "alert();"
app_file "app/assets/javascripts/foo/application.js", "alert();"
app_file "app/controllers/users_controller.rb", <<-eoruby
@@ -95,10 +109,9 @@ module ApplicationTests
class User < ActiveRecord::Base; raise 'should not be reached'; end
eoruby
- ENV['RAILS_ENV'] = 'production'
- ENV['DATABASE_URL'] = 'postgresql://baduser:badpass@127.0.0.1/dbname'
-
- precompile!
+ precompile! \
+ 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
@@ -106,9 +119,6 @@ module ApplicationTests
assert_not_nil file, "Expected application.js asset to be generated, but none found"
assert_equal "alert();".strip, File.read(file).strip
end
- ensure
- ENV.delete 'RAILS_ENV'
- ENV.delete 'DATABASE_URL'
end
test "precompile application.js and application.css and all other non JS/CSS files" do
@@ -163,40 +173,64 @@ module ApplicationTests
precompile!
+ 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();"
+
+ precompile! RAILS_ENV: "production"
+
assert_file_exists("#{app_path}/public/assets/something-*.js")
end
- test 'precompile use assets defined in app env config' do
- add_to_env_config 'production', 'config.assets.precompile = [ "something.js" ]'
+ 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", "body { background: '<%= asset_path('rails.png') %>'; }"
+ add_to_env_config "production", 'config.assets.prefix = "production_assets"'
- app_file 'app/assets/javascripts/something.js.erb', 'alert();'
+ precompile!
- precompile! 'RAILS_ENV=production'
+ assert_file_exists("#{app_path}/public/assets/application-*.css")
- assert_file_exists("#{app_path}/public/assets/something-*.js")
+ file = Dir["#{app_path}/public/assets/application-*.css"].first
+ assert_match(/assets\/rails-([0-z]+)\.png/, File.read(file))
+
+ precompile! RAILS_ENV: "production"
+
+ assert_file_exists("#{app_path}/public/production_assets/application-*.css")
+
+ file = Dir["#{app_path}/public/production_assets/application-*.css"].first
+ 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
- add_to_config 'config.assets.precompile = [ "something.js" ]'
- add_to_env_config 'production', 'config.assets.precompile += [ "another.js" ]'
+ 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" ]'
+
+ 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")
+ assert_file_exists("#{app_path}/public/assets/another_manifest-*.js")
assert_file_exists("#{app_path}/public/assets/another-*.js")
end
- test "asset pipeline should use a Sprockets::Index when config.assets.digest is true" do
+ test "asset pipeline should use a Sprockets::CachedEnvironment when config.assets.digest is true" do
add_to_config "config.action_controller.perform_caching = false"
add_to_env_config "production", "config.assets.compile = true"
- ENV["RAILS_ENV"] = "production"
- require "#{app_path}/config/environment"
+ # Load app env
+ app "production"
- assert_equal Sprockets::Index, Rails.application.assets.class
+ assert_equal Sprockets::CachedEnvironment, Rails.application.assets.class
end
test "precompile creates a manifest file with all the assets listed" do
@@ -205,8 +239,8 @@ module ApplicationTests
app_file "app/assets/javascripts/application.js", "alert();"
precompile!
- manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first
+ manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first
assets = ActiveSupport::JSON.decode(File.read(manifest))
assert_match(/application-([0-z]+)\.js/, assets["assets"]["application.js"])
assert_match(/application-([0-z]+)\.css/, assets["assets"]["application.css"])
@@ -225,16 +259,16 @@ module ApplicationTests
test "assets do not require any assets group gem when manifest file is present" do
app_file "app/assets/javascripts/application.js", "alert();"
- add_to_env_config "production", "config.serve_static_files = true"
+ add_to_env_config "production", "config.public_file_server.enabled = true"
- ENV["RAILS_ENV"] = "production"
- precompile!
+ precompile! RAILS_ENV: "production"
manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first
assets = ActiveSupport::JSON.decode(File.read(manifest))
asset_path = assets["assets"]["application.js"]
- require "#{app_path}/config/environment"
+ # Load app env
+ app "production"
# Checking if Uglifier is defined we can know if Sprockets was reached or not
assert !defined?(Uglifier)
@@ -243,12 +277,11 @@ module ApplicationTests
assert !defined?(Uglifier)
end
- test "precompile properly refers files referenced with asset_path and runs in the provided RAILS_ENV" do
+ test "precompile properly refers files referenced with asset_path" 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 "test", "config.assets.digest = true"
+ app_file "app/assets/stylesheets/application.css.erb", "p { background-image: url(<%= asset_path('rails.png') %>) }"
- precompile!('RAILS_ENV=test')
+ precompile!
file = Dir["#{app_path}/public/assets/application-*.css"].first
assert_match(/\/assets\/rails-([0-z]+)\.png/, File.read(file))
@@ -257,10 +290,9 @@ module ApplicationTests
test "precompile shouldn't use the digests present in manifest.json" do
app_file "app/assets/images/rails.png", "notactuallyapng"
- app_file "app/assets/stylesheets/application.css.erb", "p { url: <%= asset_path('rails.png') %> }"
+ app_file "app/assets/stylesheets/application.css.erb", "p { background-image: url(<%= asset_path('rails.png') %>) }"
- ENV["RAILS_ENV"] = "production"
- precompile!
+ precompile! RAILS_ENV: "production"
manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first
assets = ActiveSupport::JSON.decode(File.read(manifest))
@@ -269,17 +301,16 @@ module ApplicationTests
app_file "app/assets/images/rails.png", "p { url: change }"
precompile!
- assets = ActiveSupport::JSON.decode(File.read(manifest))
+ assets = ActiveSupport::JSON.decode(File.read(manifest))
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", "<%= asset_path('rails.png') %>"
+ app_file "app/assets/stylesheets/application.css.erb", "p { background-image: url(<%= asset_path('rails.png') %>) }"
- ENV["RAILS_ENV"] = "production"
- precompile!
+ precompile! RAILS_ENV: "production"
file = Dir["#{app_path}/public/assets/application-*.css"].first
assert_match(/\/assets\/rails-([0-z]+)\.png/, File.read(file))
@@ -288,7 +319,8 @@ module ApplicationTests
test "precompile should handle utf8 filenames" do
filename = "レイルズ.png"
app_file "app/assets/images/#{filename}", "not an image really"
- add_to_config "config.assets.precompile = [ /\.png$/, /application.(css|js)$/ ]"
+ app_file "app/assets/config/manifest.js", "//= link_tree ../images"
+ add_to_config "config.assets.precompile = %w(manifest.js)"
precompile!
@@ -296,7 +328,8 @@ module ApplicationTests
assets = ActiveSupport::JSON.decode(File.read(manifest))
assert asset_path = assets["assets"].find { |(k, _)| k && k =~ /.png/ }[1]
- require "#{app_path}/config/environment"
+ # Load app env
+ app "development"
get "/assets/#{URI.parser.escape(asset_path)}"
assert_match "not an image really", last_response.body
@@ -310,8 +343,7 @@ module ApplicationTests
clean_assets!
- files = Dir["#{app_path}/public/assets/**/*", "#{app_path}/tmp/cache/assets/development/*",
- "#{app_path}/tmp/cache/assets/test/*", "#{app_path}/tmp/cache/assets/production/*"]
+ files = Dir["#{app_path}/public/assets/**/*"]
assert_equal 0, files.length, "Expected no assets, but found #{files.join(', ')}"
end
@@ -319,8 +351,8 @@ module ApplicationTests
app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();"
add_to_config "config.assets.compile = false"
- ENV["RAILS_ENV"] = "production"
- require "#{app_path}/config/environment"
+ # Load app env
+ app "production"
get "/assets/demo.js"
assert_equal 404, last_response.status
@@ -337,21 +369,22 @@ module ApplicationTests
add_to_env_config "development", "config.assets.digest = false"
- require "#{app_path}/config/environment"
+ # Load app env
+ app "development"
class ::OmgController < ActionController::Base
def index
flash[:cool_story] = true
- render text: "ok"
+ render plain: "ok"
end
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
- assert_equal nil, last_response.headers["Set-Cookie"]
+ assert_nil last_response.headers["Set-Cookie"]
end
test "files in any assets/ directories are not added to Sprockets" do
@@ -363,7 +396,8 @@ module ApplicationTests
add_to_env_config "development", "config.assets.digest = false"
- require "#{app_path}/config/environment"
+ # Load app env
+ app "development"
get "/assets/demo.js"
assert_match "alert();", last_response.body
@@ -374,15 +408,15 @@ module ApplicationTests
app_with_assets_in_view
# config.assets.debug and config.assets.compile are false for production environment
- ENV["RAILS_ENV"] = "production"
- precompile!
+ precompile! RAILS_ENV: "production"
- require "#{app_path}/config/environment"
+ # Load app env
+ app "production"
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
@@ -393,7 +427,8 @@ module ApplicationTests
app_file "app/assets/javascripts/xmlhr.js.erb", "<%= Post.name %>"
precompile!
- assert_equal "Post;\n", File.read(Dir["#{app_path}/public/assets/application-*.js"].first)
+
+ assert_match(/Post;/, File.read(Dir["#{app_path}/public/assets/application-*.js"].first))
end
test "initialization on the assets group should set assets_dir" do
@@ -434,12 +469,15 @@ module ApplicationTests
app_with_assets_in_view
add_to_config "config.asset_host = 'example.com'"
add_to_env_config "development", "config.assets.digest = false"
- require "#{app_path}/config/environment"
+
+ # Load app env
+ app "development"
+
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
@@ -449,6 +487,7 @@ module ApplicationTests
add_to_config "config.assets.precompile = %w{rails.png image_loader.js}"
add_to_config "config.asset_host = 'example.com'"
add_to_env_config "development", "config.assets.digest = false"
+
precompile!
assert_match "src='//example.com/assets/rails.png'", File.read(Dir["#{app_path}/public/assets/image_loader-*.js"].first)
@@ -460,6 +499,7 @@ module ApplicationTests
app_file "app/assets/javascripts/app.js.erb", "var src='<%= image_path('rails.png') %>';"
add_to_config "config.assets.precompile = %w{rails.png app.js}"
add_to_env_config "development", "config.assets.digest = false"
+
precompile!
assert_match "src='/sub/uri/assets/rails.png'", File.read(Dir["#{app_path}/public/assets/app-*.js"].first)
@@ -467,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 1bdced02e9..f62313f3e1 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
@@ -14,35 +14,38 @@ module ApplicationTests
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
RUBY
list_tables = lambda { `bin/rails runner 'p ActiveRecord::Base.connection.tables'`.strip }
- File.write("log/my.log", "zomg!")
+ File.write("log/test.log", "zomg!")
- assert_equal '[]', list_tables.call
- assert_equal 5, File.size("log/my.log")
+ assert_equal "[]", list_tables.call
+ assert_equal 5, File.size("log/test.log")
assert_not File.exist?("tmp/restart.txt")
`bin/setup 2>&1`
- assert_equal 0, File.size("log/my.log")
- assert_equal '["articles", "schema_migrations"]', list_tables.call
+ assert_equal 0, File.size("log/test.log")
+ assert_equal '["articles", "schema_migrations", "ar_internal_metadata"]', list_tables.call
assert File.exist?("tmp/restart.txt")
end
end
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)
== Installing dependencies ==
+Resolving dependencies...
The Gemfile's dependencies are satisfied
== Preparing database ==
+Created database 'db/development.sqlite3'
+Created database 'db/test.sqlite3'
== Removing old logs and tempfiles ==
diff --git a/railties/test/application/configuration/custom_test.rb b/railties/test/application/configuration/custom_test.rb
index 28b3b2f2d6..3c675eec71 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
@@ -29,10 +28,17 @@ module ApplicationTests
assert_equal 3, x.payment_processing.retries
assert_equal true, x.super_debugger
assert_equal false, x.hyper_debugger
- assert_equal nil, x.nil_debugger
+ assert_nil x.nil_debugger
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 f677a7c42a..31c3b5cf52 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,13 +34,23 @@ module ApplicationTests
FileUtils.cp_r(app_path, new_app)
end
- def app
- @app ||= Rails.application
+ def app(env = "development")
+ @app ||= begin
+ ENV["RAILS_ENV"] = env
+
+ # FIXME: shush Sass warning spam, not relevant to testing Railties
+ Kernel.silence_warnings do
+ require "#{app_path}/config/environment"
+ end
+
+ Rails.application
+ ensure
+ ENV.delete "RAILS_ENV"
+ end
end
def setup
build_app
- boot_rails
supress_default_config
end
@@ -64,12 +74,30 @@ 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
+
+ test "By default logs tags are not set in development" do
+ restore_default_config
+
+ with_rails_env "development" do
+ app "development"
+ assert Rails.application.config.log_tags.blank?
+ end
+ end
+
+ test "By default logs are tagged with :request_id in production" do
+ restore_default_config
+
+ with_rails_env "production" do
+ 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
@@ -78,8 +106,10 @@ module ApplicationTests
require 'my_logger'
config.logger = MyLogger.new STDOUT
RUBY
- require "#{app_path}/config/environment"
- assert_equal 'MyLogger', Rails.application.config.logger.class.name
+
+ app "development"
+
+ assert_equal "MyLogger", Rails.application.config.logger.class.name
end
test "a renders exception on pending migration" do
@@ -89,15 +119,15 @@ module ApplicationTests
config.action_dispatch.show_exceptions = true
RUBY
- app_file 'db/migrate/20140708012246_create_user.rb', <<-RUBY
- class CreateUser < ActiveRecord::Migration
+ app_file "db/migrate/20140708012246_create_user.rb", <<-RUBY
+ class CreateUser < ActiveRecord::Migration::Current
def change
create_table :users
end
end
RUBY
- require "#{app_path}/config/environment"
+ app "development"
ActiveRecord::Migrator.migrations_paths = ["#{app_path}/db/migrate"]
@@ -126,31 +156,31 @@ module ApplicationTests
end
test "Rails.application is nil until app is initialized" do
- require 'rails'
+ require "rails"
assert_nil Rails.application
- require "#{app_path}/config/environment"
+ app "development"
assert_equal AppTemplate::Application.instance, Rails.application
end
test "Rails.application responds to all instance methods" do
- require "#{app_path}/config/environment"
+ 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
- require "#{app_path}/config/environment"
+ 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
- require "#{app_path}/config/environment"
+ app "development"
assert_equal Pathname.new(app_path), Rails.application.root
end
test "the application root can be seen from the application singleton" do
- require "#{app_path}/config/environment"
+ app "development"
assert_equal Pathname.new(app_path), AppTemplate::Application.root
end
@@ -162,7 +192,8 @@ module ApplicationTests
use_frameworks []
- require "#{app_path}/config/environment"
+ app "development"
+
assert_equal Pathname.new(new_app), Rails.application.root
end
@@ -172,7 +203,7 @@ module ApplicationTests
use_frameworks []
Dir.chdir("#{app_path}") do
- require "#{app_path}/config/environment"
+ app "development"
assert_equal Pathname.new("#{app_path}"), Rails.application.root
end
end
@@ -181,7 +212,9 @@ module ApplicationTests
add_to_config <<-RUBY
config.root = "#{app_path}"
RUBY
- require "#{app_path}/config/environment"
+
+ app "development"
+
assert_instance_of Pathname, Rails.root
end
@@ -189,7 +222,9 @@ module ApplicationTests
add_to_config <<-RUBY
config.paths["public"] = "somewhere"
RUBY
- require "#{app_path}/config/environment"
+
+ app "development"
+
assert_instance_of Pathname, Rails.public_path
end
@@ -199,16 +234,19 @@ module ApplicationTests
config.cache_classes = true
RUBY
- require "#{app_path}/config/application"
- assert Rails.application.initialize!
+ app "development"
+
+ assert_equal :require, ActiveSupport::Dependencies.mechanism
end
test "application is always added to eager_load namespaces" do
- require "#{app_path}/config/application"
+ app "development"
assert_includes Rails.application.config.eager_load_namespaces, AppTemplate::Application
end
test "the application can be eager loaded even when there are no frameworks" do
+ FileUtils.rm_rf("#{app_path}/app/models/application_record.rb")
+ FileUtils.rm_rf("#{app_path}/app/mailers/application_mailer.rb")
FileUtils.rm_rf("#{app_path}/config/environments")
add_to_config <<-RUBY
config.eager_load = true
@@ -218,7 +256,7 @@ module ApplicationTests
use_frameworks []
assert_nothing_raised do
- require "#{app_path}/config/application"
+ app "development"
end
end
@@ -230,18 +268,18 @@ module ApplicationTests
RUBY
assert_nothing_raised do
- require "#{app_path}/config/application"
+ 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
- require "#{app_path}/config/environment"
+ 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
@@ -255,7 +293,7 @@ module ApplicationTests
assert !$prepared
- require "#{app_path}/config/environment"
+ app "development"
get "/"
assert $prepared
@@ -267,7 +305,7 @@ module ApplicationTests
end
test "skipping config.encoding still results in 'utf-8' as the default" do
- require "#{app_path}/config/application"
+ app "development"
assert_utf8
end
@@ -276,7 +314,7 @@ module ApplicationTests
config.encoding = "utf-8"
RUBY
- require "#{app_path}/config/application"
+ app "development"
assert_utf8
end
@@ -285,133 +323,179 @@ module ApplicationTests
config.paths["public"] = "somewhere"
RUBY
- require "#{app_path}/config/application"
+ app "development"
assert_equal Pathname.new(app_path).join("somewhere"), Rails.public_path
end
- test "In production mode, config.serve_static_files is off by default" do
+ test "In production mode, config.public_file_server.enabled is off by default" do
restore_default_config
with_rails_env "production" do
- require "#{app_path}/config/environment"
- assert_not app.config.serve_static_files
+ app "production"
+ assert_not app.config.public_file_server.enabled
end
end
- test "In production mode, config.serve_static_files is enabled when RAILS_SERVE_STATIC_FILES is set" do
+ test "In production mode, config.public_file_server.enabled is enabled when RAILS_SERVE_STATIC_FILES is set" do
restore_default_config
with_rails_env "production" do
switch_env "RAILS_SERVE_STATIC_FILES", "1" do
- require "#{app_path}/config/environment"
- assert app.config.serve_static_files
+ app "production"
+ assert app.config.public_file_server.enabled
end
end
end
- test "In production mode, config.serve_static_files is disabled when RAILS_SERVE_STATIC_FILES is blank" do
+ test "In production mode, STDOUT logging is enabled when RAILS_LOG_TO_STDOUT is set" do
+ restore_default_config
+
+ with_rails_env "production" do
+ switch_env "RAILS_LOG_TO_STDOUT", "1" do
+ app "production"
+ assert ActiveSupport::Logger.logger_outputs_to?(app.config.logger, STDOUT)
+ end
+ end
+ end
+
+ test "In production mode, config.public_file_server.enabled is disabled when RAILS_SERVE_STATIC_FILES is blank" do
restore_default_config
with_rails_env "production" do
switch_env "RAILS_SERVE_STATIC_FILES", " " do
- require "#{app_path}/config/environment"
- assert_not app.config.serve_static_files
+ app "production"
+ assert_not app.config.public_file_server.enabled
end
end
end
+ test "config.serve_static_files is deprecated" do
+ make_basic_app do |application|
+ assert_deprecated do
+ application.config.serve_static_files = true
+ end
+
+ assert application.config.public_file_server.enabled
+ end
+ end
+
+ test "config.static_cache_control is deprecated" do
+ make_basic_app do |application|
+ assert_deprecated do
+ application.config.static_cache_control = "public, max-age=60"
+ end
+
+ assert_equal application.config.static_cache_control, "public, max-age=60"
+ end
+ end
+
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
class ::OmgController < ActionController::Base
def index
cookies.signed[:some_key] = "some_value"
- render text: cookies[:some_key]
+ render plain: cookies[:some_key]
end
end
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
- require "#{app_path}/config/environment"
+ 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
- require "#{app_path}/config/environment"
+
+ app "development"
assert_deprecated(/You didn't set `secret_key_base`./) do
app.env_config
end
end
+ test "raise when secrets.secret_key_base is not a type of string" do
+ app_file "config/secrets.yml", <<-YAML
+ development:
+ secret_key_base: 123
+ YAML
+
+ app "development"
+
+ assert_raise(ArgumentError) do
+ app.key_generator
+ end
+ 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
- require "#{app_path}/config/environment"
- assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token
+ app "development"
+
+ 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
@@ -421,106 +505,151 @@ 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
- require "#{app_path}/config/environment"
- 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
- require "#{app_path}/config/environment"
- 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
- require "#{app_path}/config/environment"
- assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.secrets.secret_token
- assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token
+ app "development"
+
+ 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
- require "#{app_path}/config/environment"
- assert_equal 'myamazonaccesskeyid', app.secrets.aws_access_key_id
- assert_equal 'myamazonsecretaccesskey', app.secrets.aws_secret_access_key
+ 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 "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
- require "#{app_path}/config/environment"
+
+ 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
- require "#{app_path}/config/environment"
+
+ 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
- require "#{app_path}/config/environment"
- assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token
- assert_equal nil, app.secrets.secret_key_base
+ app "development"
+
+ assert_equal "b3c631c314c0bbca50c1b2843150fe33", app.config.secret_token
+ assert_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
- require "#{app_path}/config/environment"
- assert_equal '', app.config.secret_token
- assert_equal nil, app.secrets.secret_key_base
+ app "development"
+
+ assert_equal "", app.config.secret_token
+ assert_nil app.secrets.secret_key_base
assert_raise ArgumentError, /\AA secret is required/ do
app.key_generator
end
end
+ test "that nested keys are symbolized the same as parents for hashes more than one level deep" do
+ app_file "config/secrets.yml", <<-YAML
+ development:
+ smtp_settings:
+ address: "smtp.example.com"
+ user_name: "postmaster@example.com"
+ password: "697361616320736c6f616e2028656c6f7265737429"
+ YAML
+
+ app "development"
+
+ assert_equal "697361616320736c6f616e2028656c6f7265737429", app.secrets.smtp_settings[:password]
+ end
+
test "protect from forgery is the default in a new app" do
make_basic_app
@@ -535,8 +664,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)
@@ -545,15 +673,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 %>"
@@ -567,14 +694,14 @@ module ApplicationTests
end
RUBY
- require "#{app_path}/config/environment"
+ 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
@@ -584,19 +711,19 @@ 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 %>"
end
def update
- render text: "update"
+ render plain: "update"
end
private
- def form_authenticity_token; token; end # stub the authenticy token
+ def form_authenticity_token(*args); token; end # stub the authenticity token
end
RUBY
@@ -606,9 +733,9 @@ module ApplicationTests
end
RUBY
- require "#{app_path}/config/environment"
+ app "development"
- params = {authenticity_token: token}
+ params = { authenticity_token: token }
get "/posts/1"
assert_match(/patch/, last_response.body)
@@ -628,7 +755,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
@@ -659,12 +786,12 @@ module ApplicationTests
config.action_mailer.interceptors = MyMailInterceptor
RUBY
- require "#{app_path}/config/environment"
- require "mail"
+ 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
@@ -672,12 +799,12 @@ module ApplicationTests
config.action_mailer.interceptors = [MyMailInterceptor, "MyOtherMailInterceptor"]
RUBY
- require "#{app_path}/config/environment"
- require "mail"
+ 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
@@ -685,9 +812,9 @@ module ApplicationTests
config.action_mailer.preview_interceptors = MyPreviewMailInterceptor
RUBY
- require "#{app_path}/config/environment"
- require "mail"
+ app "development"
+ require "mail"
_ = ActionMailer::Base
assert_equal [ActionMailer::InlinePreviewInterceptor, ::MyPreviewMailInterceptor], ActionMailer::Base.preview_interceptors
@@ -698,22 +825,22 @@ module ApplicationTests
config.action_mailer.preview_interceptors = [MyPreviewMailInterceptor, "MyOtherPreviewMailInterceptor"]
RUBY
- require "#{app_path}/config/environment"
- require "mail"
+ app "development"
+ require "mail"
_ = ActionMailer::Base
assert_equal [ActionMailer::InlinePreviewInterceptor, MyPreviewMailInterceptor, MyOtherPreviewMailInterceptor], ActionMailer::Base.preview_interceptors
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
- require "#{app_path}/config/environment"
- require "mail"
+ app "development"
+ require "mail"
_ = ActionMailer::Base
assert_equal [], ActionMailer::Base.preview_interceptors
@@ -724,12 +851,12 @@ module ApplicationTests
config.action_mailer.observers = MyMailObserver
RUBY
- require "#{app_path}/config/environment"
- require "mail"
+ 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
@@ -737,12 +864,12 @@ module ApplicationTests
config.action_mailer.observers = [MyMailObserver, "MyOtherMailObserver"]
RUBY
- require "#{app_path}/config/environment"
- require "mail"
+ 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
@@ -750,12 +877,12 @@ module ApplicationTests
config.action_mailer.deliver_later_queue_name = 'test_default'
RUBY
- require "#{app_path}/config/environment"
- require "mail"
+ 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
@@ -764,7 +891,7 @@ module ApplicationTests
config.time_zone = "Wellington"
RUBY
- require "#{app_path}/config/environment"
+ app "development"
assert_equal "Wellington", Rails.application.config.time_zone
end
@@ -776,7 +903,7 @@ module ApplicationTests
RUBY
assert_raise(ArgumentError) do
- require "#{app_path}/config/environment"
+ app "development"
end
end
@@ -786,7 +913,7 @@ module ApplicationTests
config.beginning_of_week = :wednesday
RUBY
- require "#{app_path}/config/environment"
+ app "development"
assert_equal :wednesday, Rails.application.config.beginning_of_week
end
@@ -798,22 +925,24 @@ module ApplicationTests
RUBY
assert_raise(ArgumentError) do
- require "#{app_path}/config/environment"
+ app "development"
end
end
test "config.action_view.cache_template_loading with cache_classes default" do
add_to_config "config.cache_classes = true"
- require "#{app_path}/config/environment"
- require 'action_view/base'
+
+ app "development"
+ require "action_view/base"
assert_equal true, ActionView::Resolver.caching?
end
test "config.action_view.cache_template_loading without cache_classes default" do
add_to_config "config.cache_classes = false"
- require "#{app_path}/config/environment"
- require 'action_view/base'
+
+ app "development"
+ require "action_view/base"
assert_equal false, ActionView::Resolver.caching?
end
@@ -823,8 +952,9 @@ module ApplicationTests
config.cache_classes = true
config.action_view.cache_template_loading = false
RUBY
- require "#{app_path}/config/environment"
- require 'action_view/base'
+
+ app "development"
+ require "action_view/base"
assert_equal false, ActionView::Resolver.caching?
end
@@ -834,8 +964,9 @@ module ApplicationTests
config.cache_classes = false
config.action_view.cache_template_loading = true
RUBY
- require "#{app_path}/config/environment"
- require 'action_view/base'
+
+ app "development"
+ require "action_view/base"
assert_equal true, ActionView::Resolver.caching?
end
@@ -845,11 +976,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"
- require "#{app_path}/config/environment"
+ app "development"
assert_equal false, ActionView::Resolver.caching?
end
@@ -861,20 +992,20 @@ module ApplicationTests
class ::OmgController < ActionController::Base
def index
- render text: env["action_dispatch.show_exceptions"]
+ render plain: env["action_dispatch.show_exceptions"]
end
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)
@@ -882,16 +1013,16 @@ 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
+ render plain: params[:post].inspect
end
end
RUBY
@@ -902,17 +1033,17 @@ module ApplicationTests
end
RUBY
- require "#{app_path}/config/environment"
+ app "development"
post "/posts.json", '{ "title": "foo", "name": "bar" }', "CONTENT_TYPE" => "application/json"
- assert_equal '{"title"=>"foo"}', last_response.body
+ 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"
+ render plain: params[:post].permitted? ? "permitted" : "forbidden"
end
end
RUBY
@@ -924,17 +1055,17 @@ module ApplicationTests
config.action_controller.permit_all_parameters = true
RUBY
- require "#{app_path}/config/environment"
+ 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)
+ render plain: params.require(:post).permit(:name)
end
end
RUBY
@@ -946,16 +1077,16 @@ module ApplicationTests
config.action_controller.action_on_unpermitted_parameters = :raise
RUBY
- require "#{app_path}/config/environment"
+ 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
- require "#{app_path}/config/environment"
+ app "development"
assert_equal %w(controller action), ActionController::Parameters.always_permitted_parameters
end
@@ -963,15 +1094,17 @@ module ApplicationTests
add_to_config <<-RUBY
config.action_controller.always_permitted_parameters = %w( controller action format )
RUBY
- require "#{app_path}/config/environment"
+
+ 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])
+ render plain: params.permit(post: [:title])
end
end
RUBY
@@ -984,34 +1117,28 @@ module ApplicationTests
config.action_controller.action_on_unpermitted_parameters = :raise
RUBY
- require "#{app_path}/config/environment"
+ 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
- ENV["RAILS_ENV"] = "development"
-
- require "#{app_path}/config/environment"
+ 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
- ENV["RAILS_ENV"] = "test"
-
- require "#{app_path}/config/environment"
+ 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
- ENV["RAILS_ENV"] = "production"
-
- require "#{app_path}/config/environment"
+ app "production"
assert_equal false, ActionController::Parameters.action_on_unpermitted_parameters
end
@@ -1024,28 +1151,28 @@ module ApplicationTests
class ::OmgController < ActionController::Base
def index
respond_to do |format|
- format.html { render text: "HTML" }
- format.xml { render text: "XML" }
+ format.html { render plain: "HTML" }
+ format.xml { render plain: "XML" }
end
end
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
@@ -1072,6 +1199,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_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)
@@ -1089,17 +1232,14 @@ module ApplicationTests
test "config.active_record.dump_schema_after_migration is false on production" do
build_app
- ENV["RAILS_ENV"] = "production"
- require "#{app_path}/config/environment"
+ 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
- ENV["RAILS_ENV"] = "development"
-
- require "#{app_path}/config/environment"
+ app "development"
assert ActiveRecord::Base.dump_schema_after_migration
end
@@ -1125,12 +1265,12 @@ module ApplicationTests
end
RUBY
- require "#{app_path}/config/environment"
+ 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
@@ -1147,7 +1287,7 @@ module ApplicationTests
end
RUBY
- require "#{app_path}/config/environment"
+ app "development"
assert_not Rails.configuration.ran_block
Rails.application.load_generators
@@ -1165,7 +1305,7 @@ module ApplicationTests
end
RUBY
- require "#{app_path}/config/environment"
+ app "development"
assert_not Rails.configuration.ran_block
Rails.application.load_console
@@ -1183,7 +1323,7 @@ module ApplicationTests
end
RUBY
- require "#{app_path}/config/environment"
+ app "development"
assert_not Rails.configuration.ran_block
Rails.application.load_runner
@@ -1191,7 +1331,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'
@@ -1199,46 +1339,44 @@ module ApplicationTests
end
RUBY
- require "#{app_path}/config/environment"
+ 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")
- require "#{app_path}/config/environment"
+ 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
- Rails.env = "development"
- require "#{app_path}/config/environment"
+ 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
- Rails.env = "production"
- require "#{app_path}/config/environment"
+ 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
- Rails.env = "production"
+ 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
- require "#{app_path}/config/environment"
+
+ 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
@@ -1247,9 +1385,24 @@ module ApplicationTests
config.my_custom_config = config_for('custom')
RUBY
- require "#{app_path}/config/environment"
+ 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
+ development:
+ key: 'custom key'
+ RUBY
+
+ add_to_config <<-RUBY
+ config.my_custom_config = config_for(Pathname.new(Rails.root.join("config/custom.yml")))
+ RUBY
+
+ app "development"
+
+ 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
@@ -1258,14 +1411,14 @@ module ApplicationTests
RUBY
exception = assert_raises(RuntimeError) do
- require "#{app_path}/config/environment"
+ 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
@@ -1273,25 +1426,27 @@ module ApplicationTests
add_to_config <<-RUBY
config.my_custom_config = config_for('custom')
RUBY
- require "#{app_path}/config/environment"
+
+ 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
- require "#{app_path}/config/environment"
+
+ 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
@@ -1299,13 +1454,14 @@ module ApplicationTests
add_to_config <<-RUBY
config.my_custom_config = config_for('custom')
RUBY
- require "#{app_path}/config/environment"
- assert_equal 'custom key', Rails.application.config.my_custom_config['key']
+ app "development"
+
+ assert_equal "custom key", Rails.application.config.my_custom_config["key"]
end
- test "config_for with syntax error show a more descritive exception" do
- app_file 'config/custom.yml', <<-RUBY
+ test "config_for with syntax error show a more descriptive exception" do
+ app_file "config/custom.yml", <<-RUBY
development:
key: foo:
RUBY
@@ -1315,10 +1471,85 @@ module ApplicationTests
RUBY
exception = assert_raises(RuntimeError) do
- require "#{app_path}/config/environment"
+ 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
+ test:
+ key: 'walrus'
+ production:
+ key: 'unicorn'
+ RUBY
+
+ add_to_config <<-RUBY
+ config.my_custom_config = config_for('custom', env: 'production')
+ RUBY
+ require "#{app_path}/config/environment"
+
+ assert_equal "unicorn", Rails.application.config.my_custom_config["key"]
+ end
+
+ test "api_only is false by default" do
+ app "development"
+ refute Rails.application.config.api_only
+ end
+
+ test "api_only generator config is set when api_only is set" do
+ add_to_config <<-RUBY
+ config.api_only = true
+ RUBY
+ app "development"
+
+ Rails.application.load_generators
+ assert Rails.configuration.api_only
+ end
+
+ test "debug_exception_response_format is :api by default if api_only is enabled" do
+ add_to_config <<-RUBY
+ config.api_only = true
+ RUBY
+ app "development"
+
+ assert_equal :api, Rails.configuration.debug_exception_response_format
+ end
+
+ test "debug_exception_response_format can be overridden" do
+ add_to_config <<-RUBY
+ config.api_only = true
+ RUBY
+
+ app_file "config/environments/development.rb", <<-RUBY
+ Rails.application.configure do
+ config.debug_exception_response_format = :default
+ end
+ RUBY
+
+ app "development"
+
+ assert_equal :default, Rails.configuration.debug_exception_response_format
+ end
+
+ test "controller force_ssl declaration can be used even if session_store is disabled" do
+ make_basic_app do |application|
+ application.config.session_store :disabled
+ end
+
+ class ::OmgController < ActionController::Base
+ force_ssl
+
+ def index
+ render plain: "Yay! You're on Rails!"
+ end
+ end
+
+ get "/"
+
+ assert_equal 301, last_response.status
+ assert_equal "https://example.org/", last_response.location
end
end
end
diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb
index 7bf123d12b..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
@@ -52,12 +51,11 @@ class ConsoleTest < ActiveSupport::TestCase
a = b = c = nil
# TODO: These should be defined on the initializer
- ActionDispatch::Reloader.to_cleanup { a = b = c = 1 }
- ActionDispatch::Reloader.to_cleanup { b = c = 2 }
- ActionDispatch::Reloader.to_prepare { c = 3 }
+ ActiveSupport::Reloader.to_complete { a = b = c = 1 }
+ ActiveSupport::Reloader.to_complete { b = c = 2 }
+ ActiveSupport::Reloader.to_prepare { c = 3 }
- # Hide Reloading... output
- silence_stream(STDOUT) { irb_context.reload! }
+ irb_context.reload!(false)
assert_equal 1, a
assert_equal 2, b
@@ -81,7 +79,7 @@ class ConsoleTest < ActiveSupport::TestCase
MODEL
assert !User.new.respond_to?(:age)
- silence_stream(STDOUT) { irb_context.reload! }
+ irb_context.reload!(false)
assert User.new.respond_to?(:age)
end
@@ -90,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
@@ -105,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
@@ -128,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 84cc6e120b..d2ce14f594 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]
@@ -160,5 +159,30 @@ module ApplicationTests
assert Rails::Generators.options[:rails][:helper]
assert_equal :my_template, Rails::Generators.options[:rails][:template_engine]
end
+
+ test "api only generator generate mailer views" do
+ add_to_config <<-RUBY
+ config.api_only = true
+ RUBY
+
+ 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
+
+ test "ARGV is mutated as expected" do
+ require "#{app_path}/config/environment"
+ Rails::Command.const_set("APP_PATH", "rails/all")
+
+ FileUtils.cd(rails_root) do
+ ARGV = ["mailer", "notifier", "foo"]
+ Rails::Command.const_set("ARGV", ARGV)
+ quietly { Rails::Command.invoke :generate, ARGV }
+
+ assert_equal ["notifier", "foo"], ARGV
+ end
+
+ Rails::Command.send(:remove_const, "APP_PATH")
+ end
end
end
diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb
index 7bba910b9e..90927159dd 100644
--- a/railties/test/application/initializers/frameworks_test.rb
+++ b/railties/test/application/initializers/frameworks_test.rb
@@ -1,5 +1,4 @@
require "isolation/abstract_unit"
-require 'set'
module ApplicationTests
class FrameworksTest < ActiveSupport::TestCase
@@ -7,7 +6,6 @@ module ApplicationTests
def setup
build_app
- boot_rails
FileUtils.rm_rf "#{app_path}/config/environments"
end
@@ -17,7 +15,7 @@ module ApplicationTests
# AC & AM
test "set load paths set only if action controller or action mailer are in use" do
- assert_nothing_raised NameError do
+ assert_nothing_raised do
add_to_config <<-RUBY
config.root = "#{app_path}"
RUBY
@@ -50,6 +48,17 @@ module ApplicationTests
assert_equal "test.rails", ActionMailer::Base.default_url_options[:host]
end
+ test "Default to HTTPS for ActionMailer URLs when force_ssl is on" do
+ app_file "config/environments/development.rb", <<-RUBY
+ Rails.application.configure do
+ config.force_ssl = true
+ end
+ RUBY
+
+ require "#{app_path}/config/environment"
+ assert_equal "https", ActionMailer::Base.default_url_options[:protocol]
+ end
+
test "includes url helpers as action methods" do
app_file "config/routes.rb", <<-RUBY
Rails.application.routes.draw do
@@ -119,7 +128,7 @@ module ApplicationTests
end
RUBY
- require 'rack/test'
+ require "rack/test"
extend Rack::Test::Methods
get "/foo/included_helpers"
@@ -151,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
@@ -166,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
@@ -176,7 +185,7 @@ module ApplicationTests
test "if there's no config.active_support.bare, all of ActiveSupport is required" do
use_frameworks []
require "#{app_path}/config/environment"
- assert_nothing_raised { [1,2,3].sample }
+ assert_nothing_raised { [1, 2, 3].sample }
end
test "config.active_support.bare does not require all of ActiveSupport" do
@@ -194,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
@@ -206,29 +215,27 @@ module ApplicationTests
test "use schema cache dump" do
Dir.chdir(app_path) do
`rails generate model post title:string;
- bin/rake db:migrate db:schema:cache:dump`
+ bin/rails db:migrate db:schema:cache:dump`
end
require "#{app_path}/config/environment"
ActiveRecord::Base.connection.drop_table("posts") # force drop posts table for test.
- assert ActiveRecord::Base.connection.schema_cache.tables("posts")
+ assert ActiveRecord::Base.connection.schema_cache.data_sources("posts")
end
test "expire schema cache dump" do
Dir.chdir(app_path) do
`rails generate model post title:string;
- bin/rake db:migrate db:schema:cache:dump db:rollback`
+ bin/rails db:migrate db:schema:cache:dump db:rollback`
end
- silence_warnings {
- require "#{app_path}/config/environment"
- assert !ActiveRecord::Base.connection.schema_cache.tables("posts")
- }
+ require "#{app_path}/config/environment"
+ assert !ActiveRecord::Base.connection.schema_cache.data_sources("posts")
end
test "active record establish_connection uses Rails.env if DATABASE_URL is not set" do
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])
@@ -243,7 +250,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..36926c50ff 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
@@ -32,7 +31,7 @@ module ApplicationTests
RUBY
require "#{app_path}/config/environment"
- assert_equal [1,2,3], $initialization_callbacks
+ assert_equal [1, 2, 3], $initialization_callbacks
end
test "hooks block works correctly with eager_load" do
@@ -47,7 +46,7 @@ module ApplicationTests
RUBY
require "#{app_path}/config/environment"
- assert_equal [1,2,3,4], $initialization_callbacks
+ assert_equal [1, 2, 3, 4], $initialization_callbacks
end
test "after_initialize runs after frameworks have been initialized" do
@@ -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 9ee54796a4..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
@@ -132,6 +131,79 @@ en:
assert_equal "2", last_response.body
end
+ test "new locale files are loaded" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ RUBY
+
+ app_file "config/locales/en.yml", <<-YAML
+en:
+ foo: "1"
+ YAML
+
+ 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"
+ extend Rack::Test::Methods
+ load_app
+
+ get "/i18n"
+ assert_equal "1", last_response.body
+
+ # Wait a full second so we have time for changes to propagate
+ sleep(1)
+
+ remove_file "config/locales/en.yml"
+ app_file "config/locales/custom.en.yml", <<-YAML
+en:
+ foo: "2"
+ YAML
+
+ get "/i18n"
+ assert_equal "2", last_response.body
+ end
+
+ test "I18n.load_path is reloaded" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ RUBY
+
+ app_file "config/locales/en.yml", <<-YAML
+en:
+ foo: "1"
+ YAML
+
+ 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"
+ extend Rack::Test::Methods
+ load_app
+
+ get "/i18n"
+
+ assert_match "en.yml", last_response.body
+
+ # Wait a full second so we have time for changes to propagate
+ sleep(1)
+
+ app_file "config/locales/fr.yml", <<-YAML
+fr:
+ foo: "2"
+ YAML
+
+ get "/i18n"
+ assert_match "fr.yml", last_response.body
+ assert_match "en.yml", last_response.body
+ end
+
# Fallbacks
test "not using config.i18n.fallbacks does not initialize I18n.fallbacks" do
I18n.backend = Class.new(I18n::Backend::Simple).new
@@ -142,7 +214,7 @@ en:
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
@@ -150,7 +222,7 @@ en:
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
@@ -161,7 +233,7 @@ en:
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
@@ -172,18 +244,24 @@ en:
assert_fallbacks de: [:de, :'en-US', :en]
end
- test "[shortcut] config.i18n.fallbacks = [{ :ca => :'es-ES' }] initializes fallbacks with a mapping de-AT => de-DE" do
- I18n::Railtie.config.i18n.fallbacks.map = { :ca => :'es-ES' }
+ 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' }
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
+ test "[shortcut] config.i18n.fallbacks = { ca: :en } initializes fallbacks with a mapping ca => :en" do
+ I18n::Railtie.config.i18n.fallbacks = { ca: :en }
+ load_app
+ assert_fallbacks ca: [:ca, :en]
+ end
+
test "disable config.i18n.enforce_available_locales" do
add_to_config <<-RUBY
config.i18n.enforce_available_locales = false
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
new file mode 100644
index 0000000000..1118e5037a
--- /dev/null
+++ b/railties/test/application/integration_test_case_test.rb
@@ -0,0 +1,73 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ class IntegrationTestCaseTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ setup do
+ build_app
+ end
+
+ teardown do
+ teardown_app
+ end
+
+ test "resets Action Mailer test deliveries" do
+ script("generate mailer BaseMailer welcome")
+
+ app_file "test/integration/mailer_integration_test.rb", <<-RUBY
+ require 'test_helper'
+
+ class MailerIntegrationTest < ActionDispatch::IntegrationTest
+ setup do
+ @old_delivery_method = ActionMailer::Base.delivery_method
+ ActionMailer::Base.delivery_method = :test
+ end
+
+ teardown do
+ ActionMailer::Base.delivery_method = @old_delivery_method
+ end
+
+ 2.times do |i|
+ define_method "test_resets_deliveries_\#{i}" do
+ BaseMailer.welcome.deliver_now
+ assert_equal 1, ActionMailer::Base.deliveries.count
+ end
+ 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
+
+ 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 1027bca2c1..c75a25bc6f 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
@@ -56,10 +55,10 @@ class LoadingTest < ActiveSupport::TestCase
require "#{rails_root}/config/environment"
- assert_nothing_raised(NameError) { Trackable }
- assert_nothing_raised(NameError) { EmailLoggable }
- assert_nothing_raised(NameError) { Orderable }
- assert_nothing_raised(NameError) { Matchable }
+ assert_nothing_raised { Trackable }
+ assert_nothing_raised { EmailLoggable }
+ assert_nothing_raised { Orderable }
+ assert_nothing_raised { Matchable }
end
test "models without table do not panic on scope definitions when loaded" do
@@ -103,24 +102,24 @@ 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"
setup_ar!
- assert_equal [ActiveRecord::SchemaMigration], ActiveRecord::Base.descendants
+ assert_equal [ActiveRecord::SchemaMigration, ActiveRecord::InternalMetadata], ActiveRecord::Base.descendants
get "/load"
- assert_equal [ActiveRecord::SchemaMigration, Post], ActiveRecord::Base.descendants
+ assert_equal [ActiveRecord::SchemaMigration, ActiveRecord::InternalMetadata, Post], ActiveRecord::Base.descendants
get "/unload"
- assert_equal [ActiveRecord::SchemaMigration], ActiveRecord::Base.descendants
+ assert_equal [ActiveRecord::SchemaMigration, ActiveRecord::InternalMetadata], ActiveRecord::Base.descendants
end
test "initialize cant be called twice" do
@@ -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"
@@ -169,10 +168,12 @@ class LoadingTest < ActiveSupport::TestCase
config.file_watcher = Class.new do
def initialize(*); end
def updated?; false; end
+ def execute; end
+ def execute_if_updated; false; end
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
@@ -184,7 +185,7 @@ class LoadingTest < ActiveSupport::TestCase
end
MODEL
- require 'rack/test'
+ require "rack/test"
extend Rack::Test::Methods
require "#{rails_root}/config/environment"
@@ -207,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]] }
@@ -220,7 +221,7 @@ class LoadingTest < ActiveSupport::TestCase
end
MODEL
- require 'rack/test'
+ require "rack/test"
extend Rack::Test::Methods
require "#{rails_root}/config/environment"
@@ -239,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
@@ -253,7 +254,7 @@ class LoadingTest < ActiveSupport::TestCase
end
MODEL
- require 'rack/test'
+ require "rack/test"
extend Rack::Test::Methods
require "#{rails_root}/config/environment"
@@ -272,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]] }
@@ -284,11 +285,11 @@ 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
- class CreatePosts < ActiveRecord::Migration
+ class CreatePosts < ActiveRecord::Migration::Current
def change
create_table :posts do |t|
t.string :title, default: "TITLE"
@@ -297,14 +298,14 @@ 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"
assert_equal "TITLE", last_response.body
app_file "db/migrate/2_add_body_to_posts.rb", <<-MIGRATION
- class AddBodyToPosts < ActiveRecord::Migration
+ class AddBodyToPosts < ActiveRecord::Migration::Current
def change
add_column :posts, :body, :text, default: "BODY"
end
@@ -339,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
@@ -356,15 +357,15 @@ class LoadingTest < ActiveSupport::TestCase
assert Rails.application.initialized?
end
- protected
+ private
- 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 e462d2c15e..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"
+ 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 &#39;notifier&#39; 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..dc1d816dc5 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
@@ -20,7 +19,7 @@ module ApplicationTests
class ExpiresController < ApplicationController
def expires_header
expires_in 10, public: !params[:private]
- render text: SecureRandom.hex(16)
+ render plain: SecureRandom.hex(16)
end
def expires_etag
@@ -33,18 +32,18 @@ module ApplicationTests
end
def keeps_if_modified_since
- render :text => request.headers['If-Modified-Since']
+ render plain: request.headers['If-Modified-Since']
end
private
def render_conditionally(headers)
if stale?(headers.merge(public: !params[:private]))
- render text: SecureRandom.hex(16)
+ render plain: SecureRandom.hex(16)
end
end
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 4906f9a1e8..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
@@ -48,7 +47,7 @@ module ApplicationTests
test "uses custom exceptions app" do
add_to_config <<-RUBY
config.exceptions_app = lambda do |env|
- [404, { "Content-Type" => "text/plain" }, ["YOU FAILED BRO"]]
+ [404, { "Content-Type" => "text/plain" }, ["YOU FAILED"]]
end
RUBY
@@ -56,7 +55,7 @@ module ApplicationTests
get "/foo"
assert_equal 404, last_response.status
- assert_equal "YOU FAILED BRO", last_response.body
+ assert_equal "YOU FAILED", last_response.body
end
test "url generation error when action_dispatch.show_exceptions is set raises an exception" do
@@ -67,10 +66,10 @@ module ApplicationTests
end
end
RUBY
-
+
app.config.action_dispatch.show_exceptions = true
- get '/foo'
+ get "/foo"
assert_equal 500, last_response.status
end
@@ -78,15 +77,15 @@ module ApplicationTests
app.config.action_dispatch.show_exceptions = false
assert_raise(ActionController::RoutingError) do
- get '/foo'
+ get "/foo"
end
end
test "unspecified route when action_dispatch.show_exceptions is set shows 404" do
app.config.action_dispatch.show_exceptions = true
- assert_nothing_raised(ActionController::RoutingError) do
- get '/foo'
+ assert_nothing_raised do
+ get "/foo"
assert_match "The page you were looking for doesn't exist.", last_response.body
end
end
@@ -95,8 +94,8 @@ module ApplicationTests
app.config.action_dispatch.show_exceptions = true
app.config.consider_all_requests_local = true
- assert_nothing_raised(ActionController::RoutingError) do
- get '/foo'
+ assert_nothing_raised do
+ 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 97d5b5c698..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|
@@ -36,10 +36,10 @@ module ApplicationTests
test "works with both headers individually" do
make_basic_app
- assert_nothing_raised(ActionDispatch::RemoteIp::IpSpoofAttackError) do
+ assert_nothing_raised do
assert_equal "1.1.1.1", remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1")
end
- assert_nothing_raised(ActionDispatch::RemoteIp::IpSpoofAttackError) do
+ assert_nothing_raised do
assert_equal "1.1.1.2", remote_ip("HTTP_CLIENT_IP" => "1.1.1.2")
end
end
@@ -49,7 +49,7 @@ module ApplicationTests
app.config.action_dispatch.ip_spoofing_check = false
end
- assert_nothing_raised(ActionDispatch::RemoteIp::IpSpoofAttackError) do
+ assert_nothing_raised do
assert_equal "1.1.1.1", remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1", "HTTP_CLIENT_IP" => "1.1.1.2")
end
end
@@ -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 dc96480d6d..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,8 +59,8 @@ module ApplicationTests
test "files handled by ActionDispatch::Static are handled by Rack::Sendfile" do
make_basic_app do |app|
- app.config.action_dispatch.x_sendfile_header = 'X-Sendfile'
- app.config.serve_static_files = true
+ 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 25eadfc387..959a629ede 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
@@ -20,12 +19,19 @@ module ApplicationTests
@app ||= Rails.application
end
- test "config.force_ssl sets cookie to secure only" do
+ test "config.force_ssl sets cookie to secure only by default" do
add_to_config "config.force_ssl = true"
require "#{app_path}/config/environment"
assert app.config.session_options[:secure], "Expected session to be marked as secure"
end
+ test "config.force_ssl doesn't set cookie to secure only when changed from default" do
+ add_to_config "config.force_ssl = true"
+ add_to_config "config.ssl_options = { secure_cookies: false }"
+ require "#{app_path}/config/environment"
+ assert !app.config.session_options[:secure]
+ end
+
test "session is not loaded if it's not used" do
make_basic_app
@@ -47,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)'
@@ -64,7 +70,7 @@ module ApplicationTests
end
def read_session
- render text: session[:foo].inspect
+ render plain: session[:foo].inspect
end
end
RUBY
@@ -75,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)'
@@ -105,7 +111,7 @@ module ApplicationTests
end
def read_cookie
- render text: cookies[:foo].inspect
+ render plain: cookies[:foo].inspect
end
end
RUBY
@@ -116,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
@@ -143,38 +149,38 @@ module ApplicationTests
end
def read_session
- render text: session[:foo]
+ render plain: session[:foo]
end
def read_encrypted_cookie
- render text: cookies.encrypted[:_myapp_session]['foo']
+ render plain: cookies.encrypted[:_myapp_session]['foo']
end
def read_raw_cookie
- render text: cookies[:_myapp_session]
+ render plain: cookies[:_myapp_session]
end
end
RUBY
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')
- encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret)
+ secret = app.key_generator.generate_key("encrypted cookie")
+ sign_secret = app.key_generator.generate_key("signed encrypted cookie")
+ encryptor = ActiveSupport::MessageEncryptor.new(secret[0, ActiveSupport::MessageEncryptor.key_len], 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
@@ -188,15 +194,15 @@ module ApplicationTests
end
def read_session
- render text: session[:foo]
+ render plain: session[:foo]
end
def read_encrypted_cookie
- render text: cookies.encrypted[:_myapp_session]['foo']
+ render plain: cookies.encrypted[:_myapp_session]['foo']
end
def read_raw_cookie
- render text: cookies[:_myapp_session]
+ render plain: cookies[:_myapp_session]
end
end
RUBY
@@ -207,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')
- encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret)
+ secret = app.key_generator.generate_key("encrypted cookie")
+ sign_secret = app.key_generator.generate_key("signed encrypted cookie")
+ encryptor = ActiveSupport::MessageEncryptor.new(secret[0, ActiveSupport::MessageEncryptor.key_len], 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
@@ -243,15 +249,15 @@ module ApplicationTests
end
def read_session
- render text: session[:foo]
+ render plain: session[:foo]
end
def read_encrypted_cookie
- render text: cookies.encrypted[:_myapp_session]['foo']
+ render plain: cookies.encrypted[:_myapp_session]['foo']
end
def read_raw_cookie
- render text: cookies[:_myapp_session]
+ render plain: cookies[:_myapp_session]
end
end
RUBY
@@ -262,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')
- encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret)
+ secret = app.key_generator.generate_key("encrypted cookie")
+ sign_secret = app.key_generator.generate_key("signed encrypted cookie")
+ encryptor = ActiveSupport::MessageEncryptor.new(secret[0, ActiveSupport::MessageEncryptor.key_len], 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
@@ -302,15 +308,15 @@ module ApplicationTests
end
def read_session
- render text: session[:foo]
+ render plain: session[:foo]
end
def read_signed_cookie
- render text: cookies.signed[:_myapp_session]['foo']
+ render plain: cookies.signed[:_myapp_session]['foo']
end
def read_raw_cookie
- render text: cookies[:_myapp_session]
+ render plain: cookies[:_myapp_session]
end
end
RUBY
@@ -322,21 +328,55 @@ 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"
+
+ controller :test, <<-RUBY
+ class TestController < ApplicationController
+ def dump_flash
+ request.reset_session
+ render plain: 'It worked!'
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ get '/dump_flash' => "test#dump_flash"
+ end
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ get "/dump_flash"
+
+ assert_equal 200, last_response.status
+ assert_equal "It worked!", last_response.body
+
+ 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 1a46cd3568..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,32 +18,49 @@ 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 "static_index defaults to 'index'" do
+ test "headers for static files are configurable" do
+ app_file "public/about.html", "static"
+ add_to_config <<-CONFIG
+ config.public_file_server.headers = {
+ "Access-Control-Allow-Origin" => "http://rubyonrails.org",
+ "Cache-Control" => "public, max-age=60"
+ }
+ CONFIG
+
+ require "#{app_path}/config/environment"
+
+ 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"]
+ 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
- test "static_index configurable" do
+ test "public_file_server.index_name configurable" do
app_file "public/other-index.html", "/other-index.html"
- add_to_config "config.static_index = 'other-index'"
-
+ add_to_config "config.public_file_server.index_name = 'other-index'"
+
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 ce92ebbf66..0a6e5b52e9 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
@@ -26,24 +25,21 @@ module ApplicationTests
assert_equal [
"Rack::Sendfile",
"ActionDispatch::Static",
- "Rack::Lock",
+ "ActionDispatch::Executor",
"ActiveSupport::Cache::Strategy::LocalCache",
"Rack::Runtime",
"Rack::MethodOverride",
"ActionDispatch::RequestId",
- "Rails::Rack::Logger", # must come after Rack::MethodOverride to properly log overridden methods
+ "ActionDispatch::RemoteIp",
+ "Rails::Rack::Logger",
"ActionDispatch::ShowExceptions",
"ActionDispatch::DebugExceptions",
- "ActionDispatch::RemoteIp",
"ActionDispatch::Reloader",
"ActionDispatch::Callbacks",
"ActiveRecord::Migration::CheckPending",
- "ActiveRecord::ConnectionAdapters::ConnectionManagement",
- "ActiveRecord::QueryCache",
"ActionDispatch::Cookies",
"ActionDispatch::Session::CookieStore",
"ActionDispatch::Flash",
- "ActionDispatch::ParamsParser",
"Rack::Head",
"Rack::ConditionalGet",
"Rack::ETag"
@@ -58,29 +54,57 @@ module ApplicationTests
assert_equal [
"Rack::Sendfile",
"ActionDispatch::Static",
- "Rack::Lock",
+ "ActionDispatch::Executor",
"ActiveSupport::Cache::Strategy::LocalCache",
"Rack::Runtime",
"ActionDispatch::RequestId",
- "Rails::Rack::Logger", # must come after Rack::MethodOverride to properly log overridden methods
+ "ActionDispatch::RemoteIp",
+ "Rails::Rack::Logger",
"ActionDispatch::ShowExceptions",
"ActionDispatch::DebugExceptions",
- "ActionDispatch::RemoteIp",
"ActionDispatch::Reloader",
"ActionDispatch::Callbacks",
- "ActiveRecord::ConnectionAdapters::ConnectionManagement",
- "ActiveRecord::QueryCache",
- "ActionDispatch::ParamsParser",
"Rack::Head",
"Rack::ConditionalGet",
"Rack::ETag"
], middleware
end
+ test "middleware dependencies" do
+ boot!
+
+ # The following array-of-arrays describes dependencies between
+ # middlewares: the first item in each list depends on the
+ # remaining items (and therefore must occur later in the
+ # middleware stack).
+
+ dependencies = [
+ # Logger needs a fully "corrected" request environment
+ %w(Rails::Rack::Logger Rack::MethodOverride ActionDispatch::RequestId ActionDispatch::RemoteIp),
+
+ # Serving public/ doesn't invoke user code, so it should skip
+ # locks etc
+ %w(ActionDispatch::Executor ActionDispatch::Static),
+
+ # Errors during reload must be reported
+ %w(ActionDispatch::Reloader ActionDispatch::ShowExceptions ActionDispatch::DebugExceptions),
+
+ # Outright dependencies
+ %w(ActionDispatch::Static Rack::Sendfile),
+ %w(ActionDispatch::Flash ActionDispatch::Session::CookieStore),
+ %w(ActionDispatch::Session::CookieStore ActionDispatch::Cookies),
+ ]
+
+ require "tsort"
+ sorted = TSort.tsort((middleware | dependencies.flatten).method(:each),
+ lambda { |n, &b| dependencies.each { |m, *ds| ds.each(&b) if m == n } })
+ assert_equal sorted, middleware
+ end
+
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
@@ -88,7 +112,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
@@ -96,67 +120,70 @@ 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
add_to_config "config.force_ssl = true"
- add_to_config "config.ssl_options = { host: 'example.com' }"
+ add_to_config "config.ssl_options = { redirect: { host: 'example.com' } }"
boot!
- assert_equal [{host: 'example.com'}], Rails.application.middleware.first.args
+ assert_equal [{ redirect: { host: "example.com" } }], Rails.application.middleware.first.args
end
test "removing Active Record omits its middleware" do
use_frameworks []
boot!
- assert !middleware.include?("ActiveRecord::ConnectionAdapters::ConnectionManagement")
- assert !middleware.include?("ActiveRecord::QueryCache")
- assert !middleware.include?("ActiveRecord::Migration::CheckPending")
+ assert_not_includes middleware, "ActiveRecord::Migration::CheckPending"
end
- test "includes lock if cache_classes is set but eager_load is not" do
- add_to_config "config.cache_classes = true"
+ test "includes executor" do
boot!
- assert middleware.include?("Rack::Lock")
+ assert_includes middleware, "ActionDispatch::Executor"
end
test "does not include lock if cache_classes is set and so is eager_load" do
add_to_config "config.cache_classes = true"
add_to_config "config.eager_load = true"
boot!
- assert !middleware.include?("Rack::Lock")
+ assert_not_includes middleware, "Rack::Lock"
end
- test "does not include lock if allow_concurrency is set" do
- add_to_config "config.allow_concurrency = true"
+ test "does not include lock if allow_concurrency is set to :unsafe" do
+ add_to_config "config.allow_concurrency = :unsafe"
boot!
- assert !middleware.include?("Rack::Lock")
+ assert_not_includes middleware, "Rack::Lock"
end
- test "removes static asset server if serve_static_files is disabled" do
- add_to_config "config.serve_static_files = false"
+ test "includes lock if allow_concurrency is disabled" do
+ add_to_config "config.allow_concurrency = false"
boot!
- assert !middleware.include?("ActionDispatch::Static")
+ assert_includes middleware, "Rack::Lock"
+ end
+
+ test "removes static asset server if public_file_server.enabled is disabled" do
+ add_to_config "config.public_file_server.enabled = false"
+ boot!
+ 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
@@ -164,21 +191,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
@@ -194,10 +221,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
@@ -231,35 +258,35 @@ module ApplicationTests
class ::OmgController < ActionController::Base
def index
if params[:nothing]
- render text: ""
+ render plain: ""
else
- render text: "OMG"
+ render plain: "OMG"
end
end
end
- etag = "W/" + "5af83e3196bf99f440f31f2e1a6c9afe".inspect
+ etag = "W/" + "c00862d1c6c1cf7c1b49388306e7b3c1".inspect
get "/"
assert_equal 200, last_response.status
assert_equal "OMG", last_response.body
- assert_equal "text/html; charset=utf-8", last_response.headers["Content-Type"]
+ assert_equal "text/plain; charset=utf-8", last_response.headers["Content-Type"]
assert_equal "max-age=0, private, must-revalidate", last_response.headers["Cache-Control"]
assert_equal etag, last_response.headers["Etag"]
get "/", {}, "HTTP_IF_NONE_MATCH" => etag
assert_equal 304, last_response.status
assert_equal "", last_response.body
- assert_equal nil, last_response.headers["Content-Type"]
+ assert_nil last_response.headers["Content-Type"]
assert_equal "max-age=0, private, must-revalidate", last_response.headers["Cache-Control"]
assert_equal etag, last_response.headers["Etag"]
get "/?nothing=true"
assert_equal 200, last_response.status
assert_equal "", last_response.body
- assert_equal "text/html; charset=utf-8", last_response.headers["Content-Type"]
+ assert_equal "text/plain; charset=utf-8", last_response.headers["Content-Type"]
assert_equal "no-cache", last_response.headers["Cache-Control"]
- assert_equal nil, last_response.headers["Etag"]
+ assert_nil last_response.headers["Etag"]
end
test "ORIGINAL_FULLPATH is passed to env" do
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
new file mode 100644
index 0000000000..6c003e9bcc
--- /dev/null
+++ b/railties/test/application/per_request_digest_cache_test.rb
@@ -0,0 +1,66 @@
+require "isolation/abstract_unit"
+require "rack/test"
+require "minitest/mock"
+
+require "action_view"
+require "active_support/testing/method_call_assertions"
+
+class PerRequestDigestCacheTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+ include ActiveSupport::Testing::MethodCallAssertions
+ include Rack::Test::Methods
+
+ setup do
+ build_app
+ add_to_config "config.consider_all_requests_local = true"
+
+ 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
+ Rails.application.routes.draw do
+ resources :customers, only: :index
+ end
+ RUBY
+
+ app_file "app/controllers/customers_controller.rb", <<-RUBY
+ class CustomersController < ApplicationController
+ self.perform_caching = true
+
+ def index
+ render [ Customer.new('david', 1), Customer.new('dingus', 2) ]
+ end
+ end
+ RUBY
+
+ app_file "app/views/customers/_customer.html.erb", <<-RUBY
+ <% cache customer do %>
+ <%= customer.name %>
+ <% end %>
+ RUBY
+
+ require "#{app_path}/config/environment"
+ end
+
+ teardown :teardown_app
+
+ test "digests are reused when rendering the same template twice" do
+ get "/customers"
+ assert_equal 200, last_response.status
+
+ values = ActionView::LookupContext::DetailsKey.digest_caches.first.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"
+ assert_equal 200, last_response.status
+ end
+ 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 e7beab8b5e..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,50 +20,102 @@ 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
def db_create_and_drop(expected_database)
Dir.chdir(app_path) do
- output = `bin/rake db:create`
- assert_empty output
+ output = `bin/rails db:create`
+ assert_match(/Created database/, output)
assert File.exist?(expected_database)
assert_equal expected_database, ActiveRecord::Base.connection_config[:database]
- output = `bin/rake db:drop`
- assert_empty output
+ output = `bin/rails db:drop`
+ assert_match(/Dropped database/, output)
assert !File.exist?(expected_database)
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
end
+ def with_database_existing
+ Dir.chdir(app_path) do
+ set_database_url
+ `bin/rails db:create`
+ yield
+ `bin/rails db:drop`
+ end
+ end
+
+ test "db:create failure because database exists" do
+ with_database_existing do
+ output = `bin/rails db:create 2>&1`
+ assert_match(/already exists/, output)
+ assert_equal 0, $?.exitstatus
+ end
+ end
+
+ def with_bad_permissions
+ Dir.chdir(app_path) do
+ set_database_url
+ FileUtils.chmod("-w", "db")
+ yield
+ FileUtils.chmod("+w", "db")
+ end
+ end
+
+ 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)
+ assert_equal 1, $?.exitstatus
+ end
+ end
+
+ 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)
+ assert_equal 0, $?.exitstatus
+ end
+ end
+
+ test "db:drop failure because bad permissions" do
+ with_database_existing do
+ with_bad_permissions do
+ output = `bin/rails db:drop 2>&1`
+ assert_match(/Couldn't drop/, output)
+ assert_equal 1, $?.exitstatus
+ end
+ end
+ end
+
def db_migrate_and_status(expected_database)
Dir.chdir(app_path) do
`bin/rails generate model book title:string;
- bin/rake db:migrate`
- output = `bin/rake db:migrate:status`
+ bin/rails db:migrate`
+ output = `bin/rails db:migrate:status`
assert_match(%r{database:\s+\S*#{Regexp.escape(expected_database)}}, output)
assert_match(/up\s+\d{14}\s+Create books/, output)
end
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
@@ -73,17 +124,17 @@ module ApplicationTests
def db_schema_dump
Dir.chdir(app_path) do
`bin/rails generate model book title:string;
- bin/rake db:migrate db:schema:dump`
+ bin/rails db:migrate db:schema:dump`
schema_dump = File.read("db/schema.rb")
assert_match(/create_table \"books\"/, schema_dump)
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
@@ -91,29 +142,29 @@ module ApplicationTests
def db_fixtures_load(expected_database)
Dir.chdir(app_path) do
`bin/rails generate model book title:string;
- bin/rake db:migrate db:fixtures:load`
+ bin/rails db:migrate db:fixtures:load`
assert_match expected_database, ActiveRecord::Base.connection_config[:database]
require "#{app_path}/app/models/book"
assert_equal 2, Book.count
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;
- bin/rake db:migrate db:fixtures:load`
+ bin/rails db:migrate db:fixtures:load`
require "#{app_path}/app/models/admin/book"
assert_equal 2, Admin::Book.count
end
@@ -122,10 +173,10 @@ module ApplicationTests
def db_structure_dump_and_load(expected_database)
Dir.chdir(app_path) do
`bin/rails generate model book title:string;
- bin/rake db:migrate db:structure:dump`
+ bin/rails db:migrate db:structure:dump`
structure_dump = File.read("db/structure.sql")
assert_match(/CREATE TABLE \"books\"/, structure_dump)
- `bin/rake environment db:drop db:structure:load`
+ `bin/rails environment db:drop db:structure:load`
assert_match expected_database, ActiveRecord::Base.connection_config[:database]
require "#{app_path}/app/models/book"
#if structure is not loaded correctly, exception would be raised
@@ -133,34 +184,34 @@ 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 }'`
- stderr_output = capture(:stderr) { `bin/rake db:structure:dump` }
+ stderr_output = capture(:stderr) { `bin/rails db:structure:dump` }
assert_empty stderr_output
structure_dump = File.read("db/structure.sql")
assert_match(/CREATE TABLE \"posts\"/, structure_dump)
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
@@ -169,29 +220,29 @@ module ApplicationTests
list_tables = lambda { `bin/rails runner 'p ActiveRecord::Base.connection.tables'`.strip }
assert_equal '["posts"]', list_tables[]
- `bin/rake db:schema:load`
- assert_equal '["posts", "comments", "schema_migrations"]', list_tables[]
+ `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
- `bin/rake db:structure:load`
- assert_equal '["posts", "comments", "schema_migrations", "users"]', list_tables[]
+ `bin/rails db:structure:load`
+ assert_equal '["posts", "comments", "schema_migrations", "ar_internal_metadata", "users"]', list_tables[]
end
end
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
@@ -199,7 +250,7 @@ module ApplicationTests
end
RUBY
- `bin/rake db:schema:load`
+ `bin/rails db:schema:load`
tables = `bin/rails runner 'p ActiveRecord::Base.connection.tables'`.strip
assert_match(/"geese"/, tables)
@@ -212,30 +263,30 @@ module ApplicationTests
def db_test_load_structure
Dir.chdir(app_path) do
`bin/rails generate model book title:string;
- bin/rake db:migrate db:structure:dump db:test:load_structure`
+ bin/rails db:migrate db:structure:dump db:test:load_structure`
ActiveRecord::Base.configurations = Rails.application.config.database_configuration
ActiveRecord::Base.establish_connection :test
require "#{app_path}/app/models/book"
#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
@@ -243,12 +294,12 @@ module ApplicationTests
end
RUBY
- app_file 'db/seeds.rb', <<-RUBY
+ app_file "db/seeds.rb", <<-RUBY
puts ActiveRecord::Base.connection_config[:database]
RUBY
Dir.chdir(app_path) do
- database_path = `bin/rake db:setup`
+ database_path = `bin/rails db:setup`
assert_equal "development.sqlite3", File.basename(database_path.strip)
end
ensure
diff --git a/railties/test/application/rake/dev_test.rb b/railties/test/application/rake/dev_test.rb
new file mode 100644
index 0000000000..4f992d9c8d
--- /dev/null
+++ b/railties/test/application/rake/dev_test.rb
@@ -0,0 +1,43 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ module RakeTests
+ class RakeDevTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ 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_match(/Development mode is now being cached/, output)
+ end
+ end
+
+ 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_match(/Development mode is no longer being cached/, output)
+ end
+ end
+
+ test "dev:cache removes server.pid also" do
+ Dir.chdir(app_path) do
+ FileUtils.mkdir_p("tmp/pids")
+ FileUtils.touch("tmp/pids/server.pid")
+ `rails dev:cache`
+ assert_not File.exist?("tmp/pids/server.pid")
+ end
+ end
+ end
+ end
+end
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/log_test.rb b/railties/test/application/rake/log_test.rb
new file mode 100644
index 0000000000..fdd3c71fe8
--- /dev/null
+++ b/railties/test/application/rake/log_test.rb
@@ -0,0 +1,33 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ module RakeTests
+ class LogTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test "log:clear clear all environments log files by default" do
+ Dir.chdir(app_path) do
+ File.open("config/environments/staging.rb", "w")
+
+ File.write("log/staging.log", "staging")
+ File.write("log/test.log", "test")
+ File.write("log/dummy.log", "dummy")
+
+ `rails log:clear`
+
+ assert_equal 0, File.size("log/test.log")
+ assert_equal 0, File.size("log/staging.log")
+ assert_equal 5, File.size("log/dummy.log")
+ end
+ end
+ end
+ end
+end
diff --git a/railties/test/application/rake/migrations_test.rb b/railties/test/application/rake/migrations_test.rb
index 2d8bd7c571..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,23 +12,23 @@ 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`
app_file "db/migrate/01_a_migration.bukkits.rb", <<-MIGRATION
- class AMigration < ActiveRecord::Migration
+ class AMigration < ActiveRecord::Migration::Current
end
MIGRATION
- output = `bin/rake db:migrate SCOPE=bukkits`
+ output = `bin/rails db:migrate SCOPE=bukkits`
assert_no_match(/create_table\(:users\)/, output)
assert_no_match(/CreateUsers/, output)
assert_no_match(/add_column\(:users, :email, :string\)/, output)
assert_match(/AMigration: migrated/, output)
- output = `bin/rake db:migrate SCOPE=bukkits VERSION=0`
+ output = `bin/rails db:migrate SCOPE=bukkits VERSION=0`
assert_no_match(/drop_table\(:users\)/, output)
assert_no_match(/CreateUsers/, output)
assert_no_match(/remove_column\(:users, :email\)/, output)
@@ -38,164 +37,186 @@ 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/rake db:migrate`
- assert_match(/create_table\(:users\)/, output)
- assert_match(/CreateUsers: migrated/, output)
- assert_match(/add_column\(:users, :email, :string\)/, output)
- assert_match(/AddEmailToUsers: migrated/, output)
-
- output = `bin/rake db:rollback STEP=2`
- assert_match(/drop_table\(:users\)/, output)
- assert_match(/CreateUsers: reverted/, output)
- assert_match(/remove_column\(:users, :email, :string\)/, output)
- 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/rake 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;
- bin/rake db:migrate`
+ bin/rails db:migrate`
- output = `bin/rake 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)
- `bin/rake db:rollback STEP=1`
- output = `bin/rake db:migrate:status`
+ `bin/rails db:rollback STEP=1`
+ output = `bin/rails db:migrate:status`
assert_match(/up\s+\d{14}\s+Create users/, output)
assert_match(/down\s+\d{14}\s+Add email to users/, output)
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;
bin/rails generate migration add_email_to_users email:string;
- bin/rake db:migrate`
+ bin/rails db:migrate`
- output = `bin/rake 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)
- `bin/rake db:rollback STEP=1`
- output = `bin/rake db:migrate:status`
+ `bin/rails db:rollback STEP=1`
+ output = `bin/rails db:migrate:status`
assert_match(/up\s+\d{3,}\s+Create users/, output)
assert_match(/down\s+\d{3,}\s+Add email to users/, output)
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/rake db:migrate`
+ bin/rails db:migrate`
- output = `bin/rake 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/rake db:rollback STEP=2`
- output = `bin/rake 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/rake db:migrate:redo`
- output = `bin/rake 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/rake db:migrate`
+ bin/rails db:migrate`
+
+ output = `bin/rails db:migrate:status`
- output = `bin/rake db:migrate:status`
+ assert_match(/up\s+\d{3,}\s+Create users/, output)
+ assert_match(/up\s+\d{3,}\s+Add email to users/, output)
+
+ `bin/rails db:rollback STEP=2`
+ 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(/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/rake db:rollback STEP=2`
- output = `bin/rake db:migrate:status`
+ assert_match(/up\s+\d{3,}\s+Create users/, output)
+ assert_match(/up\s+\d{3,}\s+Add email to users/, output)
+ end
+ end
+
+ test "running migrations with not timestamp head migration files" do
+ Dir.chdir(app_path) do
+
+ app_file "db/migrate/1_one_migration.rb", <<-MIGRATION
+ class OneMigration < ActiveRecord::Migration::Current
+ end
+ MIGRATION
+
+ app_file "db/migrate/02_two_migration.rb", <<-MIGRATION
+ class TwoMigration < ActiveRecord::Migration::Current
+ end
+ MIGRATION
- 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`
- `bin/rake db:migrate:redo`
- output = `bin/rake 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+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`
output = `bin/rails generate model author name:string`
version = output =~ %r{[^/]+db/migrate/(\d+)_create_authors\.rb} && $1
- `bin/rake db:migrate db:rollback db:forward db:migrate:up db:migrate:down VERSION=#{version}`
+ `bin/rails db:migrate db:rollback db:forward db:migrate:up db:migrate:down VERSION=#{version}`
assert !File.exist?("db/schema.rb"), "should not dump schema when configured not to"
end
- add_to_config('config.active_record.dump_schema_after_migration = true')
+ add_to_config("config.active_record.dump_schema_after_migration = true")
Dir.chdir(app_path) do
`bin/rails generate model reviews book_id:integer`
- `bin/rake db:migrate`
+ `bin/rails db:migrate`
structure_dump = File.read("db/schema.rb")
assert_match(/create_table "reviews"/, structure_dump)
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/rake db:migrate`
+ bin/rails db:migrate`
structure_dump = File.read("db/schema.rb")
assert_match(/create_table "books"/, structure_dump)
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;
- bin/rake db:migrate
+ bin/rails db:migrate
rm db/migrate/*email*.rb`
- output = `bin/rake db:migrate:status`
- File.write('test.txt', output)
+ output = `bin/rails db:migrate:status`
+ 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 d6f5fee5c3..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"
@@ -74,7 +74,7 @@ module ApplicationTests
app_file "some_other_dir/blah.rb", "# TODO: note in some_other directory"
- run_rake_notes "SOURCE_ANNOTATION_DIRECTORIES='some_other_dir' bin/rake notes" do |output, lines|
+ run_rake_notes "SOURCE_ANNOTATION_DIRECTORIES='some_other_dir' bin/rails notes" do |output, lines|
assert_match(/note in app directory/, output)
assert_match(/note in config directory/, output)
assert_match(/note in db directory/, output)
@@ -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"
@@ -102,7 +102,7 @@ module ApplicationTests
end
EOS
- run_rake_notes "bin/rake notes_custom" do |output, lines|
+ run_rake_notes "bin/rails notes_custom" do |output, lines|
assert_match(/\[FIXME\] note in lib directory/, output)
assert_match(/\[TODO\] note in test directory/, output)
assert_no_match(/OPTIMIZE/, output)
@@ -113,7 +113,8 @@ 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"
app_file "app/assets/stylesheets/application.css.sass", "// TODO: note in sass"
@@ -125,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/rake 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 4cae199e6b..6ebd2d5461 100644
--- a/railties/test/application/rake/restart_test.rb
+++ b/railties/test/application/rake/restart_test.rb
@@ -7,31 +7,39 @@ 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 "rails restart removes server.pid also" do
+ Dir.chdir(app_path) do
+ FileUtils.mkdir_p("tmp/pids")
+ FileUtils.touch("tmp/pids/server.pid")
+ `bin/rails restart`
+ assert_not File.exist?("tmp/pids/server.pid")
end
end
end
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index a040dd4cf6..d80a45a83f 100644
--- a/railties/test/application/rake_test.rb
+++ b/railties/test/application/rake_test.rb
@@ -1,4 +1,3 @@
-# coding:utf-8
require "isolation/abstract_unit"
require "active_support/core_ext/string/strip"
@@ -8,7 +7,6 @@ module ApplicationTests
def setup
build_app
- boot_rails
end
def teardown
@@ -25,6 +23,26 @@ module ApplicationTests
assert $task_loaded
end
+ test "task is protected when previous migration was production" do
+ Dir.chdir(app_path) do
+ output = `bin/rails generate model product name:string;
+ env RAILS_ENV=production bin/rails db:create db:migrate;
+ env RAILS_ENV=production bin/rails db:test:prepare test 2>&1`
+
+ assert_match(/ActiveRecord::ProtectedEnvironmentError/, output)
+ end
+ end
+
+ def test_not_protected_when_previous_migration_was_not_production
+ Dir.chdir(app_path) do
+ output = `bin/rails generate model product name:string;
+ env RAILS_ENV=test bin/rails db:create db:migrate;
+ env RAILS_ENV=test bin/rails db:test:prepare test 2>&1`
+
+ refute_match(/ActiveRecord::ProtectedEnvironmentError/, output)
+ end
+ end
+
def test_environment_is_required_in_rake_tasks
app_file "config/environment.rb", <<-RUBY
SuperMiddleware = Struct.new(:app)
@@ -36,7 +54,7 @@ module ApplicationTests
Rails.application.initialize!
RUBY
- assert_match("SuperMiddleware", Dir.chdir(app_path){ `bin/rake middleware` })
+ assert_match("SuperMiddleware", Dir.chdir(app_path) { `bin/rails middleware` })
end
def test_initializers_are_executed_in_rake_tasks
@@ -51,7 +69,7 @@ module ApplicationTests
end
RUBY
- output = Dir.chdir(app_path){ `bin/rake do_nothing` }
+ output = Dir.chdir(app_path) { `bin/rails do_nothing` }
assert_match "Doing something...", output
end
@@ -64,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'
@@ -72,8 +90,8 @@ module ApplicationTests
end
RUBY
- output = Dir.chdir(app_path) { `bin/rake do_nothing` }
- assert_match 'Hello world', output
+ output = Dir.chdir(app_path) { `bin/rails do_nothing` }
+ assert_match "Hello world", output
end
def test_should_not_eager_load_model_for_rake
@@ -84,37 +102,119 @@ 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/rake 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
def test_code_statistics_sanity
- assert_match "Code LOC: 7 Test LOC: 0 Code to Test Ratio: 1:0.0",
- Dir.chdir(app_path){ `bin/rake stats` }
+ assert_match "Code LOC: 26 Test LOC: 0 Code to Test Ratio: 1:0.0",
+ Dir.chdir(app_path) { `bin/rails stats` }
+ end
+
+ def test_rails_routes_calls_the_route_inspector
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ get '/cart', to: 'cart#show'
+ end
+ RUBY
+
+ 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
+
+ def test_rails_routes_with_controller_environment
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ get '/cart', to: 'cart#show'
+ get '/basketball', to: 'basketball#index'
+ end
+ RUBY
+
+ 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` }
+ assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output
end
- def test_rake_routes_calls_the_route_inspector
+ def test_rails_routes_with_namespaced_controller_environment
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ namespace :admin do
+ resource :post
+ end
+ end
+ RUBY
+ expected_output = [" Prefix Verb URI Pattern Controller#Action",
+ " new_admin_post GET /admin/post/new(.:format) admin/posts#new",
+ "edit_admin_post GET /admin/post/edit(.:format) admin/posts#edit",
+ " admin_post GET /admin/post(.:format) admin/posts#show",
+ " PATCH /admin/post(.:format) admin/posts#update",
+ " PUT /admin/post(.:format) admin/posts#update",
+ " DELETE /admin/post(.:format) admin/posts#destroy",
+ " POST /admin/post(.:format) admin/posts#create\n"].join("\n")
+
+ 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` }
+ assert_equal expected_output, output
+ end
+
+ def test_singular_resource_output_in_rake_routes
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ resource :post
+ end
+ RUBY
+
+ expected_output = [" Prefix Verb URI Pattern Controller#Action",
+ " new_post GET /post/new(.:format) posts#new",
+ "edit_post GET /post/edit(.:format) posts#edit",
+ " post GET /post(.:format) posts#show",
+ " PATCH /post(.:format) posts#update",
+ " PUT /post(.:format) posts#update",
+ " DELETE /post(.:format) posts#destroy",
+ " POST /post(.:format) posts#create\n"].join("\n")
+
+ output = Dir.chdir(app_path) { `bin/rails routes -c PostController` }
+ assert_equal expected_output, output
+ end
+
+ def test_rails_routes_with_global_search_key
app_file "config/routes.rb", <<-RUBY
Rails.application.routes.draw do
get '/cart', to: 'cart#show'
+ post '/cart', to: 'cart#create'
+ get '/basketballs', to: 'basketball#index'
end
RUBY
- output = Dir.chdir(app_path){ `bin/rake routes` }
+ 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` }
+ 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` }
+ assert_equal " Prefix Verb URI Pattern Controller#Action\n" \
+ "basketballs GET /basketballs(.:format) basketball#index\n", output
end
- def test_rake_routes_with_controller_environment
+ def test_rails_routes_with_controller_search_key
app_file "config/routes.rb", <<-RUBY
Rails.application.routes.draw do
get '/cart', to: 'cart#show'
@@ -122,18 +222,23 @@ module ApplicationTests
end
RUBY
- ENV['CONTROLLER'] = 'cart'
- output = Dir.chdir(app_path){ `bin/rake routes` }
+ 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` }
+ 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` }
assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output
end
- def test_rake_routes_displays_message_when_no_routes_are_defined
+ def test_rails_routes_displays_message_when_no_routes_are_defined
app_file "config/routes.rb", <<-RUBY
Rails.application.routes.draw do
end
RUBY
- assert_equal <<-MESSAGE.strip_heredoc, Dir.chdir(app_path){ `bin/rake 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.
@@ -142,6 +247,17 @@ module ApplicationTests
MESSAGE
end
+ def test_rake_routes_with_rake_options
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ get '/cart', to: 'cart#show'
+ end
+ RUBY
+
+ 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
+
def test_logger_is_flushed_when_exiting_production_rake_tasks
add_to_config <<-RUBY
rake_tasks do
@@ -151,7 +267,7 @@ module ApplicationTests
end
RUBY
- output = Dir.chdir(app_path){ `bin/rake 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
@@ -159,13 +275,13 @@ module ApplicationTests
Dir.chdir(app_path) do
`bin/rails generate model user username:string password:string;
bin/rails generate model product name:string;
- bin/rake db:migrate`
+ bin/rails db:migrate`
end
require "#{rails_root}/config/environment"
# loading a specific fixture
- errormsg = Dir.chdir(app_path) { `bin/rake db:fixtures:load FIXTURES=products` }
+ errormsg = Dir.chdir(app_path) { `bin/rails db:fixtures:load FIXTURES=products` }
assert $?.success?, errormsg
assert_equal 2, ::AppTemplate::Application::Product.count
@@ -174,23 +290,23 @@ module ApplicationTests
def test_loading_only_yml_fixtures
Dir.chdir(app_path) do
- `bin/rake db:migrate`
+ `bin/rails db:migrate`
end
app_file "test/fixtures/products.csv", ""
require "#{rails_root}/config/environment"
- errormsg = Dir.chdir(app_path) { `bin/rake db:fixtures:load` }
+ errormsg = Dir.chdir(app_path) { `bin/rails db:fixtures:load` }
assert $?.success?, errormsg
end
def test_scaffold_tests_pass_by_default
output = Dir.chdir(app_path) do
`bin/rails generate scaffold user username:string password:string;
- bin/rake db:migrate test`
+ 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
@@ -206,23 +322,22 @@ module ApplicationTests
output = Dir.chdir(app_path) do
`bin/rails generate scaffold user username:string password:string;
- bin/rake db:migrate test`
+ RAILS_ENV=test bin/rails db:migrate test`
end
assert_match(/5 runs, 7 assertions, 0 failures, 0 errors/, output)
assert_no_match(/Errors running/, output)
end
- def test_scaffold_with_references_columns_tests_pass_when_belongs_to_is_optional
- app_file "config/initializers/active_record_belongs_to_required_by_default.rb",
- "Rails.application.config.active_record.belongs_to_required_by_default = false"
-
+ def test_scaffold_with_references_columns_tests_pass_by_default
output = Dir.chdir(app_path) do
- `bin/rails generate scaffold LineItems product:references cart:belongs_to;
- bin/rake db:migrate test`
+ `bin/rails generate model Product;
+ bin/rails generate model Cart;
+ bin/rails generate scaffold LineItems product:references cart:belongs_to;
+ 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
@@ -230,8 +345,8 @@ module ApplicationTests
add_to_config "config.active_record.schema_format = :sql"
output = Dir.chdir(app_path) do
`bin/rails generate scaffold user username:string;
- bin/rake db:migrate;
- bin/rake db:test:clone 2>&1 --trace`
+ bin/rails db:migrate;
+ bin/rails db:test:clone 2>&1 --trace`
end
assert_match(/Execute db:test:clone_structure/, output)
end
@@ -240,8 +355,8 @@ module ApplicationTests
add_to_config "config.active_record.schema_format = :sql"
output = Dir.chdir(app_path) do
`bin/rails generate scaffold user username:string;
- bin/rake db:migrate;
- bin/rake db:test:prepare 2>&1 --trace`
+ bin/rails db:migrate;
+ bin/rails db:test:prepare 2>&1 --trace`
end
assert_match(/Execute db:test:load_structure/, output)
end
@@ -249,9 +364,9 @@ module ApplicationTests
def test_rake_dump_structure_should_respect_db_structure_env_variable
Dir.chdir(app_path) do
# ensure we have a schema_migrations table to dump
- `bin/rake db:migrate db:structure:dump SCHEMA=db/my_structure.sql`
+ `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
@@ -259,7 +374,7 @@ module ApplicationTests
output = Dir.chdir(app_path) do
`bin/rails g model post title:string;
- bin/rake db:migrate:redo 2>&1 --trace;`
+ bin/rails db:migrate:redo 2>&1 --trace;`
end
# expect only Invoke db:structure:dump (first_time)
@@ -270,26 +385,26 @@ module ApplicationTests
Dir.chdir(app_path) do
`bin/rails generate model post title:string;
bin/rails generate model product name:string;
- bin/rake db:migrate db:schema:cache:dump`
+ 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.yml"))
end
def test_rake_clear_schema_cache
Dir.chdir(app_path) do
- `bin/rake db:schema:cache:dump db:schema:cache:clear`
+ `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.yml"))
end
def test_copy_templates
Dir.chdir(app_path) do
- `bin/rake rails:templates:copy`
+ `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
@@ -299,7 +414,7 @@ module ApplicationTests
app_file "template.rb", ""
output = Dir.chdir(app_path) do
- `bin/rake rails:template LOCATION=template.rb`
+ `bin/rails app:template LOCATION=template.rb`
end
assert_match(/Hello, World!/, output)
@@ -307,7 +422,7 @@ module ApplicationTests
def test_tmp_clear_should_work_if_folder_missing
FileUtils.remove_dir("#{app_path}/tmp")
- errormsg = Dir.chdir(app_path) { `bin/rake tmp:clear` }
+ errormsg = Dir.chdir(app_path) { `bin/rails tmp:clear` }
assert_predicate $?, :success?
assert_empty errormsg
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 cbada6be97..c515e2b270 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
@@ -21,6 +20,12 @@ module ApplicationTests
assert_equal 200, last_response.status
end
+ test "rails/info in development" do
+ app("development")
+ get "/rails/info"
+ assert_equal 302, last_response.status
+ end
+
test "rails/info/routes in development" do
app("development")
get "/rails/info/routes"
@@ -33,28 +38,46 @@ 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")
- get '/'
- assert_match %r{<h1>Getting started</h1>} , last_response.body
+ assert_welcome get("/")
controller :foo, <<-RUBY
class FooController < ApplicationController
def index
- render text: "foo"
+ render plain: "foo"
end
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
@@ -63,6 +86,12 @@ module ApplicationTests
assert_equal 404, last_response.status
end
+ test "rails/info in production" do
+ app("production")
+ get "/rails/info"
+ assert_equal 404, last_response.status
+ end
+
test "rails/info/routes in production" do
app("production")
get "/rails/info/routes"
@@ -78,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
@@ -91,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"
@@ -99,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
@@ -119,35 +148,35 @@ 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
controller :foo, <<-RUBY
class FooController < ApplicationController
def index
- render text: my_blog_path
+ render plain: my_blog_path
end
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
controller :foo, <<-RUBY
class FooController < ApplicationController
def index
- render text: "foo"
+ render plain: "foo"
end
end
RUBY
@@ -155,59 +184,59 @@ module ApplicationTests
controller :bar, <<-RUBY
class BarController < ActionController::Base
def index
- render text: "bar"
+ render plain: "bar"
end
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"
+ render plain: "foo"
end
end
RUBY
- controller 'admin/foo', <<-RUBY
+ controller "admin/foo", <<-RUBY
module Admin
class FooController < ApplicationController
def index
- render text: "admin::foo"
+ render plain: "admin::foo"
end
end
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
@@ -219,36 +248,36 @@ 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
def bar
- render text: "bar"
+ render plain: "bar"
end
def baz
- render text: "baz"
+ render plain: "baz"
end
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
@@ -256,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
@@ -267,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
@@ -280,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!
@@ -298,36 +327,36 @@ module ApplicationTests
end
def test_root_path
- app('development')
+ app("development")
controller :foo, <<-RUBY
class FooController < ApplicationController
def index
- render :text => "foo"
+ render plain: "foo"
end
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
def index
- render text: "foo"
+ render plain: "foo"
end
end
RUBY
@@ -335,28 +364,28 @@ module ApplicationTests
controller :bar, <<-RUBY
class BarController < ApplicationController
def index
- render text: "bar"
+ render plain: "bar"
end
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'
@@ -365,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
@@ -381,24 +410,24 @@ 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
def index
- render text: "foo"
+ render plain: "foo"
end
end
RUBY
@@ -406,22 +435,22 @@ module ApplicationTests
controller :bar, <<-RUBY
class BarController < ApplicationController
def index
- render text: "bar"
+ render plain: "bar"
end
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
@@ -429,39 +458,39 @@ 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'
+ render plain: 'yazilar#index'
end
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 0c180339b4..7d058f6ee6 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
@@ -44,6 +43,15 @@ module ApplicationTests
assert_match "42", Dir.chdir(app_path) { `bin/rails runner "bin/count_users.rb"` }
end
+ def test_no_minitest_loaded_in_production_mode
+ app_file "bin/print_features.rb", <<-SCRIPT
+ p $LOADED_FEATURES.grep(/minitest/)
+ SCRIPT
+ assert_match "[]", Dir.chdir(app_path) {
+ `RAILS_ENV=production bin/rails runner "bin/print_features.rb"`
+ }
+ end
+
def test_should_set_dollar_0_to_file
app_file "bin/dollar0.rb", <<-SCRIPT
puts $0
@@ -60,6 +68,14 @@ module ApplicationTests
assert_match "bin/program_name.rb", Dir.chdir(app_path) { `bin/rails runner "bin/program_name.rb"` }
end
+ def test_passes_extra_args_to_file
+ app_file "bin/program_name.rb", <<-SCRIPT
+ p ARGV
+ SCRIPT
+
+ assert_match %w( a b ).to_s, Dir.chdir(app_path) { `bin/rails runner "bin/program_name.rb" a b` }
+ end
+
def test_with_hook
add_to_config <<-RUBY
runner do |app|
@@ -74,6 +90,18 @@ module ApplicationTests
assert_match "development", Dir.chdir(app_path) { `bin/rails runner "puts Rails.env"` }
end
+ def test_runner_detects_syntax_errors
+ 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
+ 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
with_rails_env "production" do
assert_match "production", Dir.chdir(app_path) { `bin/rails runner "puts Rails.env"` }
diff --git a/railties/test/application/test_runner_test.rb b/railties/test/application/test_runner_test.rb
index 494e6dd7bd..0939587960 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,22 +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("")
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
@@ -259,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
@@ -282,73 +287,264 @@ 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
+ require 'test_helper'
+
+ class PostTest < ActiveSupport::TestCase
+ test "first filter" do
+ puts 'PostTest:FirstFilter'
+ assert true
+ end
+
+ test "second filter" do
+ puts 'PostTest:SecondFilter'
+ assert true
+ end
+
+ test "test line filter does not run this" do
+ assert true
+ end
+ 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
+ end
+ end
+
+ def test_more_than_one_line_filter_with_multiple_files
+ app_file "test/models/account_test.rb", <<-RUBY
+ require 'test_helper'
+
+ class AccountTest < ActiveSupport::TestCase
+ test "first filter" do
+ puts 'AccountTest:FirstFilter'
+ assert true
+ end
+
+ test "second filter" do
+ puts 'AccountTest:SecondFilter'
+ assert true
+ end
+
+ test "line filter does not run this" do
+ assert true
+ end
+ end
+ RUBY
+
+ app_file "test/models/post_test.rb", <<-RUBY
+ require 'test_helper'
+
+ class PostTest < ActiveSupport::TestCase
+ test "first filter" do
+ puts 'PostTest:FirstFilter'
+ assert true
+ end
+
+ test "second filter" do
+ puts 'PostTest:SecondFilter'
+ assert true
+ end
+
+ test "line filter does not run this" do
+ assert true
+ end
+ 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
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
+ end
+ end
+
+ def test_line_filters_trigger_only_one_runnable
+ app_file "test/models/post_test.rb", <<-RUBY
+ require 'test_helper'
+
+ class PostTest < ActiveSupport::TestCase
+ test 'truth' do
+ assert true
+ end
+ end
+
+ class SecondPostTest < ActiveSupport::TestCase
+ test 'truth' do
+ assert false, 'ran second runnable'
+ end
+ end
+ RUBY
- 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
+ # 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
end
end
- def test_line_filter_without_line_runs_all_tests
- create_test_file :models, 'account'
+ def test_line_filter_with_minitest_string_filter
+ app_file "test/models/post_test.rb", <<-RUBY
+ require 'test_helper'
+
+ class PostTest < ActiveSupport::TestCase
+ test 'by line' do
+ puts 'by line'
+ assert true
+ end
+
+ test 'by name' do
+ puts 'by name'
+ assert true
+ end
+ end
+ RUBY
- run_test_command('test/models/account_test.rb:').tap do |output|
- assert_match 'AccountTest', 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
+
+ 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
+
+ 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
+
+ assert_match(/Interrupt/,
+ 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") }
+ 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
+ # 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
+ end
+
+ def test_pass_rake_options
+ 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
+ end
+
+ def test_rails_db_create_all_restores_db_connection
+ 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"
+ 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"
+ 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"
+ 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
@@ -363,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'
@@ -376,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
@@ -388,24 +584,24 @@ 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')
+ def create_test_file(path = :unit, name = "test", pass: true)
app_file "test/#{path}/#{name}_test.rb", <<-RUBY
require 'test_helper'
class #{name.camelize}Test < ActiveSupport::TestCase
def test_truth
puts "#{name.camelize}Test"
- assert true
+ assert #{pass}, 'wups!'
end
end
RUBY
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
@@ -417,13 +613,17 @@ 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"
+ end
+
def run_migration
- Dir.chdir(app_path) { `bin/rake db:migrate` }
+ Dir.chdir(app_path) { `bin/rails db:migrate` }
end
end
end
diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb
index 0e997f4ba7..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
@@ -232,7 +263,7 @@ module ApplicationTests
assert_successful_test_run "models/user_test.rb"
- Dir.chdir(app_path) { `bin/rake db:test:prepare` }
+ Dir.chdir(app_path) { `bin/rails db:test:prepare` }
assert_unsuccessful_run "models/user_test.rb", <<-ASSERTION
Expected: ["id", "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..37f129475c 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"
@@ -28,7 +27,7 @@ module ApplicationTests
class ::OmgController < ::ApplicationController
def index
- render text: omg_path
+ render plain: omg_path
end
end
@@ -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..f71e56f323 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]
+ 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]
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 46445a001a..1bd4225f34 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)
@@ -52,7 +52,7 @@ class CodeStatisticsCalculatorTest < ActiveSupport::TestCase
assert_equal 3, @code_statistics_calculator.classes
assert_equal 4, @code_statistics_calculator.methods
- code_statistics_calculator_2 = CodeStatisticsCalculator.new(2, 3, 4, 5)
+ code_statistics_calculator_2 = CodeStatisticsCalculator.new(2, 3, 4, 5)
@code_statistics_calculator.add(code_statistics_calculator_2)
assert_equal 3, @code_statistics_calculator.lines
@@ -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,9 +299,25 @@ class Animal
assert_equal 0, @code_statistics_calculator.methods
end
+ test "count rake tasks" do
+ code = <<-'CODE'
+ task :test_task do
+ puts 'foo'
+ end
+
+ CODE
+
+ @code_statistics_calculator.add_by_io(StringIO.new(code), :rake)
+
+ assert_equal 4, @code_statistics_calculator.lines
+ assert_equal 3, @code_statistics_calculator.code_lines
+ assert_equal 0, @code_statistics_calculator.classes
+ assert_equal 0, @code_statistics_calculator.methods
+ end
+
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 1b1ff80bc1..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.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'tmp', '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,9 +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
+ def foo
+ puts 'foo'
+ end
+ CODE
+
+ assert_nothing_raised do
+ 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 7950ed6aa7..0f8c5dbb79 100644
--- a/railties/test/commands/dbconsole_test.rb
+++ b/railties/test/commands/dbconsole_test.rb
@@ -1,30 +1,29 @@
-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
config_sample = {
- "test"=> {
- "adapter"=> "sqlite3",
- "host"=> "localhost",
- "port"=> "9000",
- "database"=> "foo_test",
- "user"=> "foo",
- "password"=> "bar",
- "pool"=> "5",
- "timeout"=> "3000"
+ "test" => {
+ "adapter" => "sqlite3",
+ "host" => "localhost",
+ "port" => "9000",
+ "database" => "foo_test",
+ "user" => "foo",
+ "password" => "bar",
+ "pool" => "5",
+ "timeout" => "3000"
}
}
app_db_config(config_sample) do
@@ -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: 'mysql', 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: 'mysql', 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: 'mysql', 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
+
+ attr_reader :dbconsole
- def start(config = {}, argv = [])
- dbconsole.stub(:config, config.stringify_keys) do
- dbconsole.stub(:arguments, argv) do
- capture_abort { dbconsole.start }
+ 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
+
+ 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
- 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 ba688f1e9e..527529aa52 100644
--- a/railties/test/commands/server_test.rb
+++ b/railties/test/commands/server_test.rb
@@ -1,88 +1,150 @@
-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
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]
+ args = ["thin", "-e", "production"]
+ options = parse_arguments(args)
+ 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]
+ args = ["-e", "production"]
+ options = parse_arguments(args)
+ assert_equal "production", options[:environment]
assert_nil options[:server]
end
def test_server_option_without_environment
- args = ["thin"]
- options = Rails::Server::Options.new.parse!(args)
- assert_nil options[:environment]
- assert_equal 'thin', options[:server]
+ args = ["thin"]
+ with_rack_env nil do
+ with_rails_env nil do
+ options = parse_arguments(args)
+ assert_equal "development", options[:environment]
+ assert_equal "thin", options[:server]
+ end
+ end
end
def test_environment_with_rails_env
with_rack_env nil do
- with_rails_env 'production' do
- server = Rails::Server.new
- assert_equal 'production', server.options[:environment]
+ with_rails_env "production" do
+ options = parse_arguments
+ assert_equal "production", options[:environment]
end
end
end
def test_environment_with_rack_env
with_rails_env nil do
- with_rack_env 'production' do
- server = Rails::Server.new
- assert_equal 'production', server.options[:environment]
+ with_rack_env "production" do
+ options = parse_arguments
+ assert_equal "production", options[:environment]
end
end
end
+ def test_environment_with_port
+ switch_env "PORT", "1234" do
+ options = parse_arguments
+ assert_equal 1234, options[:Port]
+ end
+ end
+
+ def test_environment_with_host
+ switch_env "HOST", "1.2.3.4" do
+ options = parse_arguments
+ assert_equal "1.2.3.4", options[:Host]
+ end
+ end
+
+ def test_caching_without_option
+ args = []
+ options = parse_arguments(args)
+ assert_nil options[:caching]
+ end
+
+ def test_caching_with_option
+ args = ["--dev-caching"]
+ options = parse_arguments(args)
+ assert_equal true, options[:caching]
+
+ args = ["--no-dev-caching"]
+ options = parse_arguments(args)
+ assert_equal false, options[:caching]
+ end
+
def test_log_stdout
with_rack_env nil do
with_rails_env nil do
args = []
- options = Rails::Server::Options.new.parse!(args)
+ options = parse_arguments(args)
assert_equal true, options[:log_stdout]
args = ["-e", "development"]
- options = Rails::Server::Options.new.parse!(args)
+ options = parse_arguments(args)
assert_equal true, options[:log_stdout]
args = ["-e", "production"]
- options = Rails::Server::Options.new.parse!(args)
+ options = parse_arguments(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)
+ options = parse_arguments(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)
+ options = parse_arguments(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)
+ options = parse_arguments(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)
+ options = parse_arguments(args)
assert_equal false, options[:log_stdout]
end
end
end
end
+
+ def test_default_options
+ old_default_options = parse_arguments
+
+ Dir.chdir("..") do
+ default_options = parse_arguments
+ assert_equal old_default_options, default_options
+ end
+ end
+
+ def test_restart_command_contains_customized_options
+ original_args = ARGV.dup
+ args = %w(-p 4567 -b 127.0.0.1 -c dummy_config.ru -d -e test -P tmp/server.pid -C)
+ ARGV.replace args
+
+ options = parse_arguments(args)
+ expected = "bin/rails server -p 4567 -b 127.0.0.1 -c dummy_config.ru -d -e test -P tmp/server.pid -C"
+
+ assert_equal expected, options[:restart_cmd]
+ ensure
+ ARGV.replace original_args
+ end
+
+ private
+ def parse_arguments(args = [])
+ Rails::Command::ServerCommand.new([], args).server_options
+ end
end
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 2857dae07e..360e8e97d7 100644
--- a/railties/test/generators/actions_test.rb
+++ b/railties/test/generators/actions_test.rb
@@ -1,7 +1,6 @@
-require 'generators/generators_test_helper'
-require 'rails/generators/rails/app/app_generator'
-require 'env_helpers'
-require 'minitest/mock'
+require "generators/generators_test_helper"
+require "rails/generators/rails/app/app_generator"
+require "env_helpers"
class ActionsTest < Rails::Generators::TestCase
include GeneratorsTestHelper
@@ -12,126 +11,141 @@ class ActionsTest < Rails::Generators::TestCase
def setup
Rails.application = TestApp::Application
- @mock_generator = Minitest::Mock.new
super
end
def teardown
Rails.application = TestApp::Application.instance
- @mock_generator.verify
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"
+ end
+ 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
+ run_generator
+
+ action :gem, "frozen_gem".freeze, "1.0.0".freeze
+
+ 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
@@ -139,104 +153,132 @@ 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
- @mock_generator.expect(:call, nil, ['git init'])
- generator.stub(:run, @mock_generator) 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
- @mock_generator.expect(:call, nil, ["git rm README"])
- @mock_generator.expect(:call, nil, ["git add ."])
- generator.stub(:run, @mock_generator) do
- action :git, rm: 'README', add: '.'
+ assert_called_with(generator, :run, [ ["git rm README"], ["git add ."] ]) do
+ 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
- @mock_generator.expect(:call, nil, ['bin/rails generate model MyModel', verbose: false])
- generator.stub(:run_ruby_script, @mock_generator) 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"
+ 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"
+ 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
+ with_rails_env "production" do
+ 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
+ with_rails_env "staging" do
+ action :rake, "log:clear", env: "production"
+ end
+ end
+ end
+
+ 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
+ end
end
end
- def test_rake_should_run_rake_command_with_default_env
- @mock_generator.expect(:call, nil, ["rake log:clear RAILS_ENV=development", verbose: false])
- generator.stub(:run, @mock_generator) do
+ 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 :rake, 'log:clear'
+ action :rails_command, "log:clear"
end
end
end
- def test_rake_with_env_option_should_run_rake_command_in_env
- @mock_generator.expect(:call, nil, ['rake log:clear RAILS_ENV=production', verbose: false])
- generator.stub(:run, @mock_generator) do
- action :rake, 'log:clear', env: 'production'
+ 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"
end
end
- def test_rake_with_rails_env_variable_should_run_rake_command_in_env
- @mock_generator.expect(:call, nil, ['rake log:clear RAILS_ENV=production', verbose: false])
- generator.stub(:run, @mock_generator) do
+ 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
with_rails_env "production" do
- action :rake, 'log:clear'
+ action :rails_command, "log:clear"
end
end
end
- def test_env_option_should_win_over_rails_env_variable_when_running_rake
- @mock_generator.expect(:call, nil, ['rake log:clear RAILS_ENV=production', verbose: false])
- generator.stub(:run, @mock_generator) do
+ 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
with_rails_env "staging" do
- action :rake, 'log:clear', env: 'production'
+ action :rails_command, "log:clear", env: "production"
end
end
end
- def test_rake_with_sudo_option_should_run_rake_command_with_sudo
- @mock_generator.expect(:call, nil, ["sudo rake log:clear RAILS_ENV=development", verbose: false])
- generator.stub(:run, @mock_generator) do
+ 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 :rake, 'log:clear', sudo: true
+ action :rails_command, "log:clear", sudo: true
end
end
end
def test_capify_should_run_the_capify_command
- @mock_generator.expect(:call, nil, ['capify .', verbose: false])
- generator.stub(:run, @mock_generator) do
+ assert_called_with(generator, :run, ["capify .", verbose: false]) do
action :capify!
end
end
@@ -245,7 +287,22 @@ 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)
+
+ # runs first time, not asserting
+ action :route, "root 'welcome#index'"
+ content_1 = File.read(route_path)
+
+ # runs second time
+ action :route, "root 'welcome#index'"
+ content_2 = File.read(route_path)
+
+ assert_equal content_1, content_2
end
def test_route_should_add_data_with_an_new_line
@@ -255,11 +312,18 @@ 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) }
- assert_file "config/routes.rb", /\.routes\.draw do\n root 'welcome#index'\nend\n\z/
+
+ routes = <<-F
+Rails.application.routes.draw do
+ root 'welcome#index'
+end
+F
+
+ assert_file "config/routes.rb", routes
action :route, "resources :product_lines"
@@ -274,8 +338,7 @@ F
def test_readme
run_generator
- 2.times { @mock_generator.expect(:call, destination_root,[]) }
- Rails::Generators::AppGenerator.stub(:source_root, @mock_generator) do
+ assert_called(Rails::Generators::AppGenerator, :source_root, times: 2, returns: destination_root) do
assert_match "application up and running", action(:readme, "README.md")
end
end
@@ -283,8 +346,7 @@ F
def test_readme_with_quiet
generator(default_arguments, quiet: true)
run_generator
- 2.times { @mock_generator.expect(:call, destination_root,[]) }
- Rails::Generators::AppGenerator.stub(:source_root, @mock_generator) do
+ assert_called(Rails::Generators::AppGenerator, :source_root, times: 2, returns: destination_root) do
assert_no_match "application up and running", action(:readme, "README.md")
end
end
@@ -307,10 +369,9 @@ F
assert_equal("", action(:log, :yes, "YES"))
end
- protected
+ private
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 9978ad0da1..c54d9cc599 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
@@ -35,10 +35,9 @@ class ApiAppGeneratorTest < Rails::Generators::TestCase
assert_file "Gemfile" do |content|
assert_no_match(/gem 'coffee-rails'/, content)
- assert_no_match(/gem 'jquery-rails'/, content)
assert_no_match(/gem 'sass-rails'/, content)
- assert_no_match(/gem 'jbuilder'/, content)
- assert_match(/gem 'active_model_serializers'/, content)
+ assert_no_match(/gem 'web-console'/, content)
+ assert_match(/# gem 'jbuilder'/, content)
end
assert_file "config/application.rb" do |content|
@@ -52,45 +51,73 @@ class ApiAppGeneratorTest < Rails::Generators::TestCase
assert_file "app/controllers/application_controller.rb", /ActionController::API/
end
- private
-
- def default_files
- files = %W(
- .gitignore
- Gemfile
- Rakefile
- config.ru
- app/controllers
- app/mailers
- app/models
- 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
+ def test_generator_if_skip_action_cable_is_given
+ run_generator [destination_root, "--skip-action-cable"]
+ assert_file "config/application.rb", /#\s+require\s+["']action_cable\/engine["']/
+ assert_no_file "config/cable.yml"
+ assert_no_file "app/channels"
+ assert_file "Gemfile" do |content|
+ assert_no_match(/redis/, content)
+ end
end
- def skipped_files
- %w(app/assets
- app/helpers
- app/views
- config/initializers/assets.rb
- config/initializers/cookies_serializer.rb
- config/initializers/session_store.rb
- lib/assets
- vendor/assets
- test/helpers
- tmp/cache/assets)
+ def test_generator_skips_per_form_csrf_token_and_origin_check_configs_for_api_apps
+ run_generator
+
+ 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
+
+ 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
+ bin/yarn
+ config/initializers/assets.rb
+ config/initializers/cookies_serializer.rb
+ lib/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.icon
+ vendor/package.json
+ )
+ end
end
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index daf362357c..079ee3765c 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -1,7 +1,6 @@
-require 'generators/generators_test_helper'
-require 'rails/generators/rails/app/app_generator'
-require 'generators/shared_generator_tests'
-require 'mocha/setup' # FIXME: stop using mocha
+require "generators/generators_test_helper"
+require "rails/generators/rails/app/app_generator"
+require "generators/shared_generator_tests"
DEFAULT_APP_FILES = %w(
.gitignore
@@ -27,6 +26,9 @@ DEFAULT_APP_FILES = %w(
config/environments
config/initializers
config/locales
+ config/cable.yml
+ config/puma.rb
+ config/spring.rb
db
lib
lib/tasks
@@ -41,9 +43,6 @@ DEFAULT_APP_FILES = %w(
test/mailers
test/integration
vendor
- vendor/assets
- vendor/assets/stylesheets
- vendor/assets/javascripts
tmp
tmp/cache
tmp/cache/assets
@@ -63,8 +62,8 @@ class AppGeneratorTest < Rails::Generators::TestCase
def test_assets
run_generator
- assert_file("app/views/layouts/application.html.erb", /stylesheet_link_tag\s+'application', media: 'all', 'data-turbolinks-track' => true/)
- assert_file("app/views/layouts/application.html.erb", /javascript_include_tag\s+'application', 'data-turbolinks-track' => true/)
+ assert_file("app/views/layouts/application.html.erb", /stylesheet_link_tag\s+'application', media: 'all', 'data-turbolinks-track': 'reload'/)
+ assert_file("app/views/layouts/application.html.erb", /javascript_include_tag\s+'application', 'data-turbolinks-track': 'reload'/)
assert_file("app/assets/stylesheets/application.css")
assert_file("app/assets/javascripts/application.js")
end
@@ -75,7 +74,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
@@ -86,12 +85,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
@@ -102,7 +101,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`
@@ -117,35 +116,31 @@ class AppGeneratorTest < Rails::Generators::TestCase
run_generator [app_root]
- Rails.application.config.root = app_moved_root
- Rails.application.class.stubs(:name).returns("Myapp")
- Rails.application.stubs(:is_a?).returns(Rails::Application)
+ stub_rails_application(app_moved_root) do
+ Rails.application.stub(:is_a?, -> *args { Rails::Application }) do
+ FileUtils.mv(app_root, app_moved_root)
- FileUtils.mv(app_root, app_moved_root)
+ # make sure we are in correct dir
+ FileUtils.cd(app_moved_root)
- # make sure we are in correct dir
- FileUtils.cd(app_moved_root)
-
- generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true },
- destination_root: app_moved_root, shell: @shell
- 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/
+ generator = Rails::Generators::AppGenerator.new ["rails"], [],
+ destination_root: app_moved_root, shell: @shell
+ generator.send(:app_const)
+ quietly { generator.send(:update_config_files) }
+ assert_file "myapp_moved/config/environment.rb", /Rails\.application\.initialize!/
+ 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]
- Rails.application.config.root = app_root
- Rails.application.class.stubs(:name).returns("Myapp")
- Rails.application.stubs(:is_a?).returns(Rails::Application)
-
- generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, destination_root: app_root, shell: @shell
- generator.send(:app_const)
- quietly { generator.send(:update_config_files) }
- assert_file "myapp/config/initializers/session_store.rb", /_myapp_session/
+ 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) }
+ end
end
def test_new_application_use_json_serialzier
@@ -154,98 +149,96 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file("config/initializers/cookies_serializer.rb", /Rails\.application\.config\.action_dispatch\.cookies_serializer = :json/)
end
+ def test_new_application_not_include_api_initializers
+ run_generator
+
+ 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]
- Rails.application.config.root = app_root
- Rails.application.class.stubs(:name).returns("Myapp")
- Rails.application.stubs(:is_a?).returns(Rails::Application)
-
- generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, destination_root: app_root, shell: @shell
- generator.send(:app_const)
- quietly { generator.send(:update_config_files) }
- assert_file("#{app_root}/config/initializers/cookies_serializer.rb", /Rails\.application\.config\.action_dispatch\.cookies_serializer = :json/)
+ 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/cookies_serializer.rb", /Rails\.application\.config\.action_dispatch\.cookies_serializer = :json/)
+ end
end
- def test_rails_update_does_not_create_callback_terminator_initializer
- app_root = File.join(destination_root, 'myapp')
+ def test_rails_update_set_the_cookie_serializer_to_marshal_if_it_is_not_already_configured
+ app_root = File.join(destination_root, "myapp")
run_generator [app_root]
- FileUtils.rm("#{app_root}/config/initializers/callback_terminator.rb")
-
- Rails.application.config.root = app_root
- Rails.application.class.stubs(:name).returns("Myapp")
- Rails.application.stubs(:is_a?).returns(Rails::Application)
+ FileUtils.rm("#{app_root}/config/initializers/cookies_serializer.rb")
- generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, destination_root: app_root, shell: @shell
- generator.send(:app_const)
- quietly { generator.send(:update_config_files) }
- assert_no_file "#{app_root}/config/initializers/callback_terminator.rb"
+ 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/cookies_serializer.rb",
+ /Valid options are :json, :marshal, and :hybrid\.\nRails\.application\.config\.action_dispatch\.cookies_serializer = :marshal/)
+ end
end
- def test_rails_update_does_not_remove_callback_terminator_initializer_if_already_present
- app_root = File.join(destination_root, 'myapp')
+ def test_rails_update_dont_set_file_watcher
+ app_root = File.join(destination_root, "myapp")
run_generator [app_root]
- FileUtils.touch("#{app_root}/config/initializers/callback_terminator.rb")
-
- Rails.application.config.root = app_root
- Rails.application.class.stubs(:name).returns("Myapp")
- Rails.application.stubs(:is_a?).returns(Rails::Application)
-
- generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, destination_root: app_root, shell: @shell
- generator.send(:app_const)
- quietly { generator.send(:update_config_files) }
- assert_file "#{app_root}/config/initializers/callback_terminator.rb"
+ 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/environments/development.rb" do |content|
+ assert_match(/# config.file_watcher/, content)
+ end
+ end
end
- def test_rails_update_set_the_cookie_serializer_to_marchal_if_it_is_not_already_configured
- 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/cookies_serializer.rb")
+ FileUtils.rm("#{app_root}/config/initializers/new_framework_defaults.rb")
- Rails.application.config.root = app_root
- Rails.application.class.stubs(:name).returns("Myapp")
- Rails.application.stubs(:is_a?).returns(Rails::Application)
+ stub_rails_application(app_root) do
+ generator = Rails::Generators::AppGenerator.new ["rails"], { update: true }, destination_root: app_root, shell: @shell
+ generator.send(:app_const)
+ quietly { generator.send(:update_config_files) }
- generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, destination_root: app_root, shell: @shell
- generator.send(:app_const)
- quietly { generator.send(:update_config_files) }
- assert_file("#{app_root}/config/initializers/cookies_serializer.rb", /Rails\.application\.config\.action_dispatch\.cookies_serializer = :marshal/)
+ 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_active_record_belongs_to_required_by_default
- app_root = File.join(destination_root, 'myapp')
+ def test_rails_update_does_not_create_rack_cors
+ 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")
-
- Rails.application.config.root = app_root
- Rails.application.class.stubs(:name).returns("Myapp")
- Rails.application.stubs(:is_a?).returns(Rails::Application)
-
- generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, destination_root: app_root, shell: @shell
- generator.send(:app_const)
- quietly { generator.send(:update_config_files) }
- assert_no_file "#{app_root}/config/initializers/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_no_file "#{app_root}/config/initializers/cors.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')
+ def test_rails_update_does_not_remove_rack_cors_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")
-
- Rails.application.config.root = app_root
- Rails.application.class.stubs(:name).returns("Myapp")
- Rails.application.stubs(:is_a?).returns(Rails::Application)
+ FileUtils.touch("#{app_root}/config/initializers/cors.rb")
- generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, destination_root: app_root, shell: @shell
- generator.send(:app_const)
- quietly { generator.send(:update_config_files) }
- assert_file "#{app_root}/config/initializers/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/cors.rb"
+ end
end
def test_application_names_are_not_singularized
@@ -256,7 +249,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
@@ -279,7 +272,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
if defined?(JRUBY_VERSION)
assert_gem "activerecord-jdbcmysql-adapter"
else
- assert_gem "mysql2"
+ assert_gem "mysql2", "'>= 0.3.18', '< 0.5'"
end
end
@@ -294,7 +287,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
if defined?(JRUBY_VERSION)
assert_gem "activerecord-jdbcpostgresql-adapter"
else
- assert_gem "pg"
+ assert_gem "pg", "'~> 0.18'"
end
end
@@ -345,14 +338,38 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_generator_defaults_to_puma_version
+ run_generator [destination_root]
+ assert_gem "puma", "'~> 3.0'"
+ end
+
+ def test_generator_if_skip_puma_is_given
+ run_generator [destination_root, "--skip-puma"]
+ assert_no_file "config/puma.rb"
+ assert_file "Gemfile" do |content|
+ assert_no_match(/puma/, content)
+ end
+ end
+
def test_generator_if_skip_active_record_is_given
run_generator [destination_root, "--skip-active-record"]
+ assert_no_directory "db/"
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 "bin/setup" do |setup_content|
+ assert_no_match(/db:setup/, setup_content)
+ end
+ assert_file "bin/update" do |update_content|
+ assert_no_match(/db:migrate/, update_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
@@ -367,6 +384,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"
end
def test_generator_if_skip_sprockets_is_given
@@ -378,7 +404,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "Gemfile" do |content|
assert_no_match(/sass-rails/, content)
assert_no_match(/uglifier/, content)
- assert_match(/coffee-rails/, content)
+ assert_no_match(/coffee-rails/, content)
end
assert_file "config/environments/development.rb" do |content|
assert_no_match(/config\.assets\.debug = true/, content)
@@ -388,6 +414,25 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_no_match(/config\.assets\.js_compressor = :uglifier/, content)
assert_no_match(/config\.assets\.css_compressor = :sass/, content)
end
+ assert_file "config/initializers/new_framework_defaults.rb" do |content|
+ assert_no_match(/unknown_asset_fallback/, content)
+ end
+ end
+
+ def test_generator_if_skip_action_cable_is_given
+ run_generator [destination_root, "--skip-action-cable"]
+ assert_file "config/application.rb", /#\s+require\s+["']action_cable\/engine["']/
+ assert_no_file "config/cable.yml"
+ assert_no_file "app/assets/javascripts/cable.js"
+ assert_no_file "app/channels"
+ assert_file "Gemfile" do |content|
+ assert_no_match(/redis/, content)
+ end
+ end
+
+ def test_action_cable_redis_gems
+ run_generator
+ assert_file "Gemfile", /^# gem 'redis'/
end
def test_inclusion_of_javascript_runtime
@@ -399,29 +444,25 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
end
- def test_jquery_is_the_default_javascript_library
+ def test_rails_ujs_is_the_default_ujs_library
run_generator
assert_file "app/assets/javascripts/application.js" do |contents|
- assert_match %r{^//= require jquery}, contents
- assert_match %r{^//= require jquery_ujs}, contents
+ assert_match %r{^//= require rails-ujs}, contents
end
- assert_gem "jquery-rails"
end
- def test_other_javascript_libraries
- run_generator [destination_root, '-j', 'prototype']
+ def test_inclusion_of_javascript_libraries_if_required
+ run_generator [destination_root, "-j", "jquery"]
assert_file "app/assets/javascripts/application.js" do |contents|
- assert_match %r{^//= require prototype}, contents
- assert_match %r{^//= require prototype_ujs}, contents
+ assert_match %r{^//= require jquery}, contents
end
- assert_gem "prototype-rails"
+ assert_gem "jquery-rails"
end
def test_javascript_is_skipped_if_required
run_generator [destination_root, "--skip-javascript"]
assert_no_file "app/assets/javascripts"
- assert_no_file "vendor/assets/javascripts"
assert_file "app/views/layouts/application.html.erb" do |contents|
assert_match(/stylesheet_link_tag\s+'application', media: 'all' %>/, contents)
@@ -430,13 +471,41 @@ 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_coffeescript_is_skipped_if_required
+ run_generator [destination_root, "--skip-coffee"]
+
+ assert_file "Gemfile" do |content|
+ assert_no_match(/coffee-rails/, content)
+ assert_match(/uglifier/, content)
+ end
+ end
+
+ def test_generator_for_yarn
+ run_generator([destination_root])
+ assert_file "vendor/package.json", /dependencies/
+ assert_file "config/initializers/assets.rb", /node_modules/
+ end
+
+ def test_generator_for_yarn_skipped
+ run_generator([destination_root, "--skip-yarn"])
+ assert_no_file "vendor/package.json"
+
+ assert_file "config/initializers/assets.rb" do |content|
+ assert_no_match(/node_modules/, content)
end
end
def test_inclusion_of_jbuilder
run_generator
- assert_gem 'jbuilder'
+ assert_gem "jbuilder"
end
def test_inclusion_of_a_debugger
@@ -446,7 +515,32 @@ 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/
+ assert_listen_related_configuration
+ else
+ assert_no_listen_related_configuration
+ end
+ end
+
+ def test_non_inclusion_of_listen_related_configuration_if_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_match(/^\s*config.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content)
+ else
+ assert_match(/^\s*# config.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content)
+ end
end
end
@@ -456,13 +550,15 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
def test_usage_read_from_file
- File.expects(:read).returns("USAGE FROM FILE")
- assert_equal "USAGE FROM FILE", Rails::Generators::AppGenerator.desc
+ assert_called(File, :read, returns: "USAGE FROM FILE") do
+ assert_equal "USAGE FROM FILE", Rails::Generators::AppGenerator.desc
+ end
end
def test_default_usage
- Rails::Generators::AppGenerator.expects(:usage_path).returns(nil)
- assert_match(/Create rails files for app generator/, Rails::Generators::AppGenerator.desc)
+ assert_called(Rails::Generators::AppGenerator, :usage_path, returns: nil) do
+ assert_match(/Create rails files for app generator/, Rails::Generators::AppGenerator.desc)
+ end
end
def test_default_namespace
@@ -470,8 +566,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
@@ -486,13 +582,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)
@@ -502,15 +591,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
@@ -518,7 +606,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(/gem 'web-console', '~> 2.0'/, content)
+ assert_no_match(/\Agem 'web-console', '>= 3.3.0'\z/, content)
end
end
@@ -527,35 +615,64 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "Gemfile" do |content|
assert_match(/gem 'web-console',\s+github: 'rails\/web-console'/, content)
- assert_no_match(/gem 'web-console', '~> 2.0'/, content)
+ 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
jruby_skip "spring doesn't run on JRuby"
- generator.stubs(:bundle_command).with('install')
- generator.expects(:bundle_command).with('exec spring binstub --all').once
- quietly { generator.invoke_all }
+ command_check = -> command do
+ @binstub_called ||= 0
+
+ case command
+ when "install"
+ # Called when running bundle, we just want to stub it so nothing to do here.
+ 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
+ end
+
+ generator.stub :bundle_command, command_check do
+ quietly { generator.invoke_all }
+ end
end
def test_spring_no_fork
jruby_skip "spring doesn't run on JRuby"
- Process.stubs(:respond_to?).with(:fork).returns(false)
- run_generator
+ assert_called_with(Process, :respond_to?, [[:fork], [:fork]], returns: false) do
+ run_generator
- assert_file "Gemfile" do |content|
- assert_no_match(/spring/, content)
+ assert_file "Gemfile" do |content|
+ assert_no_match(/spring/, content)
+ end
end
end
def test_skip_spring
run_generator [destination_root, "--skip-spring"]
+ assert_no_file "config/spring.rb"
assert_file "Gemfile" do |content|
assert_no_match(/spring/, content)
end
@@ -586,15 +703,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
@@ -602,7 +719,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
@@ -611,8 +728,6 @@ class AppGeneratorTest < Rails::Generators::TestCase
run_generator
folders_with_keep = %w(
app/assets/images
- app/mailers
- app/models
app/controllers/concerns
app/models/concerns
lib/tasks
@@ -626,7 +741,6 @@ class AppGeneratorTest < Rails::Generators::TestCase
test/helpers
test/integration
tmp
- vendor/assets/stylesheets
)
folders_with_keep.each do |folder|
assert_file("#{folder}/.keep")
@@ -647,27 +761,90 @@ 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
- generator([destination_root], template: path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
+ check_open = -> *args do
+ assert_equal [ path, "Accept" => "application/x-thor-template" ], args
+ template
+ end
- bundler_first = sequence('bundle, binstubs, after_bundle')
- generator.expects(:bundle_command).with('install').once.in_sequence(bundler_first)
- generator.expects(:bundle_command).with('exec spring binstub --all').in_sequence(bundler_first)
- generator.expects(:run).with('echo ran after_bundle').in_sequence(bundler_first)
+ 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
+ end
- quietly { generator.invoke_all }
+ 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
+ end
+ end
+
+ assert_equal 3, @sequence_step
end
- protected
+ private
- def action(*args, &block)
- capture(:stdout) { generator.send(*args, &block) }
- end
+ def stub_rails_application(root)
+ Rails.application.config.root = root
+ Rails.application.class.stub(:name, "Myapp") do
+ yield
+ end
+ end
- def assert_gem(gem)
- assert_file "Gemfile", /^\s*gem\s+["']#{gem}["']$*/
- 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}["']$*/
+ end
+ end
+
+ 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)
+ end
+ end
+
+ 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
+
+ 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
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
new file mode 100644
index 0000000000..a1d54200ba
--- /dev/null
+++ b/railties/test/generators/channel_generator_test.rb
@@ -0,0 +1,77 @@
+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"]
+
+ assert_file "app/channels/application_cable/channel.rb" do |cable|
+ assert_match(/module ApplicationCable\n class Channel < ActionCable::Channel::Base\n/, cable)
+ end
+
+ assert_file "app/channels/application_cable/connection.rb" do |cable|
+ assert_match(/module ApplicationCable\n class Connection < ActionCable::Connection::Base\n/, cable)
+ end
+ end
+
+ def test_channel_is_created
+ 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.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"]
+
+ 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.js"
+ end
+
+ def test_cable_js_is_created_if_not_present_already
+ run_generator ["chat"]
+ FileUtils.rm("#{destination_root}/app/assets/javascripts/cable.js")
+ run_generator ["camp"]
+
+ assert_file "app/assets/javascripts/cable.js"
+ end
+
+ def test_channel_on_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.js"
+
+ assert_file "app/channels/application_cable/channel.rb"
+ assert_file "app/channels/application_cable/connection.rb"
+ assert_file "app/assets/javascripts/cable.js"
+ end
+end
diff --git a/railties/test/generators/controller_generator_test.rb b/railties/test/generators/controller_generator_test.rb
index 1351151afb..af86a0136f 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
@@ -65,7 +65,7 @@ class ControllerGeneratorTest < Rails::Generators::TestCase
def test_add_routes
run_generator
- assert_file "config/routes.rb", /get 'account\/foo'/, /get 'account\/bar'/
+ assert_file "config/routes.rb", /^ get 'account\/foo'/, /^ get 'account\/bar'/
end
def test_skip_routes
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 7871399dd7..904bade658 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
@@ -20,47 +20,47 @@ module Rails
end
def test_construction
- klass = make_builder_class
- assert klass.start(['new', 'blah'])
+ klass = make_builder_class
+ 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
@@ -80,6 +80,21 @@ module Rails
}
assert_equal gems.drop(2), generator.gemfile_entries
end
+
+ def test_recommended_rails_versions
+ klass = make_builder_class
+ 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"]
+ end
end
end
end
diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb
index 62ca0ecb4b..2cdddc8713 100644
--- a/railties/test/generators/generators_test_helper.rb
+++ b/railties/test/generators/generators_test_helper.rb
@@ -1,14 +1,15 @@
-require 'abstract_unit'
-require 'active_support/core_ext/module/remove_method'
-require 'active_support/testing/stream'
-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
@@ -19,12 +20,13 @@ 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
+ include ActiveSupport::Testing::MethodCallAssertions
def self.included(base)
base.class_eval do
@@ -32,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
@@ -44,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 7fd8f2062f..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
@@ -26,4 +26,11 @@ class JobGeneratorTest < Rails::Generators::TestCase
assert_match(/queue_as :admin/, job)
end
end
+
+ def test_application_job_skeleton_is_created
+ run_generator ["refresh_counters"]
+ assert_file "app/jobs/application_job.rb" do |job|
+ assert_match(/class ApplicationJob < ActiveJob::Base/, job)
+ end
+ end
end
diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb
index f01e8cd2d9..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
@@ -12,13 +12,10 @@ class MailerGeneratorTest < Rails::Generators::TestCase
assert_no_match(/default from: "from@example.com"/, mailer)
assert_no_match(/layout :mailer_notifier/, mailer)
end
- end
- def test_application_mailer_skeleton_is_created
- run_generator
assert_file "app/mailers/application_mailer.rb" do |mailer|
assert_match(/class ApplicationMailer < ActionMailer::Base/, mailer)
- assert_match(/default from: "from@example.com"/, mailer)
+ assert_match(/default from: 'from@example.com'/, mailer)
assert_match(/layout 'mailer'/, mailer)
end
end
@@ -33,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
@@ -62,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
@@ -70,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
@@ -106,15 +103,13 @@ class MailerGeneratorTest < Rails::Generators::TestCase
end
assert_file "app/views/layouts/mailer.html.erb" do |view|
- assert_match(%r{<html>\n <body>\n <%= yield %>\n </body>\n</html>}, view)
+ assert_match(%r{<body>\n <%= yield %>\n </body>}, view)
end
end
def test_invokes_default_template_engine_even_with_no_action
run_generator ["notifier"]
assert_file "app/views/notifier_mailer"
- assert_file "app/views/layouts/mailer.text.erb"
- assert_file "app/views/layouts/mailer.html.erb"
end
def test_logs_if_the_template_engine_cannot_be_found
@@ -162,10 +157,6 @@ class MailerGeneratorTest < Rails::Generators::TestCase
assert_no_file "app/views/notifier/bar.text.erb"
assert_no_file "app/views/notifier/foo.html.erb"
assert_no_file "app/views/notifier/bar.html.erb"
-
- assert_file "app/mailers/application_mailer.rb"
- assert_file "app/views/layouts/mailer.text.erb"
- assert_file "app/views/layouts/mailer.html.erb"
end
def test_mailer_suffix_is_not_duplicated
diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb
index 57bc220558..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
@@ -7,7 +7,7 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
def test_migration
migration = "change_title_body_from_posts"
run_generator [migration]
- assert_migration "db/migrate/#{migration}.rb", /class ChangeTitleBodyFromPosts < ActiveRecord::Migration/
+ assert_migration "db/migrate/#{migration}.rb", /class ChangeTitleBodyFromPosts < ActiveRecord::Migration\[[0-9.]+\]/
end
def test_migrations_generated_simultaneously
@@ -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
@@ -26,7 +26,7 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
def test_migration_with_class_name
migration = "ChangeTitleBodyFromPosts"
run_generator [migration]
- assert_migration "db/migrate/change_title_body_from_posts.rb", /class #{migration} < ActiveRecord::Migration/
+ assert_migration "db/migrate/change_title_body_from_posts.rb", /class #{migration} < ActiveRecord::Migration\[[0-9.]+\]/
end
def test_migration_with_invalid_file_name
@@ -79,8 +79,8 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
assert_migration "db/migrate/#{migration}.rb" do |content|
assert_method :change, content do |change|
- assert_match(/remove_reference :books, :author, index: true/, change)
- assert_match(/remove_reference :books, :distributor, polymorphic: true, index: true/, change)
+ assert_match(/remove_reference :books, :author/, change)
+ assert_match(/remove_reference :books, :distributor, polymorphic: true/, change)
end
end
end
@@ -166,8 +166,8 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
assert_migration "db/migrate/#{migration}.rb" do |content|
assert_method :change, content do |change|
- assert_match(/add_reference :books, :author, index: true/, change)
- assert_match(/add_reference :books, :distributor, polymorphic: true, index: true/, change)
+ assert_match(/add_reference :books, :author/, change)
+ assert_match(/add_reference :books, :distributor, polymorphic: true/, change)
end
end
end
@@ -178,8 +178,8 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
assert_migration "db/migrate/#{migration}.rb" do |content|
assert_method :change, content do |change|
- assert_match(/add_reference :books, :author, index: true, null: false/, change)
- assert_match(/add_reference :books, :distributor, polymorphic: true, index: true, null: false/, change)
+ assert_match(/add_reference :books, :author, null: false/, change)
+ assert_match(/add_reference :books, :distributor, polymorphic: true, null: false/, change)
end
end
end
@@ -221,6 +221,15 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_add_uuid_to_create_table_migration
+ run_generator ["create_books", "--primary_key_type=uuid"]
+ assert_migration "db/migrate/create_books.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/create_table :books, id: :uuid/, change)
+ end
+ end
+ end
+
def test_should_create_empty_migrations_if_name_not_start_with_add_or_remove_or_create
migration = "delete_books"
run_generator [migration, "title:string", "content:text"]
@@ -239,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 abd3ff50a4..2b9f3ed7f2 100644
--- a/railties/test/generators/model_generator_test.rb
+++ b/railties/test/generators/model_generator_test.rb
@@ -1,11 +1,19 @@
-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_help_shows_invoked_generators_options
content = run_generator ["--help"]
assert_match(/ActiveRecord options:/, content)
@@ -26,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
@@ -35,9 +43,20 @@ class ModelGeneratorTest < Rails::Generators::TestCase
assert_no_migration "db/migrate/create_accounts.rb"
end
+ def test_model_with_existent_application_record
+ mkdir_p "#{destination_root}/app/models"
+ touch "#{destination_root}/app/models/application_record.rb"
+
+ Dir.chdir(destination_root) do
+ run_generator ["account"]
+ end
+
+ assert_file "app/models/account.rb", /class Account < ApplicationRecord/
+ end
+
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
@@ -52,17 +71,17 @@ 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
run_generator
- assert_migration "db/migrate/create_accounts.rb", /class CreateAccounts < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_accounts.rb", /class CreateAccounts < ActiveRecord::Migration\[[0-9.]+\]/
end
def test_migration_with_namespace
run_generator ["Gallery::Image"]
- assert_migration "db/migrate/create_gallery_images", /class CreateGalleryImages < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_gallery_images", /class CreateGalleryImages < ActiveRecord::Migration\[[0-9.]+\]/
assert_no_migration "db/migrate/create_images"
end
@@ -70,7 +89,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
run_generator ["Admin::Gallery::Image"]
assert_no_migration "db/migrate/create_images"
assert_no_migration "db/migrate/create_gallery_images"
- assert_migration "db/migrate/create_admin_gallery_images", /class CreateAdminGalleryImages < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_admin_gallery_images", /class CreateAdminGalleryImages < ActiveRecord::Migration\[[0-9.]+\]/
assert_migration "db/migrate/create_admin_gallery_images", /create_table :admin_gallery_images/
end
@@ -80,7 +99,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
assert_no_migration "db/migrate/create_images"
assert_no_migration "db/migrate/create_gallery_images"
assert_no_migration "db/migrate/create_admin_gallery_images"
- assert_migration "db/migrate/create_admin_gallery_image", /class CreateAdminGalleryImage < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_admin_gallery_image", /class CreateAdminGalleryImage < ActiveRecord::Migration\[[0-9.]+\]/
assert_migration "db/migrate/create_admin_gallery_image", /create_table :admin_gallery_image/
ensure
ActiveRecord::Base.pluralize_table_names = true
@@ -89,7 +108,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
def test_migration_with_namespaces_in_model_name_without_plurization
ActiveRecord::Base.pluralize_table_names = false
run_generator ["Gallery::Image"]
- assert_migration "db/migrate/create_gallery_image", /class CreateGalleryImage < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_gallery_image", /class CreateGalleryImage < ActiveRecord::Migration\[[0-9.]+\]/
assert_no_migration "db/migrate/create_gallery_images"
ensure
ActiveRecord::Base.pluralize_table_names = true
@@ -98,7 +117,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
def test_migration_without_pluralization
ActiveRecord::Base.pluralize_table_names = false
run_generator
- assert_migration "db/migrate/create_account", /class CreateAccount < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_account", /class CreateAccount < ActiveRecord::Migration\[[0-9.]+\]/
assert_no_migration "db/migrate/create_accounts"
ensure
ActiveRecord::Base.pluralize_table_names = true
@@ -193,10 +212,10 @@ class ModelGeneratorTest < Rails::Generators::TestCase
def test_migration_without_timestamps
ActiveRecord::Base.timestamped_migrations = false
run_generator ["account"]
- assert_file "db/migrate/001_create_accounts.rb", /class CreateAccounts < ActiveRecord::Migration/
+ assert_file "db/migrate/001_create_accounts.rb", /class CreateAccounts < ActiveRecord::Migration\[[0-9.]+\]/
run_generator ["project"]
- assert_file "db/migrate/002_create_projects.rb", /class CreateProjects < ActiveRecord::Migration/
+ assert_file "db/migrate/002_create_projects.rb", /class CreateProjects < ActiveRecord::Migration\[[0-9.]+\]/
ensure
ActiveRecord::Base.timestamped_migrations = true
end
@@ -256,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
@@ -281,31 +300,31 @@ 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
run_generator ["LineItem", "product:references", "cart:belongs_to"]
- assert_file "test/fixtures/line_items.yml", /product: \n cart: /
+ assert_file "test/fixtures/line_items.yml", /product: one\n cart: one/
assert_generated_fixture("test/fixtures/line_items.yml",
- {"one"=>{"product"=>nil, "cart"=>nil}, "two"=>{"product"=>nil, "cart"=>nil}})
+ "one" => { "product" => "one", "cart" => "one" }, "two" => { "product" => "two", "cart" => "two" })
end
def test_fixtures_use_the_references_ids_and_type
run_generator ["LineItem", "product:references{polymorphic}", "cart:belongs_to"]
- assert_file "test/fixtures/line_items.yml", /product: \n product_type: Product\n cart: /
+ 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"=>nil, "product_type"=>"Product", "cart"=>nil},
- "two"=>{"product"=>nil, "product_type"=>"Product", "cart"=>nil}})
+ "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
@@ -324,36 +343,16 @@ 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
- def test_index_is_added_for_belongs_to_association
- run_generator ["account", "supplier:belongs_to"]
-
- assert_migration "db/migrate/create_accounts.rb" do |m|
- assert_method :change, m do |up|
- assert_match(/index: true/, up)
- end
- end
- end
-
- def test_index_is_added_for_references_association
- run_generator ["account", "supplier:references"]
-
- assert_migration "db/migrate/create_accounts.rb" do |m|
- assert_method :change, m do |up|
- assert_match(/index: true/, up)
- end
- end
- end
-
def test_index_is_skipped_for_belongs_to_association
run_generator ["account", "supplier:belongs_to", "--no-indexes"]
@@ -374,11 +373,20 @@ class ModelGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_add_uuid_to_create_table_migration
+ run_generator ["account", "--primary_key_type=uuid"]
+ assert_migration "db/migrate/create_accounts.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/create_table :accounts, id: :uuid/, change)
+ end
+ end
+ end
+
def test_required_belongs_to_adds_required_association
run_generator ["account", "supplier:references{required}"]
expected_file = <<-FILE.strip_heredoc
- class Account < ActiveRecord::Base
+ class Account < ApplicationRecord
belongs_to :supplier, required: true
end
FILE
@@ -389,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
@@ -400,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
@@ -451,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 1c32fc1bfd..3015b5363b 100644
--- a/railties/test/generators/named_base_test.rb
+++ b/railties/test/generators/named_base_test.rb
@@ -1,85 +1,84 @@
-require 'generators/generators_test_helper'
-require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator'
-require 'minitest/mock'
+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
@@ -90,49 +89,49 @@ 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
+ private
def assert_name(generator, value, method)
assert_equal value, generator.send(method)
diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb
index e839b67960..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,17 +99,17 @@ 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
run_generator
- assert_migration "db/migrate/create_test_app_accounts.rb", /create_table :test_app_accounts/, /class CreateTestAppAccounts < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_test_app_accounts.rb", /create_table :test_app_accounts/, /class CreateTestAppAccounts < ActiveRecord::Migration\[[0-9.]+\]/
end
def test_migration_with_namespace
run_generator ["Gallery::Image"]
- assert_migration "db/migrate/create_test_app_gallery_images", /class CreateTestAppGalleryImages < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_test_app_gallery_images", /class CreateTestAppGalleryImages < ActiveRecord::Migration\[[0-9.]+\]/
assert_no_migration "db/migrate/create_test_app_images"
end
@@ -117,7 +117,7 @@ class NamespacedModelGeneratorTest < NamespacedGeneratorTestCase
run_generator ["Admin::Gallery::Image"]
assert_no_migration "db/migrate/create_images"
assert_no_migration "db/migrate/create_gallery_images"
- assert_migration "db/migrate/create_test_app_admin_gallery_images", /class CreateTestAppAdminGalleryImages < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_test_app_admin_gallery_images", /class CreateTestAppAdminGalleryImages < ActiveRecord::Migration\[[0-9.]+\]/
assert_migration "db/migrate/create_test_app_admin_gallery_images", /create_table :test_app_admin_gallery_images/
end
@@ -127,7 +127,7 @@ class NamespacedModelGeneratorTest < NamespacedGeneratorTestCase
assert_no_migration "db/migrate/create_images"
assert_no_migration "db/migrate/create_gallery_images"
assert_no_migration "db/migrate/create_test_app_admin_gallery_images"
- assert_migration "db/migrate/create_test_app_admin_gallery_image", /class CreateTestAppAdminGalleryImage < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_test_app_admin_gallery_image", /class CreateTestAppAdminGalleryImage < ActiveRecord::Migration\[[0-9.]+\]/
assert_migration "db/migrate/create_test_app_admin_gallery_image", /create_table :test_app_admin_gallery_image/
ensure
ActiveRecord::Base.pluralize_table_names = true
@@ -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"
@@ -218,7 +218,7 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
/class ProductLinesController < ApplicationController/
assert_file "test/controllers/test_app/product_lines_controller_test.rb",
- /module TestApp\n class ProductLinesControllerTest < ActionController::TestCase/
+ /module TestApp\n class ProductLinesControllerTest < ActionDispatch::IntegrationTest/
# Views
%w(index edit new show _form).each do |view|
@@ -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"
@@ -281,10 +281,11 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
# Controller
assert_file "app/controllers/test_app/admin/roles_controller.rb" do |content|
assert_match(/module TestApp\n class Admin::RolesController < ApplicationController/, content)
+ assert_match(%r(require_dependency "test_app/application_controller"), content)
end
assert_file "test/controllers/test_app/admin/roles_controller_test.rb",
- /module TestApp\n class Admin::RolesControllerTest < ActionController::TestCase/
+ /module TestApp\n class Admin::RolesControllerTest < ActionDispatch::IntegrationTest/
# Views
%w(index edit new show _form).each do |view|
@@ -335,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"
@@ -351,7 +352,7 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
end
assert_file "test/controllers/test_app/admin/user/special/roles_controller_test.rb",
- /module TestApp\n class Admin::User::Special::RolesControllerTest < ActionController::TestCase/
+ /module TestApp\n class Admin::User::Special::RolesControllerTest < ActionDispatch::IntegrationTest/
# Views
%w(index edit new show _form).each do |view|
@@ -395,4 +396,28 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
# Stylesheets (should not be removed)
assert_file "app/assets/stylesheets/scaffold.css"
end
+
+ def test_api_scaffold_with_namespace_on_invoke
+ run_generator [ "admin/role", "name:string", "description:string", "--api" ]
+
+ # 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 < 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"
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_match(/^ namespace :admin do\n resources :roles\n end$/, route)
+ end
+
+ # Controller
+ assert_file "app/controllers/test_app/admin/roles_controller.rb" do |content|
+ assert_match(/module TestApp\n class Admin::RolesController < ApplicationController/, content)
+ assert_match(%r(require_dependency "test_app/application_controller"), content)
+ end
+ assert_file "test/controllers/test_app/admin/roles_controller_test.rb",
+ /module TestApp\n class Admin::RolesControllerTest < ActionDispatch::IntegrationTest/
+ end
end
diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb
index d6e5f4bd89..9921a80342 100644
--- a/railties/test/generators/plugin_generator_test.rb
+++ b/railties/test/generators/plugin_generator_test.rb
@@ -1,13 +1,12 @@
-require 'generators/generators_test_helper'
-require 'rails/generators/rails/plugin/plugin_generator'
-require 'generators/shared_generator_tests'
-require 'mocha/setup' # FIXME: stop using mocha
+require "generators/generators_test_helper"
+require "rails/generators/rails/plugin/plugin_generator"
+require "generators/shared_generator_tests"
DEFAULT_PLUGIN_FILES = %w(
.gitignore
Gemfile
Rakefile
- README.rdoc
+ README.md
bukkits.gemspec
MIT-LICENSE
lib
@@ -28,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")] }
- 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, "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
@@ -59,14 +58,18 @@ class PluginGeneratorTest < Rails::Generators::TestCase
def test_generating_without_options
run_generator
- assert_file "README.rdoc", /Bukkits/
+ assert_file "README.md", /Bukkits/
assert_no_file "config/routes.rb"
+ assert_no_file "app/assets/config/bukkits_manifest.js"
assert_file "test/test_helper.rb" do |content|
assert_match(/require.+test\/dummy\/config\/environment/, content)
assert_match(/ActiveRecord::Migrator\.migrations_paths.+test\/dummy\/db\/migrate/, content)
assert_match(/Minitest\.backtrace_filter = Minitest::BacktraceFilter\.new/, content)
+ 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"
end
def test_generating_test_files_in_full_mode
@@ -77,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)
@@ -97,8 +100,16 @@ class PluginGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_generating_adds_dummy_app_in_full_mode_without_sprockets
+ run_generator [destination_root, "-S", "--full"]
+
+ assert_file "test/dummy/config/environments/production.rb" do |contents|
+ assert_no_match(/config\.assets/, contents)
+ end
+ 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
@@ -190,13 +201,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
@@ -222,22 +244,22 @@ class PluginGeneratorTest < Rails::Generators::TestCase
def test_ensure_that_tests_work
run_generator
FileUtils.cd destination_root
- quietly { system 'bundle install' }
- assert_match(/1 runs, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test 2>&1`)
+ 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' }
- output = `bundle exec rake db:migrate 2>&1`
+ quietly { system "bundle install" }
+ output = `bin/rails db:migrate 2>&1`
assert $?.success?, "Command failed: #{output}"
end
@@ -304,6 +326,9 @@ class PluginGeneratorTest < Rails::Generators::TestCase
assert_file "lib/bukkits/engine.rb", /isolate_namespace Bukkits/
assert_file "test/dummy/config/routes.rb", /mount Bukkits::Engine => "\/bukkits"/
assert_file "app/controllers/bukkits/application_controller.rb", /module Bukkits\n class ApplicationController < ActionController::Base/
+ assert_file "app/models/bukkits/application_record.rb", /module Bukkits\n class ApplicationRecord < ActiveRecord::Base/
+ assert_file "app/jobs/bukkits/application_job.rb", /module Bukkits\n class ApplicationJob < ActiveJob::Base/
+ assert_file "app/mailers/bukkits/application_mailer.rb", /module Bukkits\n class ApplicationMailer < ActionMailer::Base\n default from: 'from@example.com'\n layout 'mailer'\n/
assert_file "app/helpers/bukkits/application_helper.rb", /module Bukkits\n module ApplicationHelper/
assert_file "app/views/layouts/bukkits/application.html.erb" do |contents|
assert_match "<title>Bukkits</title>", contents
@@ -313,7 +338,10 @@ class PluginGeneratorTest < Rails::Generators::TestCase
assert_file "test/test_helper.rb" do |content|
assert_match(/ActiveRecord::Migrator\.migrations_paths.+\.\.\/test\/dummy\/db\/migrate/, content)
assert_match(/ActiveRecord::Migrator\.migrations_paths.+<<.+\.\.\/db\/migrate/, content)
+ 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"
end
def test_create_mountable_application_with_mountable_option_and_hypenated_name
@@ -322,11 +350,14 @@ class PluginGeneratorTest < Rails::Generators::TestCase
assert_file "hyphenated-name/app/assets/stylesheets/hyphenated/name"
assert_file "hyphenated-name/app/assets/images/hyphenated/name"
assert_file "hyphenated-name/config/routes.rb", /Hyphenated::Name::Engine.routes.draw do/
- assert_file "hyphenated-name/lib/hyphenated/name/version.rb", /module Hyphenated\n module Name\n VERSION = "0.0.1"\n end\nend/
+ assert_file "hyphenated-name/lib/hyphenated/name/version.rb", /module Hyphenated\n module Name\n VERSION = '0.1.0'\n end\nend/
assert_file "hyphenated-name/lib/hyphenated/name/engine.rb", /module Hyphenated\n module Name\n class Engine < ::Rails::Engine\n isolate_namespace Hyphenated::Name\n end\n end\nend/
assert_file "hyphenated-name/lib/hyphenated/name.rb", /require "hyphenated\/name\/engine"/
assert_file "hyphenated-name/test/dummy/config/routes.rb", /mount Hyphenated::Name::Engine => "\/hyphenated-name"/
- assert_file "hyphenated-name/app/controllers/hyphenated/name/application_controller.rb", /module Hyphenated\n module Name\n class ApplicationController < ActionController::Base\n end\n end\nend/
+ assert_file "hyphenated-name/app/controllers/hyphenated/name/application_controller.rb", /module Hyphenated\n module Name\n class ApplicationController < ActionController::Base\n protect_from_forgery with: :exception\n end\n end\nend\n/
+ assert_file "hyphenated-name/app/models/hyphenated/name/application_record.rb", /module Hyphenated\n module Name\n class ApplicationRecord < ActiveRecord::Base\n self\.abstract_class = true\n end\n end\nend/
+ assert_file "hyphenated-name/app/jobs/hyphenated/name/application_job.rb", /module Hyphenated\n module Name\n class ApplicationJob < ActiveJob::Base/
+ assert_file "hyphenated-name/app/mailers/hyphenated/name/application_mailer.rb", /module Hyphenated\n module Name\n class ApplicationMailer < ActionMailer::Base\n default from: 'from@example.com'\n layout 'mailer'\n end\n end\nend/
assert_file "hyphenated-name/app/helpers/hyphenated/name/application_helper.rb", /module Hyphenated\n module Name\n module ApplicationHelper\n end\n end\nend/
assert_file "hyphenated-name/app/views/layouts/hyphenated/name/application.html.erb" do |contents|
assert_match "<title>Hyphenated name</title>", contents
@@ -341,11 +372,14 @@ class PluginGeneratorTest < Rails::Generators::TestCase
assert_file "my_hyphenated-name/app/assets/stylesheets/my_hyphenated/name"
assert_file "my_hyphenated-name/app/assets/images/my_hyphenated/name"
assert_file "my_hyphenated-name/config/routes.rb", /MyHyphenated::Name::Engine.routes.draw do/
- assert_file "my_hyphenated-name/lib/my_hyphenated/name/version.rb", /module MyHyphenated\n module Name\n VERSION = "0.0.1"\n end\nend/
+ assert_file "my_hyphenated-name/lib/my_hyphenated/name/version.rb", /module MyHyphenated\n module Name\n VERSION = '0.1.0'\n end\nend/
assert_file "my_hyphenated-name/lib/my_hyphenated/name/engine.rb", /module MyHyphenated\n module Name\n class Engine < ::Rails::Engine\n isolate_namespace MyHyphenated::Name\n end\n end\nend/
assert_file "my_hyphenated-name/lib/my_hyphenated/name.rb", /require "my_hyphenated\/name\/engine"/
assert_file "my_hyphenated-name/test/dummy/config/routes.rb", /mount MyHyphenated::Name::Engine => "\/my_hyphenated-name"/
- assert_file "my_hyphenated-name/app/controllers/my_hyphenated/name/application_controller.rb", /module MyHyphenated\n module Name\n class ApplicationController < ActionController::Base\n end\n end\nend/
+ assert_file "my_hyphenated-name/app/controllers/my_hyphenated/name/application_controller.rb", /module MyHyphenated\n module Name\n class ApplicationController < ActionController::Base\n protect_from_forgery with: :exception\n end\n end\nend\n/
+ assert_file "my_hyphenated-name/app/models/my_hyphenated/name/application_record.rb", /module MyHyphenated\n module Name\n class ApplicationRecord < ActiveRecord::Base\n self\.abstract_class = true\n end\n end\nend/
+ assert_file "my_hyphenated-name/app/jobs/my_hyphenated/name/application_job.rb", /module MyHyphenated\n module Name\n class ApplicationJob < ActiveJob::Base/
+ assert_file "my_hyphenated-name/app/mailers/my_hyphenated/name/application_mailer.rb", /module MyHyphenated\n module Name\n class ApplicationMailer < ActionMailer::Base\n default from: 'from@example.com'\n layout 'mailer'\n end\n end\nend/
assert_file "my_hyphenated-name/app/helpers/my_hyphenated/name/application_helper.rb", /module MyHyphenated\n module Name\n module ApplicationHelper\n end\n end\nend/
assert_file "my_hyphenated-name/app/views/layouts/my_hyphenated/name/application.html.erb" do |contents|
assert_match "<title>My hyphenated name</title>", contents
@@ -360,11 +394,14 @@ class PluginGeneratorTest < Rails::Generators::TestCase
assert_file "deep-hyphenated-name/app/assets/stylesheets/deep/hyphenated/name"
assert_file "deep-hyphenated-name/app/assets/images/deep/hyphenated/name"
assert_file "deep-hyphenated-name/config/routes.rb", /Deep::Hyphenated::Name::Engine.routes.draw do/
- assert_file "deep-hyphenated-name/lib/deep/hyphenated/name/version.rb", /module Deep\n module Hyphenated\n module Name\n VERSION = "0.0.1"\n end\n end\nend/
+ assert_file "deep-hyphenated-name/lib/deep/hyphenated/name/version.rb", /module Deep\n module Hyphenated\n module Name\n VERSION = '0.1.0'\n end\n end\nend/
assert_file "deep-hyphenated-name/lib/deep/hyphenated/name/engine.rb", /module Deep\n module Hyphenated\n module Name\n class Engine < ::Rails::Engine\n isolate_namespace Deep::Hyphenated::Name\n end\n end\n end\nend/
assert_file "deep-hyphenated-name/lib/deep/hyphenated/name.rb", /require "deep\/hyphenated\/name\/engine"/
assert_file "deep-hyphenated-name/test/dummy/config/routes.rb", /mount Deep::Hyphenated::Name::Engine => "\/deep-hyphenated-name"/
- assert_file "deep-hyphenated-name/app/controllers/deep/hyphenated/name/application_controller.rb", /module Deep\n module Hyphenated\n module Name\n class ApplicationController < ActionController::Base\n end\n end\n end\nend/
+ assert_file "deep-hyphenated-name/app/controllers/deep/hyphenated/name/application_controller.rb", /module Deep\n module Hyphenated\n module Name\n class ApplicationController < ActionController::Base\n protect_from_forgery with: :exception\n end\n end\n end\nend\n/
+ assert_file "deep-hyphenated-name/app/models/deep/hyphenated/name/application_record.rb", /module Deep\n module Hyphenated\n module Name\n class ApplicationRecord < ActiveRecord::Base\n self\.abstract_class = true\n end\n end\n end\nend/
+ assert_file "deep-hyphenated-name/app/jobs/deep/hyphenated/name/application_job.rb", /module Deep\n module Hyphenated\n module Name\n class ApplicationJob < ActiveJob::Base/
+ assert_file "deep-hyphenated-name/app/mailers/deep/hyphenated/name/application_mailer.rb", /module Deep\n module Hyphenated\n module Name\n class ApplicationMailer < ActionMailer::Base\n default from: 'from@example.com'\n layout 'mailer'\n end\n end\n end\nend/
assert_file "deep-hyphenated-name/app/helpers/deep/hyphenated/name/application_helper.rb", /module Deep\n module Hyphenated\n module Name\n module ApplicationHelper\n end\n end\n end\nend/
assert_file "deep-hyphenated-name/app/views/layouts/deep/hyphenated/name/application.html.erb" do |contents|
assert_match "<title>Deep hyphenated name</title>", contents
@@ -376,8 +413,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase
def test_creating_gemspec
run_generator
assert_file "bukkits.gemspec", /s.name\s+= "bukkits"/
- assert_file "bukkits.gemspec", /s.files = Dir\["\{app,config,db,lib\}\/\*\*\/\*", "MIT-LICENSE", "Rakefile", "README\.rdoc"\]/
- assert_file "bukkits.gemspec", /s.test_files = Dir\["test\/\*\*\/\*"\]/
+ assert_file "bukkits.gemspec", /s.files = Dir\["\{app,config,db,lib\}\/\*\*\/\*", "MIT-LICENSE", "Rakefile", "README\.md"\]/
assert_file "bukkits.gemspec", /s.version\s+ = Bukkits::VERSION/
end
@@ -422,11 +458,19 @@ 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
+ def test_dummy_appplication_skip_listen_by_default
+ run_generator
+
+ assert_file "test/dummy/config/environments/development.rb" do |contents|
+ assert_match(/^\s*# config.file_watcher = ActiveSupport::EventedFileUpdateChecker/, contents)
+ end
+ end
+
def test_ensure_that_gitignore_can_be_generated_from_a_template_for_dummy_path
FileUtils.cd(Rails.root)
run_generator([destination_root, "--dummy_path", "spec/dummy", "--skip-test"])
@@ -435,13 +479,23 @@ class PluginGeneratorTest < Rails::Generators::TestCase
end
end
+ 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"
+ end
+
def test_skipping_test_files
run_generator [destination_root, "--skip-test"]
assert_no_file "test"
- assert_file "bukkits.gemspec" do |contents|
- assert_no_match(/s.test_files = Dir\["test\/\*\*\/\*"\]/, contents)
- end
- assert_file '.gitignore' do |contents|
+ assert_file ".gitignore" do |contents|
assert_no_match(/test\dummy/, contents)
end
end
@@ -450,10 +504,9 @@ 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_match(/gem 'rails', '~> #{Rails.version}'/, contents)
+ assert_no_match("gemspec", contents)
+ assert_match(/gem 'rails'/, contents)
assert_match_sqlite3(contents)
- assert_no_match(/# gem "jquery-rails"/, contents)
end
end
@@ -461,8 +514,8 @@ 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_match(/gem 'rails', '~> #{Rails.version}'/, contents)
+ assert_no_match("gemspec", contents)
+ assert_match(/gem 'rails'/, contents)
assert_match_sqlite3(contents)
end
end
@@ -470,21 +523,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"]
@@ -493,7 +546,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
@@ -534,7 +587,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
@@ -544,20 +597,155 @@ class PluginGeneratorTest < Rails::Generators::TestCase
end
end
-protected
- def action(*args, &block)
- silence(:stdout){ generator.send(*args, &block) }
+ def test_skipping_useless_folders_generation_for_api_engines
+ ["--full", "--mountable"].each do |option|
+ run_generator [destination_root, option, "--api"]
+
+ assert_no_directory "app/assets"
+ assert_no_directory "app/helpers"
+ assert_no_directory "app/views"
+
+ FileUtils.rm_rf destination_root
+ end
+ end
+
+ def test_application_controller_parent_for_mountable_api_plugins
+ run_generator [destination_root, "--mountable", "--api"]
+
+ assert_file "app/controllers/bukkits/application_controller.rb" do |content|
+ assert_match "ApplicationController < ActionController::API", content
+ end
end
- def default_files
- ::DEFAULT_PLUGIN_FILES
+ def test_dummy_api_application_for_api_plugins
+ run_generator [destination_root, "--api"]
+
+ assert_file "test/dummy/config/application.rb" do |content|
+ assert_match "config.api_only = true", content
+ 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)
+ def test_api_generators_configuration_for_api_engines
+ run_generator [destination_root, "--full", "--api"]
+
+ assert_file "lib/bukkits/engine.rb" do |content|
+ assert_match "config.generators.api_only = true", content
+ end
+ end
+
+ def test_scaffold_generator_for_mountable_api_plugins
+ run_generator [destination_root, "--mountable", "--api"]
+
+ capture(:stdout) do
+ `#{destination_root}/bin/rails g scaffold article`
+ end
+
+ assert_file "app/models/bukkits/article.rb"
+ assert_file "app/controllers/bukkits/articles_controller.rb" do |content|
+ assert_match "only: [:show, :update, :destroy]", content
+ end
+
+ assert_no_directory "app/assets"
+ assert_no_directory "app/helpers"
+ assert_no_directory "app/views"
+ end
+
+ def test_model_with_existent_application_record_in_mountable_engine
+ run_generator [destination_root, "--mountable"]
+ capture(:stdout) do
+ `#{destination_root}/bin/rails g model article`
+ end
+
+ assert_file "app/models/bukkits/article.rb", /class Article < ApplicationRecord/
+ end
+
+ def test_generate_application_record_when_does_not_exist_in_mountable_engine
+ 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`
+ end
+
+ assert_file "#{destination_root}/app/models/bukkits/application_record.rb" do |record|
+ assert_match(/module Bukkits/, record)
+ assert_match(/class ApplicationRecord < ActiveRecord::Base/, record)
+ assert_match(/self.abstract_class = true/, record)
+ end
+ end
+
+ def test_generate_application_mailer_when_does_not_exist_in_mountable_engine
+ 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`
+ end
+
+ assert_file "#{destination_root}/app/mailers/bukkits/application_mailer.rb" do |mailer|
+ assert_match(/module Bukkits/, mailer)
+ assert_match(/class ApplicationMailer < ActionMailer::Base/, mailer)
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"]
+ FileUtils.rm "#{destination_root}/app/jobs/bukkits/application_job.rb"
+ capture(:stdout) do
+ `#{destination_root}/bin/rails g job refresh_counters`
+ end
+
+ assert_file "#{destination_root}/app/jobs/bukkits/application_job.rb" do |record|
+ assert_match(/module Bukkits/, record)
+ assert_match(/class ApplicationJob < ActiveJob::Base/, record)
+ end
+ end
+
+ private
+
+ def action(*args, &block)
+ silence(:stdout) { generator.send(*args, &block) }
+ end
+
+ def default_files
+ ::DEFAULT_PLUGIN_FILES
+ 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
+
+ def assert_generates_without_bundler(options = {})
+ generator([destination_root], options)
+
+ 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
+
+ generator.stub :bundle_command, command_check do
+ quietly { generator.invoke_all }
+ end
+ end
end
diff --git a/railties/test/generators/plugin_test_helper.rb b/railties/test/generators/plugin_test_helper.rb
new file mode 100644
index 0000000000..8ac90e3484
--- /dev/null
+++ b/railties/test/generators/plugin_test_helper.rb
@@ -0,0 +1,24 @@
+require "abstract_unit"
+require "tmpdir"
+
+module PluginTestHelper
+ def create_test_file(name, pass: true)
+ plugin_file "test/#{name}_test.rb", <<-RUBY
+ require 'test_helper'
+
+ class #{name.camelize}Test < ActiveSupport::TestCase
+ def test_truth
+ puts "#{name.camelize}Test"
+ assert #{pass}, 'wups!'
+ end
+ end
+ RUBY
+ end
+
+ 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
+ end
+ end
+end
diff --git a/railties/test/generators/plugin_test_runner_test.rb b/railties/test/generators/plugin_test_runner_test.rb
new file mode 100644
index 0000000000..0bdf3b2726
--- /dev/null
+++ b/railties/test/generators/plugin_test_runner_test.rb
@@ -0,0 +1,103 @@
+require "generators/plugin_test_helper"
+
+class PluginTestRunnerTest < ActiveSupport::TestCase
+ include PluginTestHelper
+
+ def setup
+ @destination_root = Dir.mktmpdir("bukkits")
+ Dir.chdir(@destination_root) { `bundle exec rails plugin new bukkits --skip-bundle` }
+ plugin_file "test/dummy/db/schema.rb", ""
+ end
+
+ def teardown
+ FileUtils.rm_rf(@destination_root)
+ end
+
+ def test_run_single_file
+ 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"
+ 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
+ require 'test_helper'
+
+ class PostTest < ActiveSupport::TestCase
+ def test_post
+ puts 'PostTest'
+ assert true
+ end
+
+ def test_line_filter_does_not_run_this
+ assert true
+ end
+ 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
+ end
+ end
+
+ def test_multiple_line_filters
+ 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
+ end
+ end
+
+ def test_output_inline_by_default
+ create_test_file "post", pass: false
+
+ 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
+
+ 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
+
+ assert_match(/Interrupt/,
+ 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") }
+ 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"
+ end
+
+ def run_test_command(arguments)
+ Dir.chdir(plugin_path) { `bin/test #{arguments}` }
+ end
+end
diff --git a/railties/test/generators/resource_generator_test.rb b/railties/test/generators/resource_generator_test.rb
index 581d80d60e..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
@@ -33,7 +33,7 @@ class ResourceGeneratorTest < Rails::Generators::TestCase
def test_resource_controller_with_pluralized_class_name
run_generator
assert_file "app/controllers/accounts_controller.rb", /class AccountsController < ApplicationController/
- assert_file "test/controllers/accounts_controller_test.rb", /class AccountsControllerTest < ActionController::TestCase/
+ assert_file "test/controllers/accounts_controller_test.rb", /class AccountsControllerTest < ActionDispatch::IntegrationTest/
assert_file "app/helpers/accounts_helper.rb", /module AccountsHelper/
end
@@ -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 648b8d9325..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
@@ -56,7 +56,7 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
assert_file "app/controllers/users_controller.rb" do |content|
assert_match(/def user_params/, content)
- assert_match(/params\[:user\]/, content)
+ assert_match(/params\.fetch\(:user, \{\}\)/, content)
end
end
@@ -104,10 +104,10 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
run_generator ["User", "name:string", "age:integer", "organization:references{polymorphic}"]
assert_file "test/controllers/users_controller_test.rb" do |content|
- assert_match(/class UsersControllerTest < ActionController::TestCase/, content)
+ assert_match(/class UsersControllerTest < ActionDispatch::IntegrationTest/, content)
assert_match(/test "should get index"/, content)
- assert_match(/post :create, params: \{ user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}/, content)
- assert_match(/patch :update, params: \{ id: @user, 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 \} \}/, 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)
end
end
@@ -115,10 +115,10 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
run_generator ["User"]
assert_file "test/controllers/users_controller_test.rb" do |content|
- assert_match(/class UsersControllerTest < ActionController::TestCase/, content)
+ assert_match(/class UsersControllerTest < ActionDispatch::IntegrationTest/, content)
assert_match(/test "should get index"/, content)
- assert_match(/post :create, params: \{ user: \{ \} \}/, content)
- assert_match(/patch :update, params: \{ id: @user, user: \{ \} \}/, content)
+ assert_match(/post users_url, params: \{ user: \{ \} \}/, content)
+ assert_match(/patch user_url\(@user\), params: \{ user: \{ \} \}/, content)
end
end
@@ -182,7 +182,7 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
Dir.chdir(engine_path) do
quietly { `bin/rails g controller dashboard foo` }
- assert_match(/2 runs, 2 assertions, 0 failures, 0 errors/, `bundle exec rake test 2>&1`)
+ assert_match(/2 runs, 2 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`)
end
end
@@ -193,7 +193,7 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
Dir.chdir(engine_path) do
quietly { `bin/rails g controller dashboard foo` }
- assert_match(/2 runs, 2 assertions, 0 failures, 0 errors/, `bundle exec rake test 2>&1`)
+ assert_match(/2 runs, 2 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`)
end
end
@@ -236,10 +236,10 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
run_generator ["User", "name:string", "age:integer", "organization:references{polymorphic}", "--api"]
assert_file "test/controllers/users_controller_test.rb" do |content|
- assert_match(/class UsersControllerTest < ActionController::TestCase/, content)
+ assert_match(/class UsersControllerTest < ActionDispatch::IntegrationTest/, content)
assert_match(/test "should get index"/, content)
- assert_match(/post :create, params: \{ user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}/, content)
- assert_match(/patch :update, params: \{ id: @user, 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 debf1140ab..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,11 +11,11 @@ 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, index: true/
- assert_migration "db/migrate/create_product_lines.rb", /references :user, index: true/
+ assert_migration "db/migrate/create_product_lines.rb", /belongs_to :product/
+ assert_migration "db/migrate/create_product_lines.rb", /references :user/
# Route
assert_file "config/routes.rb" do |route|
@@ -57,9 +57,9 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
end
assert_file "test/controllers/product_lines_controller_test.rb" do |test|
- assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, test)
- assert_match(/post :create, params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
- assert_match(/patch :update, params: \{ id: @product_line, product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
+ assert_match(/class ProductLinesControllerTest < ActionDispatch::IntegrationTest/, test)
+ assert_match(/post product_lines_url, params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
+ assert_match(/patch product_line_url\(@product_line\), params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
end
# Views
@@ -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,11 +91,11 @@ 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, index: true/
- assert_migration "db/migrate/create_product_lines.rb", /references :user, index: true/
+ assert_migration "db/migrate/create_product_lines.rb", /belongs_to :product/
+ assert_migration "db/migrate/create_product_lines.rb", /references :user/
# Route
assert_file "config/routes.rb" do |route|
@@ -135,9 +135,9 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
end
assert_file "test/controllers/product_lines_controller_test.rb" do |test|
- assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, test)
- assert_match(/post :create, params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
- assert_match(/patch :update, params: \{ id: @product_line, product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
+ assert_match(/class ProductLinesControllerTest < ActionDispatch::IntegrationTest/, test)
+ assert_match(/post product_lines_url, params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
+ assert_match(/patch product_line_url\(@product_line\), params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
assert_no_match(/assert_redirected_to/, test)
end
@@ -161,10 +161,10 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
run_generator ["product_line"]
assert_file "test/controllers/product_lines_controller_test.rb" do |content|
- assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, content)
+ assert_match(/class ProductLinesControllerTest < ActionDispatch::IntegrationTest/, content)
assert_match(/test "should get index"/, content)
- assert_match(/post :create, params: \{ product_line: \{ \} \}/, content)
- assert_match(/patch :update, params: \{ id: @product_line, product_line: \{ \} \}/, content)
+ assert_match(/post product_lines_url, params: \{ product_line: \{ \} \}/, content)
+ assert_match(/patch product_line_url\(@product_line\), params: \{ product_line: \{ \} \}/, content)
end
end
@@ -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"
@@ -250,7 +250,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
end
assert_file "test/controllers/admin/roles_controller_test.rb",
- /class Admin::RolesControllerTest < ActionController::TestCase/
+ /class Admin::RolesControllerTest < ActionDispatch::IntegrationTest/
# Views
%w(index edit new show _form).each do |view|
@@ -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
@@ -486,9 +486,9 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
Dir.chdir(engine_path) do
quietly do
`bin/rails g scaffold User name:string age:integer;
- bundle exec rake db:migrate`
+ bin/rails db:migrate`
end
- assert_match(/8 runs, 13 assertions, 0 failures, 0 errors/, `bundle exec rake test 2>&1`)
+ assert_match(/8 runs, 10 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`)
end
end
@@ -500,9 +500,37 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
Dir.chdir(engine_path) do
quietly do
`bin/rails g scaffold User name:string age:integer;
- bundle exec rake db:migrate`
+ bin/rails db:migrate`
+ end
+ assert_match(/8 runs, 10 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`)
+ end
+ end
+
+ def test_scaffold_tests_pass_by_default_inside_api_mountable_engine
+ Dir.chdir(destination_root) { `bundle exec rails plugin new bukkits --mountable --api` }
+
+ engine_path = File.join(destination_root, "bukkits")
+
+ Dir.chdir(engine_path) do
+ quietly do
+ `bin/rails g scaffold User name:string age:integer;
+ bin/rails db:migrate`
+ end
+ assert_match(/6 runs, 8 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`)
+ end
+ end
+
+ def test_scaffold_tests_pass_by_default_inside_api_full_engine
+ Dir.chdir(destination_root) { `bundle exec rails plugin new bukkits --full --api` }
+
+ engine_path = File.join(destination_root, "bukkits")
+
+ Dir.chdir(engine_path) do
+ quietly do
+ `bin/rails g scaffold User name:string age:integer;
+ bin/rails db:migrate`
end
- assert_match(/8 runs, 13 assertions, 0 failures, 0 errors/, `bundle exec rake test 2>&1`)
+ assert_match(/6 runs, 8 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`)
end
end
end
diff --git a/railties/test/generators/shared_generator_tests.rb b/railties/test/generators/shared_generator_tests.rb
index f983b45d2b..08b0e34fe2 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,24 +26,13 @@ module SharedGeneratorTests
default_files.each { |path| assert_file path }
end
- def assert_generates_with_bundler(options = {})
- generator([destination_root], options)
- generator.expects(:bundle_command).with('install').once
- generator.stubs(:bundle_command).with('exec spring binstub --all')
- quietly { generator.invoke_all }
- 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
@@ -55,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)] }
- 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)
+ 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
@@ -79,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)
@@ -91,49 +80,44 @@ module SharedGeneratorTests
template = %{ say "It works!" }
template.instance_eval "def read; self; end" # Make the string respond to read
- generator([destination_root], template: path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
- quietly { assert_match(/It works!/, capture(:stdout) { generator.invoke_all }) }
- 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
+ check_open = -> *args do
+ assert_equal [ path, "Accept" => "application/x-thor-template" ], args
+ template
+ 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")}["']$}
+ generator([destination_root], template: path).stub(:open, check_open, template) do
+ quietly { assert_match(/It works!/, capture(:stdout) { generator.invoke_all }) }
+ end
end
def test_skip_gemfile
- generator([destination_root], skip_gemfile: true).expects(:bundle_command).never
- quietly { generator.invoke_all }
- assert_no_file 'Gemfile'
+ assert_not_called(generator([destination_root], skip_gemfile: true), :bundle_command) do
+ quietly { generator.invoke_all }
+ assert_no_file "Gemfile"
+ end
end
def test_skip_bundle
- generator([destination_root], skip_bundle: true).expects(:bundle_command).never
- quietly { generator.invoke_all }
-
- # skip_bundle is only about running bundle install, ensure the Gemfile is still
- # generated.
- assert_file 'Gemfile'
+ assert_not_called(generator([destination_root], skip_bundle: true), :bundle_command) do
+ quietly { generator.invoke_all }
+ # skip_bundle is only about running bundle install, ensure the Gemfile is still
+ # generated.
+ assert_file "Gemfile"
+ end
end
def test_skip_git
- run_generator [destination_root, '--skip-git', '--full']
- assert_no_file('.gitignore')
- assert_file('app/mailers/.keep')
+ 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/mailers/.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
new file mode 100644
index 0000000000..4b5fb3ba3f
--- /dev/null
+++ b/railties/test/generators/test_runner_in_engine_test.rb
@@ -0,0 +1,32 @@
+require "generators/plugin_test_helper"
+
+class TestRunnerInEngineTest < ActiveSupport::TestCase
+ include PluginTestHelper
+
+ def setup
+ @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", ""
+ end
+
+ def teardown
+ FileUtils.rm_rf(@destination_root)
+ end
+
+ def test_rerun_snippet_is_relative_path
+ create_test_file "post", pass: false
+
+ 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
+
+ private
+ def plugin_path
+ "#{@destination_root}/bukkits"
+ end
+
+ def run_test_command(arguments)
+ Dir.chdir(plugin_path) { `bin/rails test #{arguments}` }
+ end
+end
diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb
index 31a575749a..68ba435393 100644
--- a/railties/test/generators_test.rb
+++ b/railties/test/generators_test.rb
@@ -1,7 +1,6 @@
-require 'generators/generators_test_helper'
-require 'rails/generators/rails/model/model_generator'
-require 'rails/generators/test_unit/model/model_generator'
-require 'minitest/mock'
+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
@@ -9,65 +8,59 @@ class GeneratorsTest < Rails::Generators::TestCase
def setup
@path = File.expand_path("lib", Rails.root)
$LOAD_PATH.unshift(@path)
- @mock_generator = MiniTest::Mock.new
end
def teardown
$LOAD_PATH.delete(@path)
- @mock_generator.verify
end
def test_simple_invoke
- assert File.exist?(File.join(@path, 'generators', 'model_generator.rb'))
- @mock_generator.expect(:call, nil, [["Account"],{}])
- TestUnit::Generators::ModelGenerator.stub(:start, @mock_generator) do
+ 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
end
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'))
- @mock_generator.expect(:call, nil, [["Account"],{}])
- Rails::Generators::ModelGenerator.stub(:start, @mock_generator) do
- warnings = capture(:stderr){ Rails::Generators.invoke :model, ["Account"] }
+ 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"] }
assert warnings.empty?
end
end
def test_invoke_with_default_values
- @mock_generator.expect(:call, nil, [["Account"],{}])
- Rails::Generators::ModelGenerator.stub(:start, @mock_generator) do
+ assert_called_with(Rails::Generators::ModelGenerator, :start, [["Account"], {}]) do
Rails::Generators.invoke :model, ["Account"]
end
end
def test_invoke_with_config_values
- @mock_generator.expect(:call, nil, [["Account"],{behavior: :skip}])
- Rails::Generators::ModelGenerator.stub(:start, @mock_generator) do
+ assert_called_with(Rails::Generators::ModelGenerator, :start, [["Account"], behavior: :skip]) do
Rails::Generators.invoke :model, ["Account"], behavior: :skip
end
end
@@ -115,15 +108,14 @@ class GeneratorsTest < Rails::Generators::TestCase
def test_invoke_with_nested_namespaces
model_generator = Minitest::Mock.new
model_generator.expect(:start, nil, [["Account"], {}])
- @mock_generator.expect(:call, model_generator, ['namespace', 'my:awesome'])
- Rails::Generators.stub(:find_by_namespace, @mock_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)
@@ -131,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
@@ -185,8 +177,7 @@ class GeneratorsTest < Rails::Generators::TestCase
def test_fallbacks_for_generators_on_invoke
Rails::Generators.fallbacks[:shoulda] = :test_unit
- @mock_generator.expect(:call, nil, [["Account"],{}])
- TestUnit::Generators::ModelGenerator.stub(:start, @mock_generator) do
+ assert_called_with(TestUnit::Generators::ModelGenerator, :start, [["Account"], {}]) do
Rails::Generators.invoke "shoulda:model", ["Account"]
end
ensure
@@ -196,8 +187,7 @@ class GeneratorsTest < Rails::Generators::TestCase
def test_nested_fallbacks_for_generators
Rails::Generators.fallbacks[:shoulda] = :test_unit
Rails::Generators.fallbacks[:super_shoulda] = :shoulda
- @mock_generator.expect(:call, nil, [["Account"],{}])
- TestUnit::Generators::ModelGenerator.stub(:start, @mock_generator) do
+ assert_called_with(TestUnit::Generators::ModelGenerator, :start, [["Account"], {}]) do
Rails::Generators.invoke "super_shoulda:model", ["Account"]
end
ensure
@@ -224,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
@@ -239,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 65d8a55421..1902eac862 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)
@@ -51,7 +52,12 @@ module TestHelpers
old_env = ENV["RAILS_ENV"]
@app ||= begin
ENV["RAILS_ENV"] = env
- require "#{app_path}/config/environment"
+
+ # FIXME: shush Sass warning spam, not relevant to testing Railties
+ Kernel.silence_warnings do
+ require "#{app_path}/config/environment"
+ end
+
Rails.application
end
ensure
@@ -60,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
@@ -69,10 +75,12 @@ module TestHelpers
end
def assert_welcome(resp)
+ 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 extract_body(resp).match(/Welcome aboard/)
+ 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
def assert_success(resp)
@@ -95,29 +103,24 @@ 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|
- f.puts $` + "\nmatch ':controller(/:action(/:id))(.:format)', via: :all\n" + $1
+ 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
@@ -150,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.
@@ -160,22 +163,22 @@ module TestHelpers
require "action_controller/railtie"
require "action_view/railtie"
- app = Class.new(Rails::Application)
- app.config.eager_load = false
- app.secrets.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4"
- app.config.session_store :cookie_store, key: "_myapp_session"
- app.config.active_support.deprecation = :log
- app.config.active_support.test_order = :random
- app.config.log_level = :info
+ @app = Class.new(Rails::Application)
+ @app.config.eager_load = false
+ @app.secrets.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4"
+ @app.config.session_store :cookie_store, key: "_myapp_session"
+ @app.config.active_support.deprecation = :log
+ @app.config.active_support.test_order = :random
+ @app.config.log_level = :info
- yield app if block_given?
- app.initialize!
+ yield @app if block_given?
+ @app.initialize!
- app.routes.draw do
+ @app.routes.draw do
get "/" => "omg#index"
end
- require 'rack/test'
+ require "rack/test"
extend ::Rack::Test::Methods
end
@@ -183,12 +186,12 @@ module TestHelpers
controller :foo, <<-RUBY
class FooController < ApplicationController
def index
- render text: "foo"
+ render plain: "foo"
end
end
RUBY
- app_file 'config/routes.rb', <<-RUBY
+ app_file "config/routes.rb", <<-RUBY
Rails.application.routes.draw do
get ':controller(/:action)'
end
@@ -205,7 +208,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)
@@ -221,7 +224,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
@@ -239,7 +242,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
@@ -248,7 +251,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
@@ -257,20 +260,27 @@ 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
end
def remove_from_config(str)
- file = "#{app_path}/config/application.rb"
+ remove_from_file("#{app_path}/config/application.rb", str)
+ end
+
+ def remove_from_env_config(env, str)
+ remove_from_file("#{app_path}/config/environments/#{env}.rb", str)
+ end
+
+ def remove_from_file(file, str)
contents = File.read(file)
contents.sub!(/#{str}/, "")
- File.open(file, "w+") { |f| f.puts contents }
+ 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
@@ -289,14 +299,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
- require File.expand_path('../../../../load_paths', __FILE__)
+ $:.reject! { |path| path =~ %r'/(#{to_remove.join('|')})/' }
end
end
end
@@ -308,7 +314,6 @@ class ActiveSupport::TestCase
include ActiveSupport::Testing::Stream
self.test_order = :sorted
-
end
# Create a scope and build a fixture rails app
@@ -319,12 +324,8 @@ Module.new do
FileUtils.rm_rf(app_template_path)
FileUtils.mkdir(app_template_path)
- environment = File.expand_path('../../../../load_paths', __FILE__)
- require_environment = "-r #{environment}"
-
- `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/exe/rails new #{app_template_path} --skip-gemfile --no-rc`
- File.open("#{app_template_path}/config/boot.rb", 'w') do |f|
- f.puts "require '#{environment}'"
+ `#{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|
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 27e64b97b7..c0b03d0c15 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
@@ -11,26 +11,26 @@ class PathGenerationTest < ActiveSupport::TestCase
super()
end
- class Dispatcher < ActionDispatch::Routing::RouteSet::Dispatcher
- def initialize(defaults, set, block)
- super(defaults)
+ class Request < DelegateClass(ActionDispatch::Request)
+ def initialize(target, url_helpers, block)
+ super(target)
+ @url_helpers = url_helpers
@block = block
- @set = set
end
- def controller_reference(controller_param)
+ def controller_class
+ url_helpers = @url_helpers
block = @block
- set = @set
Class.new(ActionController::Base) {
- include set.url_helpers
+ include url_helpers
define_method(:process) { |name| block.call(self) }
def to_a; [200, {}, []]; end
}
end
end
- def dispatcher defaults
- TestSet::Dispatcher.new defaults, self, @block
+ def make_request(env)
+ 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 12630e4d01..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
@@ -62,6 +62,13 @@ class PathsTest < ActiveSupport::TestCase
assert_equal ["/foo/bar/baz"], @root["app/models"].to_a
end
+ test "absolute current path" do
+ @root.add "config"
+ @root.add "config/locales"
+
+ assert_equal "/foo/bar/config/locales", @root["config/locales"].absolute_current
+ end
+
test "adding multiple physical paths as an array" do
@root.add "app", with: ["/app", "/app2"]
assert_equal ["/app", "/app2"], @root["app"].to_a
@@ -96,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
@@ -107,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
@@ -122,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
@@ -132,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
@@ -150,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
@@ -161,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
@@ -176,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
@@ -186,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
@@ -196,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
@@ -215,6 +222,12 @@ class PathsTest < ActiveSupport::TestCase
assert_equal "*.rb", @root["app"].glob
end
+ test "it should be possible to get extensions by glob" do
+ @root["app"] = "/app"
+ @root["app"].glob = "*.{rb,yml}"
+ assert_equal ["rb", "yml"], @root["app"].extensions
+ end
+
test "it should be possible to override a path's default glob without assignment" do
@root.add "app", with: "/app", glob: "*.rb"
assert_equal "*.rb", @root["app"].glob
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..9f4c5bb025 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,50 +11,50 @@ 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
- protected
+ private
def properties
Rails::Info.properties
end
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index 79bd7a8241..52d691b73b 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
@@ -63,22 +59,22 @@ module RailtiesTest
test "copying migrations" do
@plugin.write "db/migrate/1_create_users.rb", <<-RUBY
- class CreateUsers < ActiveRecord::Migration
+ class CreateUsers < ActiveRecord::Migration::Current
end
RUBY
@plugin.write "db/migrate/2_add_last_name_to_users.rb", <<-RUBY
- class AddLastNameToUsers < ActiveRecord::Migration
+ class AddLastNameToUsers < ActiveRecord::Migration::Current
end
RUBY
@plugin.write "db/migrate/3_create_sessions.rb", <<-RUBY
- class CreateSessions < ActiveRecord::Migration
+ class CreateSessions < ActiveRecord::Migration::Current
end
RUBY
app_file "db/migrate/1_create_sessions.rb", <<-RUBY
- class CreateSessions < ActiveRecord::Migration
+ class CreateSessions < ActiveRecord::Migration::Current
def up
end
end
@@ -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
@@ -123,12 +119,12 @@ module RailtiesTest
end
@plugin.write "db/migrate/1_create_users.rb", <<-RUBY
- class CreateUsers < ActiveRecord::Migration
+ class CreateUsers < ActiveRecord::Migration::Current
end
RUBY
@blog.write "db/migrate/2_create_blogs.rb", <<-RUBY
- class CreateBlogs < ActiveRecord::Migration
+ class CreateBlogs < ActiveRecord::Migration::Current
end
RUBY
@@ -137,7 +133,7 @@ module RailtiesTest
boot_rails
Dir.chdir(app_path) do
- output = `bundle exec rake railties:install:migrations`.split("\n")
+ output = `bundle exec rake railties:install:migrations`.split("\n")
assert_match(/Copied migration \d+_create_users.bukkits.rb from bukkits/, output.first)
assert_match(/Copied migration \d+_create_blogs.blog_engine.rb from blog_engine/, output.last)
@@ -163,17 +159,17 @@ module RailtiesTest
end
@core.write "db/migrate/1_create_users.rb", <<-RUBY
- class CreateUsers < ActiveRecord::Migration; end
+ class CreateUsers < ActiveRecord::Migration::Current; end
RUBY
@api.write "db/migrate/2_create_keys.rb", <<-RUBY
- class CreateKeys < ActiveRecord::Migration; end
+ class CreateKeys < ActiveRecord::Migration::Current; end
RUBY
boot_rails
Dir.chdir(app_path) do
- output = `bundle exec rake railties:install:migrations`.split("\n")
+ output = `bundle exec rake railties:install:migrations`.split("\n")
assert_match(/Copied migration \d+_create_users.core_engine.rb from core_engine/, output.first)
assert_match(/Copied migration \d+_create_keys.api_engine.rb from api_engine/, output.last)
@@ -190,7 +186,7 @@ module RailtiesTest
RUBY
@plugin.write "db/migrate/0_add_first_name_to_users.rb", <<-RUBY
- class AddFirstNameToUsers < ActiveRecord::Migration
+ class AddFirstNameToUsers < ActiveRecord::Migration::Current
end
RUBY
@@ -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
@@ -333,7 +327,7 @@ module RailtiesTest
controller "foo", <<-RUBY
class FooController < ActionController::Base
def index
- render :text => "foo"
+ render plain: "foo"
end
end
RUBY
@@ -347,7 +341,7 @@ module RailtiesTest
@plugin.write "app/controllers/bar_controller.rb", <<-RUBY
class BarController < ActionController::Base
def index
- render :text => "bar"
+ render plain: "bar"
end
end
RUBY
@@ -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
@@ -444,14 +436,12 @@ YAML
@plugin.write "app/controllers/admin/foo/bar_controller.rb", <<-RUBY
class Admin::Foo::BarController < ApplicationController
def index
- render text: "Rendered from namespace"
+ render plain: "Rendered from namespace"
end
end
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
@@ -546,7 +536,7 @@ YAML
controller "foo", <<-RUBY
class FooController < ActionController::Base
def index
- render text: params[:username]
+ render plain: params[:username]
end
end
RUBY
@@ -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
@@ -710,7 +700,7 @@ YAML
end
def show
- render text: foo_path
+ render plain: foo_path
end
def from_app
@@ -722,7 +712,7 @@ YAML
end
def polymorphic_path_without_namespace
- render text: polymorphic_path(Post.new)
+ render plain: polymorphic_path(Post.new)
end
end
RUBY
@@ -845,7 +835,7 @@ YAML
@plugin.write "app/controllers/bukkits/awesome/foo_controller.rb", <<-RUBY
class Bukkits::Awesome::FooController < ActionController::Base
def index
- render :text => "ok"
+ render plain: "ok"
end
end
RUBY
@@ -900,7 +890,7 @@ YAML
boot_rails
- assert_equal AppTemplate.railtie_namespace, AppTemplate::Engine
+ assert_equal AppTemplate::Engine, AppTemplate.railtie_namespace
end
test "properly reload routes" 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)
@@ -1205,7 +1195,7 @@ YAML
test "engine can be properly mounted at root" do
add_to_config("config.action_dispatch.show_exceptions = false")
- add_to_config("config.serve_static_files = false")
+ add_to_config("config.public_file_server.enabled = false")
@plugin.write "lib/bukkits.rb", <<-RUBY
module Bukkits
@@ -1230,13 +1220,12 @@ YAML
fullpath: \#{request.fullpath}
path: \#{request.path}
TEXT
- render text: text
+ render plain: text
end
end
end
RUBY
-
app_file "config/routes.rb", <<-RUBY
Rails.application.routes.draw do
mount Bukkits::Engine => "/"
@@ -1268,7 +1257,7 @@ YAML
app_file "app/controllers/bar_controller.rb", <<-RUBY
class BarController < ApplicationController
def index
- render text: bukkits.bukkit_path
+ render plain: bukkits.bukkit_path
end
end
RUBY
@@ -1286,22 +1275,70 @@ YAML
end
RUBY
+ @plugin.write "app/controllers/bukkits/bukkit_controller.rb", <<-RUBY
+ class Bukkits::BukkitController < ActionController::Base
+ def index
+ render plain: main_app.bar_path
+ end
+ end
+ RUBY
+
+ boot_rails
+
+ 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
+ end
+
+ test "paths are properly generated when application is mounted at sub-path and relative_url_root is set" do
+ add_to_config "config.relative_url_root = '/foo'"
+
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace Bukkits
+ end
+ end
+ RUBY
+
+ app_file "app/controllers/bar_controller.rb", <<-RUBY
+ class BarController < ApplicationController
+ def index
+ render plain: bukkits.bukkit_path
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ get '/bar' => 'bar#index', :as => 'bar'
+ mount Bukkits::Engine => "/bukkits", :as => "bukkits"
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ get '/bukkit' => 'bukkit#index'
+ end
+ RUBY
@plugin.write "app/controllers/bukkits/bukkit_controller.rb", <<-RUBY
class Bukkits::BukkitController < ActionController::Base
def index
- render text: main_app.bar_path
+ render plain: main_app.bar_path
end
end
RUBY
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 5f4171d44b..5c691b9ec4 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)
@@ -26,14 +26,10 @@ module RailtiesTests
end
def rails(cmd)
- environment = File.expand_path('../../../../load_paths', __FILE__)
- if File.exist?("#{environment}.rb")
- require_environment = "-r #{environment}"
- end
- `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/exe/rails #{cmd}`
+ `#{Gem.ruby} #{RAILS_FRAMEWORK_ROOT}/railties/exe/rails #{cmd}`
end
- def build_engine(is_mountable=false)
+ def build_engine(is_mountable = false)
FileUtils.rm_rf(engine_path)
FileUtils.mkdir_p(engine_path)
@@ -43,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..5838d0d7e7 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
@@ -51,7 +50,7 @@ module ApplicationTests
@simple_plugin.write "app/controllers/weblogs_controller.rb", <<-RUBY
class WeblogsController < ActionController::Base
def index
- render text: request.url
+ render plain: request.url
end
end
RUBY
@@ -75,7 +74,7 @@ module ApplicationTests
module Metrics
class GeneratingController < ActionController::Base
def generate_blog_route
- render text: blog.post_path(1)
+ render plain: blog.post_path(1)
end
def generate_blog_route_in_view
@@ -123,14 +122,14 @@ module ApplicationTests
module Blog
class PostsController < ActionController::Base
def index
- render text: blog.post_path(1)
+ render plain: blog.post_path(1)
end
def generate_application_route
path = main_app.url_for(controller: "/main",
action: "index",
only_path: true)
- render text: path
+ render plain: path
end
def application_route_in_view
@@ -138,7 +137,7 @@ module ApplicationTests
end
def engine_polymorphic_path
- render text: polymorphic_path(Post.new)
+ render plain: polymorphic_path(Post.new)
end
def engine_asset_path
@@ -151,7 +150,7 @@ module ApplicationTests
app_file "app/controllers/application_generating_controller.rb", <<-RUBY
class ApplicationGeneratingController < ActionController::Base
def engine_route
- render text: blog.posts_path
+ render plain: blog.posts_path
end
def engine_route_in_view
@@ -159,7 +158,7 @@ module ApplicationTests
end
def weblog_engine_route
- render text: weblog.weblogs_path
+ render plain: weblog.weblogs_path
end
def weblog_engine_route_in_view
@@ -167,20 +166,18 @@ module ApplicationTests
end
def url_for_engine_route
- render text: blog.url_for(controller: "blog/posts", action: "index", user: "john", only_path: true)
+ render plain: blog.url_for(controller: "blog/posts", action: "index", user: "john", only_path: true)
end
def polymorphic_route
- render text: polymorphic_url([blog, Blog::Post.new])
+ render plain: polymorphic_url([blog, Blog::Post.new])
end
def application_polymorphic_path
- render text: polymorphic_path(Blog::Post.new)
+ render plain: polymorphic_path(Blog::Post.new)
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 3066ba82d6..e22c939981 100644
--- a/railties/test/test_unit/reporter_test.rb
+++ b/railties/test/test_unit/reporter_test.rb
@@ -1,5 +1,6 @@
-require 'abstract_unit'
-require 'rails/test_unit/reporter'
+require "abstract_unit"
+require "rails/test_unit/reporter"
+require "minitest/mock"
class TestUnitReporterTest < ActiveSupport::TestCase
class ExampleTest < Minitest::Test
@@ -8,14 +9,14 @@ class TestUnitReporterTest < ActiveSupport::TestCase
setup do
@output = StringIO.new
- @reporter = Rails::TestUnitReporter.new @output
+ @reporter = Rails::TestUnitReporter.new @output, output_inline: true
end
test "prints rerun snippet to run a single failed test" do
@reporter.record(failed_test)
@reporter.report
- assert_match %r{^bin/rails test .*test/test_unit/reporter_test.rb:6$}, @output.string
+ assert_match %r{^bin/rails test .*test/test_unit/reporter_test.rb:\d+$}, @output.string
assert_rerun_snippet_count 1
end
@@ -32,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
@@ -51,38 +52,142 @@ class TestUnitReporterTest < ActiveSupport::TestCase
@reporter.record(failed_test)
@reporter.report
- assert_match %r{^bin/test .*test/test_unit/reporter_test.rb:6$}, @output.string
+ assert_match %r{^bin/test .*test/test_unit/reporter_test.rb:\d+$}, @output.string
ensure
Rails::TestUnitReporter.executable = original_executable
end
end
- private
- def assert_rerun_snippet_count(snippet_count)
- assert_equal snippet_count, @output.string.scan(%r{^bin/rails test }).size
+ test "outputs failures inline" do
+ @reporter.record(failed_test)
+ @reporter.report
+
+ expect = %r{\AF\n\nFailure:\nTestUnitReporterTest::ExampleTest#woot \[[^\]]+\]:\nboo\n\nbin/rails test test/test_unit/reporter_test.rb:\d+\n\n\z}
+ assert_match expect, @output.string
+ end
+
+ test "outputs errors inline" do
+ @reporter.record(errored_test)
+ @reporter.report
+
+ expect = %r{\AE\n\nError:\nTestUnitReporterTest::ExampleTest#woot:\nArgumentError: wups\n No backtrace\n\nbin/rails test .*test/test_unit/reporter_test.rb:\d+\n\n\z}
+ assert_match expect, @output.string
+ end
+
+ test "outputs skipped tests inline if verbose" do
+ verbose = Rails::TestUnitReporter.new @output, verbose: true, output_inline: true
+ verbose.record(skipped_test)
+ verbose.report
+
+ expect = %r{\ATestUnitReporterTest::ExampleTest#woot = 10\.00 s = S\n\n\nSkipped:\nTestUnitReporterTest::ExampleTest#woot \[[^\]]+\]:\nskipchurches, misstemples\n\nbin/rails test test/test_unit/reporter_test.rb:\d+\n\n\z}
+ assert_match expect, @output.string
+ end
+
+ test "does not output rerun snippets after run" do
+ @reporter.record(failed_test)
+ @reporter.report
+
+ assert_no_match "Failed tests:", @output.string
+ end
+
+ test "fail fast interrupts run on failure" do
+ fail_fast = Rails::TestUnitReporter.new @output, fail_fast: true
+ interrupt_raised = false
+
+ # Minitest passes through Interrupt, catch it manually.
+ begin
+ fail_fast.record(failed_test)
+ rescue Interrupt
+ interrupt_raised = true
+ ensure
+ assert interrupt_raised, "Expected Interrupt to be raised."
+ end
+ end
+
+ test "fail fast interrupts run on error" do
+ fail_fast = Rails::TestUnitReporter.new @output, fail_fast: true
+ interrupt_raised = false
+
+ # Minitest passes through Interrupt, catch it manually.
+ begin
+ fail_fast.record(errored_test)
+ rescue Interrupt
+ interrupt_raised = true
+ ensure
+ assert interrupt_raised, "Expected Interrupt to be raised."
+ end
end
- def failed_test
- ft = ExampleTest.new(:woot)
- ft.failures << begin
- raise Minitest::Assertion, "boo"
- rescue Minitest::Assertion => e
- e
- end
- ft
+ test "fail fast does not interrupt run skips" do
+ fail_fast = Rails::TestUnitReporter.new @output, fail_fast: true
+
+ fail_fast.record(skipped_test)
+ assert_no_match "Failed tests:", @output.string
end
- def passing_test
- ExampleTest.new(:woot)
+ test "outputs colored passing results" do
+ @output.stub(:tty?, true) do
+ colored = Rails::TestUnitReporter.new @output, color: true, output_inline: true
+ colored.record(passing_test)
+
+ expect = %r{\e\[32m\.\e\[0m}
+ assert_match expect, @output.string
+ end
end
- def skipped_test
- st = ExampleTest.new(:woot)
- st.failures << begin
- raise Minitest::Skip
- rescue Minitest::Assertion => e
- e
- end
- st
+ test "outputs colored skipped results" do
+ @output.stub(:tty?, true) do
+ colored = Rails::TestUnitReporter.new @output, color: true, output_inline: true
+ colored.record(skipped_test)
+
+ expect = %r{\e\[33mS\e\[0m}
+ assert_match expect, @output.string
+ end
end
+
+ test "outputs colored failed results" do
+ @output.stub(:tty?, true) do
+ colored = Rails::TestUnitReporter.new @output, color: true, output_inline: true
+ colored.record(errored_test)
+
+ expected = %r{\e\[31mE\e\[0m\n\n\e\[31mError:\nTestUnitReporterTest::ExampleTest#woot:\nArgumentError: wups\n No backtrace\n\e\[0m}
+ assert_match expected, @output.string
+ end
+ end
+
+ private
+ 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 errored_test
+ et = ExampleTest.new(:woot)
+ et.failures << Minitest::UnexpectedError.new(ArgumentError.new("wups"))
+ et
+ 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
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