diff options
Diffstat (limited to 'railties/test/application')
33 files changed, 1991 insertions, 558 deletions
diff --git a/railties/test/application/asset_debugging_test.rb b/railties/test/application/asset_debugging_test.rb index 9a571fac3a..8b83784ed6 100644 --- a/railties/test/application/asset_debugging_test.rb +++ b/railties/test/application/asset_debugging_test.rb @@ -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(); }" @@ -33,12 +36,19 @@ module ApplicationTests 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){ `bundle exec rake assets:precompile --trace 2>&1` } + output = Dir.chdir(app_path){ `bin/rake assets:precompile --trace 2>&1` } assert $?.success?, output - require "#{app_path}/config/environment" + + # Load app env + app "production" class ::PostsController < ActionController::Base ; end @@ -48,17 +58,16 @@ module ApplicationTests assert_no_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js"><\/script>/, last_response.body) end - test "assets aren't concatenated when compile is true is on and debug_assets params is true" do + test "assets are served with sourcemaps when compile is true 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' - assert_match(/<script src="\/assets\/application-([0-z]+)\.js\?body=1"><\/script>/, last_response.body) - assert_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js\?body=1"><\/script>/, last_response.body) + assert_match(/<script src="\/assets\/application(\.debug)?-([0-z]+)\.js"><\/script>/, last_response.body) end end end diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index 8f091cfdbf..18882e1855 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- require 'isolation/abstract_unit' require 'rack/test' require 'active_support/json' @@ -18,22 +17,32 @@ module ApplicationTests end def precompile!(env = nil) - quietly do - precompile_task = "bundle exec 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/rake 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('bundle exec rake assets:clobber') } + assert Dir.chdir(app_path) { system('bin/rake 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) @@ -52,7 +61,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 @@ -61,9 +73,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" @@ -72,10 +85,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"] @@ -87,6 +100,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 @@ -96,10 +110,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 @@ -107,9 +120,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 @@ -169,34 +179,39 @@ module ApplicationTests test 'precompile use assets defined in app env config' do add_to_env_config 'production', 'config.assets.precompile = [ "something.js" ]' - app_file 'app/assets/javascripts/something.js.erb', 'alert();' - precompile! 'RAILS_ENV=production' + precompile! RAILS_ENV: 'production' assert_file_exists("#{app_path}/public/assets/something-*.js") end test '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" ]' + 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();' - 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 +220,8 @@ module ApplicationTests app_file "app/assets/javascripts/application.js", "alert();" precompile! - manifest = Dir["#{app_path}/public/assets/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"]) @@ -218,23 +233,23 @@ module ApplicationTests precompile! - manifest = Dir["#{app_path}/public/x/manifest-*.json"].first + manifest = Dir["#{app_path}/public/x/.sprockets-manifest-*.json"].first assets = ActiveSupport::JSON.decode(File.read(manifest)) assert_match(/application-([0-z]+)\.js/, assets["assets"]["application.js"]) end test "assets do not require any assets group gem when manifest file is present" do app_file "app/assets/javascripts/application.js", "alert();" - add_to_env_config "production", "config.serve_static_assets = true" + add_to_env_config "production", "config.public_file_server.enabled = true" - ENV["RAILS_ENV"] = "production" - precompile! + precompile! RAILS_ENV: 'production' - manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first + 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 +258,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,29 +271,27 @@ 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/manifest-*.json"].first + manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first assets = ActiveSupport::JSON.decode(File.read(manifest)) asset_path = assets["assets"]["application.css"] 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 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,15 +300,17 @@ 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! - manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first + manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first 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 @@ -319,8 +333,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,7 +351,8 @@ 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 @@ -363,7 +378,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,10 +390,10 @@ 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 @@ -393,7 +409,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_equal "Post\n;\n", File.read(Dir["#{app_path}/public/assets/application-*.js"].first) end test "initialization on the assets group should set assets_dir" do @@ -434,13 +451,16 @@ 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'} - assert_match('src="http://example.com/assets/application.js', last_response.body) + assert_match('src="http://example.com/assets/application.debug.js', last_response.body) get '/posts', {}, {'HTTPS'=>'on'} - assert_match('src="https://example.com/assets/application.js', last_response.body) + assert_match('src="https://example.com/assets/application.debug.js', last_response.body) end test "asset urls should be protocol-relative if no request is in scope" do @@ -449,6 +469,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,20 +481,10 @@ 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) - end - test "assets:cache:clean should clean cache" do - ENV["RAILS_ENV"] = "production" precompile! - quietly do - Dir.chdir(app_path){ `bundle exec rake assets:clobber` } - end - - assert !File.exist?("#{app_path}/tmp/cache/assets") + assert_match "src='/sub/uri/assets/rails.png'", File.read(Dir["#{app_path}/public/assets/app-*.js"].first) end private diff --git a/railties/test/application/bin_setup_test.rb b/railties/test/application/bin_setup_test.rb new file mode 100644 index 0000000000..1bdced02e9 --- /dev/null +++ b/railties/test/application/bin_setup_test.rb @@ -0,0 +1,54 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class BinSetupTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + end + + def teardown + teardown_app + end + + def test_bin_setup + Dir.chdir(app_path) do + 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!") + + assert_equal '[]', list_tables.call + assert_equal 5, File.size("log/my.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 File.exist?("tmp/restart.txt") + end + end + + def test_bin_setup_output + Dir.chdir(app_path) do + app_file 'db/schema.rb', "" + + output = `bin/setup 2>&1` + assert_equal(<<-OUTPUT, output) +== Installing dependencies == +The Gemfile's dependencies are satisfied + +== Preparing database == + +== Removing old logs and tempfiles == + +== Restarting application server == + OUTPUT + end + end + end +end diff --git a/railties/test/application/build_original_fullpath_test.rb b/railties/test/application/build_original_fullpath_test.rb deleted file mode 100644 index 647ffb097a..0000000000 --- a/railties/test/application/build_original_fullpath_test.rb +++ /dev/null @@ -1,27 +0,0 @@ -require "abstract_unit" - -module ApplicationTests - class BuildOriginalPathTest < ActiveSupport::TestCase - def test_include_original_PATH_info_in_ORIGINAL_FULLPATH - env = { 'PATH_INFO' => '/foo/' } - assert_equal "/foo/", Rails.application.send(:build_original_fullpath, env) - end - - def test_include_SCRIPT_NAME - env = { - 'SCRIPT_NAME' => '/foo', - 'PATH_INFO' => '/bar' - } - - assert_equal "/foo/bar", Rails.application.send(:build_original_fullpath, env) - end - - def test_include_QUERY_STRING - env = { - 'PATH_INFO' => '/foo', - 'QUERY_STRING' => 'bar', - } - assert_equal "/foo?bar", Rails.application.send(:build_original_fullpath, env) - end - end -end diff --git a/railties/test/application/configuration/base_test.rb b/railties/test/application/configuration/base_test.rb deleted file mode 100644 index d6a82b139d..0000000000 --- a/railties/test/application/configuration/base_test.rb +++ /dev/null @@ -1,37 +0,0 @@ -require 'isolation/abstract_unit' -require 'rack/test' -require 'env_helpers' - -module ApplicationTests - module ConfigurationTests - class BaseTest < ActiveSupport::TestCase - def setup - build_app - boot_rails - FileUtils.rm_rf("#{app_path}/config/environments") - end - - def teardown - teardown_app - FileUtils.rm_rf(new_app) if File.directory?(new_app) - end - - private - def new_app - File.expand_path("#{app_path}/../new_app") - end - - def copy_app - FileUtils.cp_r(app_path, new_app) - end - - def app - @app ||= Rails.application - end - - def require_environment - require "#{app_path}/config/environment" - end - end - end -end
\ No newline at end of file diff --git a/railties/test/application/configuration/custom_test.rb b/railties/test/application/configuration/custom_test.rb index f8d22f6d97..28b3b2f2d6 100644 --- a/railties/test/application/configuration/custom_test.rb +++ b/railties/test/application/configuration/custom_test.rb @@ -1,22 +1,54 @@ -require 'application/configuration/base_test' - -class ApplicationTests::ConfigurationTests::CustomTest < ApplicationTests::ConfigurationTests::BaseTest - test 'access custom configuration point' do - add_to_config <<-RUBY - config.x.payment_processing.schedule = :daily - config.x.payment_processing.retries = 3 - config.x.super_debugger = true - config.x.hyper_debugger = false - config.x.nil_debugger = nil - RUBY - require_environment - - x = Rails.configuration.x - assert_equal :daily, x.payment_processing.schedule - assert_equal 3, x.payment_processing.retries - assert_equal true, x.super_debugger - assert_equal false, x.hyper_debugger - assert_equal nil, x.nil_debugger - assert_nil x.i_do_not_exist.zomg +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 + + def teardown + teardown_app + FileUtils.rm_rf(new_app) if File.directory?(new_app) + end + + test 'access custom configuration point' do + add_to_config <<-RUBY + config.x.payment_processing.schedule = :daily + config.x.payment_processing.retries = 3 + config.x.super_debugger = true + config.x.hyper_debugger = false + config.x.nil_debugger = nil + RUBY + require_environment + + x = Rails.configuration.x + assert_equal :daily, x.payment_processing.schedule + assert_equal 3, x.payment_processing.retries + assert_equal true, x.super_debugger + assert_equal false, x.hyper_debugger + assert_equal nil, x.nil_debugger + assert_nil x.i_do_not_exist.zomg + end + + private + def new_app + File.expand_path("#{app_path}/../new_app") + end + + def copy_app + FileUtils.cp_r(app_path, new_app) + end + + def app + @app ||= Rails.application + end + + def require_environment + require "#{app_path}/config/environment" + end + end end end diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 0eddf644d9..5f3d1879eb 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -34,14 +34,25 @@ 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 - FileUtils.rm_rf("#{app_path}/config/environments") + supress_default_config end def teardown @@ -49,6 +60,15 @@ module ApplicationTests FileUtils.rm_rf(new_app) if File.directory?(new_app) end + def supress_default_config + FileUtils.mv("#{app_path}/config/environments", "#{app_path}/config/__environments__") + end + + def restore_default_config + FileUtils.rm_rf("#{app_path}/config/environments") + FileUtils.mv("#{app_path}/config/__environments__", "#{app_path}/config/environments") + end + test "Rails.env does not set the RAILS_ENV environment variable which would leak out into rake tasks" do require "rails" @@ -59,6 +79,22 @@ module ApplicationTests end end + test "lib dir is on LOAD_PATH during config" do + app_file 'lib/my_logger.rb', <<-RUBY + require "logger" + class MyLogger < ::Logger + end + RUBY + add_to_top_of_config <<-RUBY + require 'my_logger' + config.logger = MyLogger.new STDOUT + RUBY + + app 'development' + + assert_equal 'MyLogger', Rails.application.config.logger.class.name + end + test "a renders exception on pending migration" do add_to_config <<-RUBY config.active_record.migration_error = :page_load @@ -74,7 +110,7 @@ module ApplicationTests end RUBY - require "#{app_path}/config/environment" + app 'development' ActiveRecord::Migrator.migrations_paths = ["#{app_path}/db/migrate"] @@ -105,29 +141,29 @@ module ApplicationTests test "Rails.application is nil until app is initialized" do 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 @@ -139,7 +175,8 @@ module ApplicationTests use_frameworks [] - require "#{app_path}/config/environment" + app 'development' + assert_equal Pathname.new(new_app), Rails.application.root end @@ -149,7 +186,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 @@ -158,7 +195,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 @@ -166,7 +205,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 @@ -176,12 +217,13 @@ 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 @@ -195,7 +237,7 @@ module ApplicationTests use_frameworks [] assert_nothing_raised do - require "#{app_path}/config/application" + app 'development' end end @@ -207,7 +249,7 @@ module ApplicationTests RUBY assert_nothing_raised do - require "#{app_path}/config/application" + app 'development' end end @@ -216,7 +258,7 @@ module ApplicationTests 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'] end @@ -232,7 +274,7 @@ module ApplicationTests assert !$prepared - require "#{app_path}/config/environment" + app 'development' get "/" assert $prepared @@ -244,7 +286,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 @@ -253,7 +295,7 @@ module ApplicationTests config.encoding = "utf-8" RUBY - require "#{app_path}/config/application" + app 'development' assert_utf8 end @@ -262,14 +304,65 @@ 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.public_file_server.enabled is off by default" do + restore_default_config + + with_rails_env "production" do + app 'production' + assert_not app.config.public_file_server.enabled + end + end + + 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 + app 'production' + assert app.config.public_file_server.enabled + 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 + 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 |app| - app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' - app.config.session_store :disabled + make_basic_app do |application| + application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' + application.config.session_store :disabled end class ::OmgController < ActionController::Base @@ -287,9 +380,9 @@ module ApplicationTests end test "application verifier can be used in the entire application" do - make_basic_app do |app| - app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' - app.config.session_store :disabled + make_basic_app do |application| + application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' + application.config.session_store :disabled end message = app.message_verifier(:sensitive_value).generate("some_value") @@ -301,10 +394,70 @@ module ApplicationTests assert_equal 'some_value', verifier.verify(message) end + test "application message verifier can be used when the key_generator is ActiveSupport::LegacyKeyGenerator" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + + 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 + message = app.message_verifier(:sensitive_value).generate("some_value") + assert_equal 'some_value', Rails.application.message_verifier(:sensitive_value).verify(message) + end + + test "warns when secrets.secret_key_base is blank and config.secret_token is set" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + + 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 + Rails.application.config.secret_token = "" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_token: 3b7cd727ee24e8444053437c36cc66c3 + YAML + + app 'development' + + assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token + end + test "application verifier can build different verifiers" do - make_basic_app do |app| - app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' - app.config.session_store :disabled + make_basic_app do |application| + application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' + application.config.session_store :disabled end default_verifier = app.message_verifier(:sensitive_value) @@ -327,7 +480,7 @@ module ApplicationTests secret_key_base: 3b7cd727ee24e8444053437c36cc66c3 YAML - require "#{app_path}/config/environment" + app 'development' assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_key_base end @@ -337,10 +490,26 @@ module ApplicationTests Rails.application.config.secret_key_base = "3b7cd727ee24e8444053437c36cc66c3" RUBY - require "#{app_path}/config/environment" + 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 + Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + secret_token: + YAML + + 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 development: @@ -349,7 +518,8 @@ module ApplicationTests aws_secret_access_key: myamazonsecretaccesskey YAML - require "#{app_path}/config/environment" + app 'development' + assert_equal 'myamazonaccesskeyid', app.secrets.aws_access_key_id assert_equal 'myamazonsecretaccesskey', app.secrets.aws_secret_access_key end @@ -357,11 +527,60 @@ module ApplicationTests test "blank config/secrets.yml does not crash the loading process" do 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 + Rails.application.config.secret_key_base = "iaminallyoursecretkeybase" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + + 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 + Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + + app 'development' + + assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token + assert_equal nil, app.secrets.secret_key_base + assert_equal app.key_generator.class, ActiveSupport::LegacyKeyGenerator + end + + test "uses ActiveSupport::LegacyKeyGenerator with config.secret_token as app.key_generator when secrets.secret_key_base is blank" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + + app 'development' + + assert_equal '', app.config.secret_token + assert_equal nil, app.secrets.secret_key_base + assert_raise ArgumentError, /\AA secret is required/ do + app.key_generator + end + end + test "protect from forgery is the default in a new app" do make_basic_app @@ -375,6 +594,44 @@ module ApplicationTests assert last_response.body =~ /csrf\-param/ end + test "default form builder specified as a string" do + app_file 'config/initializers/form_builder.rb', <<-RUBY + class CustomFormBuilder < ActionView::Helpers::FormBuilder + def text_field(attribute, *args) + label(attribute) + super(attribute, *args) + end + end + Rails.configuration.action_view.default_form_builder = "CustomFormBuilder" + RUBY + + app_file 'app/models/post.rb', <<-RUBY + class Post + include ActiveModel::Model + attr_accessor :name + end + RUBY + + + app_file 'app/controllers/posts_controller.rb', <<-RUBY + class PostsController < ApplicationController + def index + render inline: "<%= begin; form_for(Post.new) {|f| f.text_field(:name)}; rescue => e; e.to_s; end %>" + end + end + RUBY + + add_to_config <<-RUBY + routes.prepend do + resources :posts + end + RUBY + + 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 class Post @@ -408,9 +665,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) @@ -429,8 +686,8 @@ module ApplicationTests end test "request forgery token param can be changed" do - make_basic_app do - app.config.action_controller.request_forgery_protection_token = '_xsrf_token_here' + make_basic_app do |application| + application.config.action_controller.request_forgery_protection_token = '_xsrf_token_here' end class ::OmgController < ActionController::Base @@ -449,8 +706,8 @@ module ApplicationTests end test "sets ActionDispatch::Response.default_charset" do - make_basic_app do |app| - app.config.action_dispatch.default_charset = "utf-16" + make_basic_app do |application| + application.config.action_dispatch.default_charset = "utf-16" end assert_equal "utf-16", ActionDispatch::Response.default_charset @@ -461,9 +718,9 @@ 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") @@ -474,9 +731,9 @@ 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") @@ -487,12 +744,12 @@ module ApplicationTests config.action_mailer.preview_interceptors = MyPreviewMailInterceptor RUBY - require "#{app_path}/config/environment" - require "mail" + app 'development' + require "mail" _ = ActionMailer::Base - assert_equal [::MyPreviewMailInterceptor], ActionMailer::Base.preview_interceptors + assert_equal [ActionMailer::InlinePreviewInterceptor, ::MyPreviewMailInterceptor], ActionMailer::Base.preview_interceptors end test "registers multiple preview interceptors with ActionMailer" do @@ -500,12 +757,25 @@ module ApplicationTests config.action_mailer.preview_interceptors = [MyPreviewMailInterceptor, "MyOtherPreviewMailInterceptor"] RUBY - require "#{app_path}/config/environment" + 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 + ActionMailer::Base.preview_interceptors.delete(ActionMailer::InlinePreviewInterceptor) + RUBY + app 'development' + + require "mail" _ = ActionMailer::Base - assert_equal [MyPreviewMailInterceptor, MyOtherPreviewMailInterceptor], ActionMailer::Base.preview_interceptors + assert_equal [], ActionMailer::Base.preview_interceptors end test "registers observers with ActionMailer" do @@ -513,9 +783,9 @@ 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") @@ -526,21 +796,34 @@ 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") end + test "allows setting the queue name for the ActionMailer::DeliveryJob" do + add_to_config <<-RUBY + config.action_mailer.deliver_later_queue_name = 'test_default' + RUBY + + app 'development' + + require "mail" + _ = ActionMailer::Base + + assert_equal 'test_default', ActionMailer::Base.send(:class_variable_get, "@@deliver_later_queue_name") + end + test "valid timezone is setup correctly" do add_to_config <<-RUBY config.root = "#{app_path}" config.time_zone = "Wellington" RUBY - require "#{app_path}/config/environment" + app 'development' assert_equal "Wellington", Rails.application.config.time_zone end @@ -552,7 +835,7 @@ module ApplicationTests RUBY assert_raise(ArgumentError) do - require "#{app_path}/config/environment" + app 'development' end end @@ -562,7 +845,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 @@ -574,13 +857,14 @@ 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" + + app 'development' require 'action_view/base' assert_equal true, ActionView::Resolver.caching? @@ -588,7 +872,8 @@ module ApplicationTests test "config.action_view.cache_template_loading without cache_classes default" do add_to_config "config.cache_classes = false" - require "#{app_path}/config/environment" + + app 'development' require 'action_view/base' assert_equal false, ActionView::Resolver.caching? @@ -599,7 +884,8 @@ module ApplicationTests config.cache_classes = true config.action_view.cache_template_loading = false RUBY - require "#{app_path}/config/environment" + + app 'development' require 'action_view/base' assert_equal false, ActionView::Resolver.caching? @@ -610,7 +896,8 @@ module ApplicationTests config.cache_classes = false config.action_view.cache_template_loading = true RUBY - require "#{app_path}/config/environment" + + app 'development' require 'action_view/base' assert_equal true, ActionView::Resolver.caching? @@ -625,14 +912,14 @@ module ApplicationTests require 'action_view/railtie' require 'action_view/base' - require "#{app_path}/config/environment" + app 'development' assert_equal false, ActionView::Resolver.caching? end test "config.action_dispatch.show_exceptions is sent in env" do - make_basic_app do |app| - app.config.action_dispatch.show_exceptions = true + make_basic_app do |application| + application.config.action_dispatch.show_exceptions = true end class ::OmgController < ActionController::Base @@ -678,7 +965,7 @@ 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 @@ -700,7 +987,7 @@ 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 @@ -722,7 +1009,7 @@ 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 @@ -731,7 +1018,7 @@ module ApplicationTests 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 @@ -739,7 +1026,9 @@ 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 @@ -760,7 +1049,7 @@ 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 @@ -769,32 +1058,26 @@ module ApplicationTests 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 test "config.action_dispatch.ignore_accept_header" do - make_basic_app do |app| - app.config.action_dispatch.ignore_accept_header = true + make_basic_app do |application| + application.config.action_dispatch.ignore_accept_header = true end class ::OmgController < ActionController::Base @@ -831,9 +1114,9 @@ module ApplicationTests test "config.session_store with :active_record_store with activerecord-session_store gem" do begin - make_basic_app do |app| + make_basic_app do |application| ActionDispatch::Session::ActiveRecordStore = Class.new(ActionDispatch::Session::CookieStore) - app.config.session_store :active_record_store + application.config.session_store :active_record_store end ensure ActionDispatch::Session.send :remove_const, :ActiveRecordStore @@ -842,16 +1125,16 @@ module ApplicationTests test "config.session_store with :active_record_store without activerecord-session_store gem" do assert_raise RuntimeError, /activerecord-session_store/ do - make_basic_app do |app| - app.config.session_store :active_record_store + make_basic_app do |application| + application.config.session_store :active_record_store end end end test "config.log_level with custom logger" do - make_basic_app do |app| - app.config.logger = Logger.new(STDOUT) - app.config.log_level = :info + make_basic_app do |application| + application.config.logger = Logger.new(STDOUT) + application.config.log_level = :info end assert_equal Logger::INFO, Rails.logger.level end @@ -865,24 +1148,21 @@ 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 test "config.annotations wrapping SourceAnnotationExtractor::Annotation class" do - make_basic_app do |app| - app.config.annotations.register_extensions("coffee") do |tag| + make_basic_app do |application| + application.config.annotations.register_extensions("coffee") do |tag| /#\s*(#{tag}):?\s*(.*)$/ end end @@ -901,7 +1181,7 @@ module ApplicationTests end RUBY - require "#{app_path}/config/environment" + app 'development' assert_not Rails.configuration.ran_block require 'rake' @@ -923,7 +1203,7 @@ module ApplicationTests end RUBY - require "#{app_path}/config/environment" + app 'development' assert_not Rails.configuration.ran_block Rails.application.load_generators @@ -941,7 +1221,7 @@ module ApplicationTests end RUBY - require "#{app_path}/config/environment" + app 'development' assert_not Rails.configuration.ran_block Rails.application.load_console @@ -959,7 +1239,7 @@ module ApplicationTests end RUBY - require "#{app_path}/config/environment" + app 'development' assert_not Rails.configuration.ran_block Rails.application.load_runner @@ -970,19 +1250,19 @@ module ApplicationTests app_file 'config/environments/development.rb', <<-RUBY Rails.application.configure do - config.paths.add 'config/database', with: 'config/nonexistant.yml' + config.paths.add 'config/database', with: 'config/nonexistent.yml' config.paths['config/database'] << 'config/database.yml' end RUBY - require "#{app_path}/config/environment" + app 'development' assert_kind_of Hash, Rails.application.config.database_configuration end 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 @@ -990,25 +1270,23 @@ module ApplicationTests end test 'config.action_mailer.show_previews defaults to true in development' do - Rails.env = "development" - require "#{app_path}/config/environment" + 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" + 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" 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 @@ -1023,7 +1301,7 @@ 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'] end @@ -1034,7 +1312,7 @@ 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 @@ -1049,7 +1327,8 @@ 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 @@ -1061,7 +1340,8 @@ 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 @@ -1075,12 +1355,13 @@ module ApplicationTests add_to_config <<-RUBY 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'] end - test "config_for with syntax error show a more descritive exception" do + test "config_for with syntax error show a more descriptive exception" do app_file 'config/custom.yml', <<-RUBY development: key: foo: @@ -1091,10 +1372,26 @@ 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 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 end end diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb index 31bc003dcb..7bf123d12b 100644 --- a/railties/test/application/console_test.rb +++ b/railties/test/application/console_test.rb @@ -29,6 +29,18 @@ class ConsoleTest < ActiveSupport::TestCase assert_instance_of ActionDispatch::Integration::Session, console_session end + def test_app_can_access_path_helper_method + app_file 'config/routes.rb', <<-RUBY + Rails.application.routes.draw do + get 'foo', to: 'foo#index' + end + RUBY + + load_environment + console_session = irb_context.app + assert_equal '/foo', console_session.foo_path + end + def test_new_session_should_return_integration_session load_environment session = irb_context.new_session diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb index 78ada58ec8..84cc6e120b 100644 --- a/railties/test/application/generators_test.rb +++ b/railties/test/application/generators_test.rb @@ -125,5 +125,40 @@ module ApplicationTests assert_equal expected, c.generators.options end end + + test "api only generators hide assets, helper, js and css namespaces and set api option" do + add_to_config <<-RUBY + config.api_only = true + RUBY + + # Initialize the application + 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 Rails::Generators.options[:rails][:api] + assert_equal false, Rails::Generators.options[:rails][:assets] + assert_equal false, Rails::Generators.options[:rails][:helper] + assert_nil Rails::Generators.options[:rails][:template_engine] + end + + test "api only generators allow overriding generator options" do + add_to_config <<-RUBY + config.generators.helper = true + config.api_only = true + config.generators.template_engine = :my_template + RUBY + + # Initialize the application + require "#{app_path}/config/environment" + Rails.application.load_generators + + assert Rails::Generators.options[:rails][:api] + assert Rails::Generators.options[:rails][:helper] + assert_equal :my_template, Rails::Generators.options[:rails][:template_engine] + end end end diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index 2d45c9b53f..13f3250f5b 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 @@ -50,6 +49,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 @@ -65,7 +75,6 @@ module ApplicationTests RUBY require "#{app_path}/config/environment" - assert Foo.method_defined?(:foo_path) assert Foo.method_defined?(:foo_url) assert Foo.method_defined?(:main_app) end @@ -130,6 +139,35 @@ module ApplicationTests assert_equal "false", last_response.body end + test "action_controller api executes using all the middleware stack" do + add_to_config "config.api_only = true" + + app_file "app/controllers/application_controller.rb", <<-RUBY + class ApplicationController < ActionController::API + end + RUBY + + app_file "app/controllers/omg_controller.rb", <<-RUBY + class OmgController < ApplicationController + def show + render json: { omg: 'omg' } + end + end + RUBY + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + get "/:controller(/:action)" + end + RUBY + + require 'rack/test' + extend Rack::Test::Methods + + get 'omg/show' + assert_equal '{"omg":"omg"}', last_response.body + end + # AD test "action_dispatch extensions are applied to ActionDispatch" do add_to_config "config.action_dispatch.tld_length = 2" @@ -178,7 +216,7 @@ module ApplicationTests test "use schema cache dump" do Dir.chdir(app_path) do `rails generate model post title:string; - bundle exec rake db:migrate db:schema:cache:dump` + bin/rake db:migrate db:schema:cache:dump` end require "#{app_path}/config/environment" ActiveRecord::Base.connection.drop_table("posts") # force drop posts table for test. @@ -188,7 +226,7 @@ module ApplicationTests test "expire schema cache dump" do Dir.chdir(app_path) do `rails generate model post title:string; - bundle exec rake db:migrate db:schema:cache:dump db:rollback` + bin/rake db:migrate db:schema:cache:dump db:rollback` end silence_warnings { require "#{app_path}/config/environment" diff --git a/railties/test/application/initializers/i18n_test.rb b/railties/test/application/initializers/i18n_test.rb index 9ee54796a4..ab7f29b0f2 100644 --- a/railties/test/application/initializers/i18n_test.rb +++ b/railties/test/application/initializers/i18n_test.rb @@ -132,6 +132,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 diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb index 4f30f30f95..1027bca2c1 100644 --- a/railties/test/application/loading_test.rb +++ b/railties/test/application/loading_test.rb @@ -33,6 +33,35 @@ class LoadingTest < ActiveSupport::TestCase assert_equal 'omg', p.title end + test "concerns in app are autoloaded" do + app_file "app/controllers/concerns/trackable.rb", <<-CONCERN + module Trackable + end + CONCERN + + app_file "app/mailers/concerns/email_loggable.rb", <<-CONCERN + module EmailLoggable + end + CONCERN + + app_file "app/models/concerns/orderable.rb", <<-CONCERN + module Orderable + end + CONCERN + + app_file "app/validators/concerns/matchable.rb", <<-CONCERN + module Matchable + end + CONCERN + + require "#{rails_root}/config/environment" + + assert_nothing_raised(NameError) { Trackable } + assert_nothing_raised(NameError) { EmailLoggable } + assert_nothing_raised(NameError) { Orderable } + assert_nothing_raised(NameError) { Matchable } + end + test "models without table do not panic on scope definitions when loaded" do app_file "app/models/user.rb", <<-MODEL class User < ActiveRecord::Base @@ -181,7 +210,7 @@ class LoadingTest < ActiveSupport::TestCase app_file 'config/routes.rb', <<-RUBY $counter ||= 0 Rails.application.routes.draw do - get '/c', to: lambda { |env| User; [200, {"Content-Type" => "text/plain"}, [$counter.to_s]] } + get '/c', to: lambda { |env| User.name; [200, {"Content-Type" => "text/plain"}, [$counter.to_s]] } end RUBY @@ -214,7 +243,7 @@ class LoadingTest < ActiveSupport::TestCase $counter ||= 1 $counter *= 2 Rails.application.routes.draw do - get '/c', to: lambda { |env| User; [200, {"Content-Type" => "text/plain"}, [$counter.to_s]] } + get '/c', to: lambda { |env| User.name; [200, {"Content-Type" => "text/plain"}, [$counter.to_s]] } end RUBY diff --git a/railties/test/application/mailer_previews_test.rb b/railties/test/application/mailer_previews_test.rb index 55e917c3ec..643d876a26 100644 --- a/railties/test/application/mailer_previews_test.rb +++ b/railties/test/application/mailer_previews_test.rb @@ -1,5 +1,7 @@ require 'isolation/abstract_unit' require 'rack/test' +require 'base64' + module ApplicationTests class MailerPreviewsTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation @@ -29,7 +31,7 @@ module ApplicationTests test "/rails/mailers is accessible with correct configuraiton" 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 @@ -40,6 +42,17 @@ module ApplicationTests assert_equal 404, last_response.status end + test "/rails/mailers is accessible with globbing route present" do + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + get '*foo', to: 'foo#index' + end + RUBY + app("development") + get "/rails/mailers" + assert_equal 200, last_response.status + end + test "mailer previews are loaded from the default preview_path" do mailer 'notifier', <<-RUBY class Notifier < ActionMailer::Base @@ -316,6 +329,32 @@ module ApplicationTests assert_match "Email 'bar' not found in NotifierPreview", last_response.body end + test "mailer preview NullMail" do + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + # does not call +mail+ + end + end + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + 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 + assert_match "notifier#foo", last_response.body + end + test "mailer preview email part not found" do mailer 'notifier', <<-RUBY class Notifier < ActionMailer::Base @@ -417,56 +456,220 @@ module ApplicationTests assert_match '<option selected value="?part=text%2Fplain">View as plain-text email</option>', last_response.body end - test "*_path helpers emit a deprecation" do + test "mailer previews create correct links when loaded on a subdirectory" do + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" - app_file "config/routes.rb", <<-RUBY - Rails.application.routes.draw do - get 'foo', to: 'foo#index' + def foo + mail to: "to@example.org" + end end RUBY + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + 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 + + test "plain text mailer preview with attachment" do + image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca/JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo=" + + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + attachments['pixel.png'] = File.read("#{app_path}/public/images/pixel.png", mode: 'rb') + mail to: "to@example.org" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers/notifier/foo" + assert_equal 200, last_response.status + assert_match %r[<iframe seamless name="messageBody"], last_response.body + + get "/rails/mailers/notifier/foo?part=text/plain" + assert_equal 200, last_response.status + assert_match %r[Hello, World!], last_response.body + end + + test "multipart mailer preview with attachment" do + image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca/JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo=" + mailer 'notifier', <<-RUBY class Notifier < ActionMailer::Base default from: "from@example.com" - def path_in_view + def foo + attachments['pixel.png'] = File.read("#{app_path}/public/images/pixel.png", mode: 'rb') mail to: "to@example.org" end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + html_template 'notifier/foo', <<-RUBY + <p>Hello, World!</p> + RUBY - def path_in_mailer - @url = foo_path + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers/notifier/foo" + assert_equal 200, last_response.status + assert_match %r[<iframe seamless name="messageBody"], last_response.body + + get "/rails/mailers/notifier/foo?part=text/plain" + assert_equal 200, last_response.status + assert_match %r[Hello, World!], last_response.body + + get "/rails/mailers/notifier/foo?part=text/html" + assert_equal 200, last_response.status + assert_match %r[<p>Hello, World!</p>], last_response.body + end + + test "multipart mailer preview with inline attachment" do + image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca/JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo=" + + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + attachments['pixel.png'] = File.read("#{app_path}/public/images/pixel.png", mode: 'rb') mail to: "to@example.org" end end RUBY - html_template 'notifier/path_in_view', "<%= link_to 'foo', foo_path %>" + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + html_template 'notifier/foo', <<-RUBY + <p>Hello, World!</p> + <%= image_tag attachments['pixel.png'].url %> + RUBY mailer_preview 'notifier', <<-RUBY class NotifierPreview < ActionMailer::Preview - def path_in_view - Notifier.path_in_view + def foo + Notifier.foo end + end + RUBY + + app('development') + + get "/rails/mailers/notifier/foo" + assert_equal 200, last_response.status + assert_match %r[<iframe seamless name="messageBody"], last_response.body + + get "/rails/mailers/notifier/foo?part=text/plain" + assert_equal 200, last_response.status + assert_match %r[Hello, World!], last_response.body + + get "/rails/mailers/notifier/foo?part=text/html" + assert_equal 200, last_response.status + assert_match %r[<p>Hello, World!</p>], last_response.body + assert_match %r[src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca/JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo="], last_response.body + end + + test "multipart mailer preview with attached email" do + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + message = ::Mail.new do + from 'foo@example.com' + to 'bar@example.com' + subject 'Important Message' + + text_part do + body 'Goodbye, World!' + end + + html_part do + body '<p>Goodbye, World!</p>' + end + end + + attachments['message.eml'] = message.to_s + mail to: "to@example.org" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY - def path_in_mailer - Notifier.path_in_mailer + html_template 'notifier/foo', <<-RUBY + <p>Hello, World!</p> + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo end end RUBY app('development') - assert_deprecated do - get "/rails/mailers/notifier/path_in_view.html" - assert_equal 200, last_response.status - end + get "/rails/mailers/notifier/foo" + assert_equal 200, last_response.status + assert_match %r[<iframe seamless name="messageBody"], last_response.body - html_template 'notifier/path_in_mailer', "No ERB in here" + get "/rails/mailers/notifier/foo?part=text/plain" + assert_equal 200, last_response.status + assert_match %r[Hello, World!], last_response.body - assert_deprecated do - get "/rails/mailers/notifier/path_in_mailer.html" - assert_equal 200, last_response.status - end + get "/rails/mailers/notifier/foo?part=text/html" + assert_equal 200, last_response.status + assert_match %r[<p>Hello, World!</p>], last_response.body end private @@ -490,5 +693,9 @@ module ApplicationTests def text_template(name, contents) app_file("app/views/#{name}.text.erb", contents) end + + def image_file(name, contents) + 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 b4db840e68..c951dabd6c 100644 --- a/railties/test/application/middleware/cache_test.rb +++ b/railties/test/application/middleware/cache_test.rb @@ -81,8 +81,8 @@ module ApplicationTests add_to_config "config.action_dispatch.rack_cache = true" get "/expires/expires_header" - assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"] - assert_equal "max-age=10, public", last_response.headers["Cache-Control"] + assert_equal "miss, store", last_response.headers["X-Rack-Cache"] + assert_equal "max-age=10, public", last_response.headers["Cache-Control"] body = last_response.body @@ -115,8 +115,8 @@ module ApplicationTests add_to_config "config.action_dispatch.rack_cache = true" get "/expires/expires_etag" - assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"] - assert_equal "public", last_response.headers["Cache-Control"] + assert_equal "miss, store", last_response.headers["X-Rack-Cache"] + assert_equal "public", last_response.headers["Cache-Control"] body = last_response.body etag = last_response.headers["ETag"] @@ -149,8 +149,8 @@ module ApplicationTests add_to_config "config.action_dispatch.rack_cache = true" get "/expires/expires_last_modified" - assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"] - assert_equal "public", last_response.headers["Cache-Control"] + assert_equal "miss, store", last_response.headers["X-Rack-Cache"] + assert_equal "public", last_response.headers["Cache-Control"] body = last_response.body last = last_response.headers["Last-Modified"] diff --git a/railties/test/application/middleware/exceptions_test.rb b/railties/test/application/middleware/exceptions_test.rb index 42096cfec4..7b4babb13b 100644 --- a/railties/test/application/middleware/exceptions_test.rb +++ b/railties/test/application/middleware/exceptions_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'isolation/abstract_unit' require 'rack/test' @@ -49,7 +48,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 @@ -57,7 +56,22 @@ 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 + controller :foo, <<-RUBY + class FooController < ActionController::Base + def index + raise ActionController::UrlGenerationError + end + end + RUBY + + app.config.action_dispatch.show_exceptions = true + + get '/foo' + assert_equal 500, last_response.status end test "unspecified route when action_dispatch.show_exceptions is not set raises an exception" do diff --git a/railties/test/application/middleware/sendfile_test.rb b/railties/test/application/middleware/sendfile_test.rb index eb791f5687..be86f1a3b8 100644 --- a/railties/test/application/middleware/sendfile_test.rb +++ b/railties/test/application/middleware/sendfile_test.rb @@ -61,7 +61,7 @@ module ApplicationTests test "files handled by ActionDispatch::Static are handled by Rack::Sendfile" do make_basic_app do |app| app.config.action_dispatch.x_sendfile_header = 'X-Sendfile' - app.config.serve_static_assets = true + app.config.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 31a64c2f5a..25eadfc387 100644 --- a/railties/test/application/middleware/session_test.rb +++ b/railties/test/application/middleware/session_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'isolation/abstract_unit' require 'rack/test' @@ -36,7 +35,7 @@ module ApplicationTests flash[:notice] = "notice" end - render nothing: true + head :ok end end @@ -61,7 +60,7 @@ module ApplicationTests def write_session session[:foo] = 1 - render nothing: true + head :ok end def read_session @@ -102,7 +101,7 @@ module ApplicationTests def write_cookie cookies[:foo] = '1' - render nothing: true + head :ok end def read_cookie @@ -140,7 +139,7 @@ module ApplicationTests class FooController < ActionController::Base def write_session session[:foo] = 1 - render nothing: true + head :ok end def read_session @@ -185,7 +184,7 @@ module ApplicationTests class FooController < ActionController::Base def write_session session[:foo] = 1 - render nothing: true + head :ok end def read_session @@ -203,7 +202,7 @@ module ApplicationTests RUBY add_to_config <<-RUBY - config.secret_token = "3b7cd727ee24e8444053437c36cc66c4" + secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4" RUBY require "#{app_path}/config/environment" @@ -235,12 +234,12 @@ module ApplicationTests def write_raw_session # {"session_id"=>"1965d95720fffc123941bdfb7d2e6870", "foo"=>1} cookies[:_myapp_session] = "BAh7B0kiD3Nlc3Npb25faWQGOgZFRkkiJTE5NjVkOTU3MjBmZmZjMTIzOTQxYmRmYjdkMmU2ODcwBjsAVEkiCGZvbwY7AEZpBg==--315fb9931921a87ae7421aec96382f0294119749" - render nothing: true + head :ok end def write_session session[:foo] = session[:foo] + 1 - render nothing: true + head :ok end def read_session @@ -258,7 +257,7 @@ module ApplicationTests RUBY add_to_config <<-RUBY - config.secret_token = "3b7cd727ee24e8444053437c36cc66c4" + secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4" RUBY require "#{app_path}/config/environment" @@ -294,12 +293,12 @@ module ApplicationTests def write_raw_session # {"session_id"=>"1965d95720fffc123941bdfb7d2e6870", "foo"=>1} cookies[:_myapp_session] = "BAh7B0kiD3Nlc3Npb25faWQGOgZFRkkiJTE5NjVkOTU3MjBmZmZjMTIzOTQxYmRmYjdkMmU2ODcwBjsAVEkiCGZvbwY7AEZpBg==--315fb9931921a87ae7421aec96382f0294119749" - render nothing: true + head :ok end def write_session session[:foo] = session[:foo] + 1 - render nothing: true + head :ok end def read_session @@ -317,7 +316,7 @@ module ApplicationTests RUBY add_to_config <<-RUBY - config.secret_token = "3b7cd727ee24e8444053437c36cc66c4" + secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4" secrets.secret_key_base = nil RUBY @@ -334,7 +333,7 @@ module ApplicationTests get '/foo/read_signed_cookie' assert_equal '2', last_response.body - verifier = ActiveSupport::MessageVerifier.new(app.config.secret_token) + verifier = ActiveSupport::MessageVerifier.new(app.secrets.secret_token) get '/foo/read_raw_cookie' assert_equal 2, verifier.verify(last_response.body)['foo'] diff --git a/railties/test/application/middleware/static_test.rb b/railties/test/application/middleware/static_test.rb index 0a793f8f60..1246e20d94 100644 --- a/railties/test/application/middleware/static_test.rb +++ b/railties/test/application/middleware/static_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'isolation/abstract_unit' require 'rack/test' @@ -27,5 +26,43 @@ module ApplicationTests assert_not last_response.headers.has_key?('Cache-Control'), "Cache-Control should not be set" end + + test "headers for static files are configurable" do + app_file "public/about.html", 'static' + 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 '/' + + assert_equal "/index.html\n", last_response.body + end + + test "public_file_server.index_name configurable" do + app_file "public/other-index.html", "/other-index.html" + add_to_config "config.public_file_server.index_name = 'other-index'" + + require "#{app_path}/config/environment" + + get '/' + + assert_equal "/other-index.html\n", last_response.body + end end end diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb index caef39d16f..1434522cce 100644 --- a/railties/test/application/middleware_test.rb +++ b/railties/test/application/middleware_test.rb @@ -26,7 +26,7 @@ module ApplicationTests assert_equal [ "Rack::Sendfile", "ActionDispatch::Static", - "Rack::Lock", + "ActionDispatch::LoadInterlock", "ActiveSupport::Cache::Strategy::LocalCache", "Rack::Runtime", "Rack::MethodOverride", @@ -43,7 +43,32 @@ module ApplicationTests "ActionDispatch::Cookies", "ActionDispatch::Session::CookieStore", "ActionDispatch::Flash", - "ActionDispatch::ParamsParser", + "Rack::Head", + "Rack::ConditionalGet", + "Rack::ETag" + ], middleware + end + + test "api middleware stack" do + add_to_config "config.api_only = true" + + boot! + + assert_equal [ + "Rack::Sendfile", + "ActionDispatch::Static", + "ActionDispatch::LoadInterlock", + "ActiveSupport::Cache::Strategy::LocalCache", + "Rack::Runtime", + "ActionDispatch::RequestId", + "Rails::Rack::Logger", # must come after Rack::MethodOverride to properly log overridden methods + "ActionDispatch::ShowExceptions", + "ActionDispatch::DebugExceptions", + "ActionDispatch::RemoteIp", + "ActionDispatch::Reloader", + "ActionDispatch::Callbacks", + "ActiveRecord::ConnectionAdapters::ConnectionManagement", + "ActiveRecord::QueryCache", "Rack::Head", "Rack::ConditionalGet", "Rack::ETag" @@ -94,27 +119,44 @@ module ApplicationTests assert !middleware.include?("ActiveRecord::Migration::CheckPending") end - test "includes lock if cache_classes is set but eager_load is not" do + test "includes interlock if cache_classes is set but eager_load is not" do add_to_config "config.cache_classes = true" boot! - assert middleware.include?("Rack::Lock") + assert_not_includes middleware, "Rack::Lock" + assert_includes middleware, "ActionDispatch::LoadInterlock" + end + + test "includes interlock if cache_classes is off" do + add_to_config "config.cache_classes = false" + boot! + assert_not_includes middleware, "Rack::Lock" + assert_includes middleware, "ActionDispatch::LoadInterlock" end test "does not include lock if cache_classes is set and so is eager_load" do add_to_config "config.cache_classes = true" add_to_config "config.eager_load = true" boot! - assert !middleware.include?("Rack::Lock") + assert_not_includes middleware, "Rack::Lock" + assert_not_includes middleware, "ActionDispatch::LoadInterlock" end - test "does not include lock if allow_concurrency is set" 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" + assert_not_includes middleware, "ActionDispatch::LoadInterlock" end - test "removes static asset server if serve_static_assets is disabled" do - add_to_config "config.serve_static_assets = false" + test "includes lock if allow_concurrency is disabled" do + add_to_config "config.allow_concurrency = false" + boot! + assert_includes middleware, "Rack::Lock" + assert_not_includes middleware, "ActionDispatch::LoadInterlock" + 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 !middleware.include?("ActionDispatch::Static") end @@ -125,6 +167,22 @@ module ApplicationTests assert !middleware.include?("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_not middleware.include?("Rack::Runtime") + end + + test "can delete a middleware from the stack even if insert_after is added after delete" do + 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_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! diff --git a/railties/test/application/multiple_applications_test.rb b/railties/test/application/multiple_applications_test.rb index 9ebf163671..f2770a9cb4 100644 --- a/railties/test/application/multiple_applications_test.rb +++ b/railties/test/application/multiple_applications_test.rb @@ -8,6 +8,7 @@ module ApplicationTests build_app(initializers: true) boot_rails require "#{rails_root}/config/environment" + Rails.application.config.some_setting = 'something_or_other' end def teardown @@ -18,7 +19,7 @@ module ApplicationTests clone = Rails.application.clone assert_equal Rails.application.config, clone.config, "The cloned application should get a copy of the config" - assert_equal Rails.application.config.secret_key_base, clone.config.secret_key_base, "The base secret key on the config should be the same" + assert_equal Rails.application.config.some_setting, clone.config.some_setting, "The some_setting on the config should be the same" end def test_inheriting_multiple_times_from_application @@ -117,7 +118,7 @@ module ApplicationTests assert_equal 0, run_count, "Without loading the initializers, the count should be 0" # Set config.eager_load to false so that an eager_load warning doesn't pop up - AppTemplate::Application.new { config.eager_load = false }.initialize! + AppTemplate::Application.create { config.eager_load = false }.initialize! assert_equal 3, run_count, "There should have been three initializers that incremented the count" end @@ -160,13 +161,14 @@ module ApplicationTests def test_inserting_configuration_into_application app = AppTemplate::Application.new(config: Rails.application.config) - new_config = Rails::Application::Configuration.new("root_of_application") - new_config.secret_key_base = "some_secret_key_dude" - app.config.secret_key_base = "a_different_secret_key" + app.config.some_setting = "a_different_setting" + assert_equal "a_different_setting", app.config.some_setting, "The configuration's some_setting should be set." - assert_equal "a_different_secret_key", app.config.secret_key_base, "The configuration's secret key should be set." + new_config = Rails::Application::Configuration.new("root_of_application") + new_config.some_setting = "some_setting_dude" app.config = new_config - assert_equal "some_secret_key_dude", app.config.secret_key_base, "The configuration's secret key should have changed." + + assert_equal "some_setting_dude", app.config.some_setting, "The configuration's some_setting should have changed." assert_equal "root_of_application", app.config.root, "The root should have changed to the new config's root." assert_equal new_config, app.config, "The application's config should have changed to the new config." end diff --git a/railties/test/application/per_request_digest_cache_test.rb b/railties/test/application/per_request_digest_cache_test.rb new file mode 100644 index 0000000000..3198e12662 --- /dev/null +++ b/railties/test/application/per_request_digest_cache_test.rb @@ -0,0 +1,63 @@ +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 + 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 + + assert_equal [ '8ba099b7749542fe765ff34a6824d548' ], ActionView::Digestor.cache.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::Digestor.cache, :clear) do + get '/customers' + assert_equal 200, last_response.status + end + end +end diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb index 267469b6f5..f94d08673a 100644 --- a/railties/test/application/rake/dbs_test.rb +++ b/railties/test/application/rake/dbs_test.rb @@ -28,11 +28,11 @@ module ApplicationTests def db_create_and_drop(expected_database) Dir.chdir(app_path) do - output = `bundle exec rake db:create` + output = `bin/rake db:create` assert_empty output assert File.exist?(expected_database) assert_equal expected_database, ActiveRecord::Base.connection_config[:database] - output = `bundle exec rake db:drop` + output = `bin/rake db:drop` assert_empty output assert !File.exist?(expected_database) end @@ -49,11 +49,63 @@ module ApplicationTests db_create_and_drop database_url_db_name end + def with_database_existing + Dir.chdir(app_path) do + set_database_url + `bin/rake db:create` + yield + `bin/rake db:drop` + end + end + + test 'db:create failure because database exists' do + with_database_existing do + output = `bin/rake 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/rake 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/rake db:drop 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/rake 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 - `rails generate model book title:string; - bundle exec rake db:migrate` - output = `bundle exec rake db:migrate:status` + `bin/rails generate model book title:string; + bin/rake db:migrate` + output = `bin/rake db:migrate:status` assert_match(%r{database:\s+\S*#{Regexp.escape(expected_database)}}, output) assert_match(/up\s+\d{14}\s+Create books/, output) end @@ -72,8 +124,8 @@ module ApplicationTests def db_schema_dump Dir.chdir(app_path) do - `rails generate model book title:string; - rake db:migrate db:schema:dump` + `bin/rails generate model book title:string; + bin/rake db:migrate db:schema:dump` schema_dump = File.read("db/schema.rb") assert_match(/create_table \"books\"/, schema_dump) end @@ -90,8 +142,8 @@ module ApplicationTests def db_fixtures_load(expected_database) Dir.chdir(app_path) do - `rails generate model book title:string; - bundle exec rake db:migrate db:fixtures:load` + `bin/rails generate model book title:string; + bin/rake db:migrate db:fixtures:load` assert_match expected_database, ActiveRecord::Base.connection_config[:database] require "#{app_path}/app/models/book" assert_equal 2, Book.count @@ -109,13 +161,23 @@ module ApplicationTests db_fixtures_load database_url_db_name end + test 'db:fixtures:load with namespaced fixture' do + require "#{app_path}/config/environment" + Dir.chdir(app_path) do + `bin/rails generate model admin::book title:string; + bin/rake db:migrate db:fixtures:load` + require "#{app_path}/app/models/admin/book" + assert_equal 2, Admin::Book.count + end + end + def db_structure_dump_and_load(expected_database) Dir.chdir(app_path) do - `rails generate model book title:string; - bundle exec rake db:migrate db:structure:dump` + `bin/rails generate model book title:string; + bin/rake db:migrate db:structure:dump` structure_dump = File.read("db/structure.sql") assert_match(/CREATE TABLE \"books\"/, structure_dump) - `bundle exec rake environment db:drop db:structure:load` + `bin/rake environment db:drop db:structure:load` assert_match expected_database, ActiveRecord::Base.connection_config[:database] require "#{app_path}/app/models/book" #if structure is not loaded correctly, exception would be raised @@ -137,19 +199,72 @@ module ApplicationTests test 'db:structure:dump does not dump schema information when no migrations are used' do Dir.chdir(app_path) do # create table without migrations - `bundle exec rails runner 'ActiveRecord::Base.connection.create_table(:posts) {|t| t.string :title }'` + `bin/rails runner 'ActiveRecord::Base.connection.create_table(:posts) {|t| t.string :title }'` - stderr_output = capture(:stderr) { `bundle exec rake db:structure:dump` } + stderr_output = capture(:stderr) { `bin/rake db:structure:dump` } assert_empty stderr_output structure_dump = File.read("db/structure.sql") assert_match(/CREATE TABLE \"posts\"/, structure_dump) end end + test 'db:schema:load and db:structure:load do not purge the existing database' do + Dir.chdir(app_path) do + `bin/rails runner 'ActiveRecord::Base.connection.create_table(:posts) {|t| t.string :title }'` + + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: 20140423102712) do + create_table(:comments) {} + end + RUBY + + list_tables = lambda { `bin/rails runner 'p ActiveRecord::Base.connection.tables'`.strip } + + assert_equal '["posts"]', list_tables[] + `bin/rake db:schema:load` + assert_equal '["posts", "comments", "schema_migrations"]', list_tables[] + + app_file 'db/structure.sql', <<-SQL + CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255)); + SQL + + `bin/rake db:structure:load` + assert_equal '["posts", "comments", "schema_migrations", "users"]', list_tables[] + end + end + + test "db:schema:load with inflections" do + Dir.chdir(app_path) do + 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 + ActiveRecord::Base.primary_key_prefix_type = :table_name + RUBY + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: 20140423102712) do + create_table("goose".pluralize) do |t| + t.string :name + end + end + RUBY + + `bin/rake db:schema:load` + + tables = `bin/rails runner 'p ActiveRecord::Base.connection.tables'`.strip + assert_match(/"geese"/, tables) + + columns = `bin/rails runner 'p ActiveRecord::Base.connection.columns("geese").map(&:name)'`.strip + assert_equal columns, '["gooseid", "name"]' + end + end + def db_test_load_structure Dir.chdir(app_path) do - `rails generate model book title:string; - bundle exec rake db:migrate db:structure:dump db:test:load_structure` + `bin/rails generate model book title:string; + bin/rake db:migrate db:structure:dump db:test:load_structure` ActiveRecord::Base.configurations = Rails.application.config.database_configuration ActiveRecord::Base.establish_connection :test require "#{app_path}/app/models/book" @@ -165,15 +280,6 @@ module ApplicationTests db_test_load_structure end - test 'db:test deprecation' do - require "#{app_path}/config/environment" - Dir.chdir(app_path) do - output = `bundle exec rake db:migrate db:test:prepare 2>&1` - assert_equal "WARNING: db:test:prepare is deprecated. The Rails test helper now maintains " \ - "your test schema automatically, see the release notes for details.\n", output - end - end - test 'db:setup loads schema and seeds database' do begin @old_rails_env = ENV["RAILS_ENV"] @@ -194,7 +300,7 @@ module ApplicationTests RUBY Dir.chdir(app_path) do - database_path = `bundle exec rake db:setup` + database_path = `bin/rake db:setup` assert_equal "development.sqlite3", File.basename(database_path.strip) end ensure diff --git a/railties/test/application/rake/dev_test.rb b/railties/test/application/rake/dev_test.rb new file mode 100644 index 0000000000..28d8b22a37 --- /dev/null +++ b/railties/test/application/rake/dev_test.rb @@ -0,0 +1,35 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + module RakeTests + class RakeDevTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + boot_rails + end + + def teardown + teardown_app + end + + test 'dev:cache creates file and outputs message' do + Dir.chdir(app_path) do + output = `rake 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 + output = `rake dev:cache` + output = `rake dev:cache` + assert_not File.exist?('tmp/caching-dev.txt') + assert_match(/Development mode is no longer being cached/, output) + end + end + end + end +end diff --git a/railties/test/application/rake/framework_test.rb b/railties/test/application/rake/framework_test.rb new file mode 100644 index 0000000000..ec57af79f6 --- /dev/null +++ b/railties/test/application/rake/framework_test.rb @@ -0,0 +1,48 @@ +require "isolation/abstract_unit" +require "active_support/core_ext/string/strip" + +module ApplicationTests + module RakeTests + class FrameworkTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + boot_rails + FileUtils.rm_rf("#{app_path}/config/environments") + end + + def teardown + teardown_app + end + + def load_tasks + 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 + require "#{app_path}/config/environment" + + load_tasks + + assert_raise NameError do + Object.method(:app_generator) + end + end + + test 'requiring the rake task should not define method .invoke_from_app_generator on Object' do + require "#{app_path}/config/environment" + + load_tasks + + assert_raise NameError do + Object.method(:invoke_from_app_generator) + end + end + end + end +end diff --git a/railties/test/application/rake/migrations_test.rb b/railties/test/application/rake/migrations_test.rb index a3819b93b2..6b74707959 100644 --- a/railties/test/application/rake/migrations_test.rb +++ b/railties/test/application/rake/migrations_test.rb @@ -15,21 +15,21 @@ module ApplicationTests test 'running migrations with given scope' do Dir.chdir(app_path) do - `rails generate model user username:string password:string` + `bin/rails generate model user username:string password:string` app_file "db/migrate/01_a_migration.bukkits.rb", <<-MIGRATION class AMigration < ActiveRecord::Migration end MIGRATION - output = `rake db:migrate SCOPE=bukkits` + output = `bin/rake db:migrate SCOPE=bukkits` assert_no_match(/create_table\(:users\)/, output) assert_no_match(/CreateUsers/, output) assert_no_match(/add_column\(:users, :email, :string\)/, output) assert_match(/AMigration: migrated/, output) - output = `rake db:migrate SCOPE=bukkits VERSION=0` + output = `bin/rake db:migrate SCOPE=bukkits VERSION=0` assert_no_match(/drop_table\(:users\)/, output) assert_no_match(/CreateUsers/, output) assert_no_match(/remove_column\(:users, :email\)/, output) @@ -40,16 +40,16 @@ module ApplicationTests test 'model and migration generator with change syntax' do Dir.chdir(app_path) do - `rails generate model user username:string password:string; - rails generate migration add_email_to_users email:string` + `bin/rails generate model user username:string password:string; + bin/rails generate migration add_email_to_users email:string` - output = `rake db:migrate` + output = `bin/rake db:migrate` assert_match(/create_table\(:users\)/, output) assert_match(/CreateUsers: migrated/, output) assert_match(/add_column\(:users, :email, :string\)/, output) assert_match(/AddEmailToUsers: migrated/, output) - output = `rake db:rollback STEP=2` + output = `bin/rake db:rollback STEP=2` assert_match(/drop_table\(:users\)/, output) assert_match(/CreateUsers: reverted/, output) assert_match(/remove_column\(:users, :email, :string\)/, output) @@ -58,23 +58,23 @@ module ApplicationTests end test 'migration status when schema migrations table is not present' do - output = Dir.chdir(app_path){ `rake db:migrate:status 2>&1` } + output = Dir.chdir(app_path){ `bin/rake db:migrate:status 2>&1` } assert_equal "Schema migrations table does not exist yet.\n", output end test 'test migration status' do Dir.chdir(app_path) do - `rails generate model user username:string password:string; - rails generate migration add_email_to_users email:string; - rake db:migrate` + `bin/rails generate model user username:string password:string; + bin/rails generate migration add_email_to_users email:string; + bin/rake db:migrate` - output = `rake db:migrate:status` + output = `bin/rake db:migrate:status` assert_match(/up\s+\d{14}\s+Create users/, output) assert_match(/up\s+\d{14}\s+Add email to users/, output) - `rake db:rollback STEP=1` - output = `rake db:migrate:status` + `bin/rake db:rollback STEP=1` + output = `bin/rake db:migrate:status` assert_match(/up\s+\d{14}\s+Create users/, output) assert_match(/down\s+\d{14}\s+Add email to users/, output) @@ -85,17 +85,17 @@ module ApplicationTests add_to_config('config.active_record.timestamped_migrations = false') Dir.chdir(app_path) do - `rails generate model user username:string password:string; - rails generate migration add_email_to_users email:string; - rake db:migrate` + `bin/rails generate model user username:string password:string; + bin/rails generate migration add_email_to_users email:string; + bin/rake db:migrate` - output = `rake db:migrate:status` + output = `bin/rake db:migrate:status` assert_match(/up\s+\d{3,}\s+Create users/, output) assert_match(/up\s+\d{3,}\s+Add email to users/, output) - `rake db:rollback STEP=1` - output = `rake db:migrate:status` + `bin/rake db:rollback STEP=1` + output = `bin/rake db:migrate:status` assert_match(/up\s+\d{3,}\s+Create users/, output) assert_match(/down\s+\d{3,}\s+Add email to users/, output) @@ -104,23 +104,23 @@ module ApplicationTests test 'test migration status after rollback and redo' do Dir.chdir(app_path) do - `rails generate model user username:string password:string; - rails generate migration add_email_to_users email:string; - rake db:migrate` + `bin/rails generate model user username:string password:string; + bin/rails generate migration add_email_to_users email:string; + bin/rake db:migrate` - output = `rake db:migrate:status` + output = `bin/rake db:migrate:status` assert_match(/up\s+\d{14}\s+Create users/, output) assert_match(/up\s+\d{14}\s+Add email to users/, output) - `rake db:rollback STEP=2` - output = `rake db:migrate:status` + `bin/rake db:rollback STEP=2` + output = `bin/rake db:migrate:status` assert_match(/down\s+\d{14}\s+Create users/, output) assert_match(/down\s+\d{14}\s+Add email to users/, output) - `rake db:migrate:redo` - output = `rake db:migrate:status` + `bin/rake db:migrate:redo` + output = `bin/rake db:migrate:status` assert_match(/up\s+\d{14}\s+Create users/, output) assert_match(/up\s+\d{14}\s+Add email to users/, output) @@ -131,54 +131,78 @@ module ApplicationTests add_to_config('config.active_record.timestamped_migrations = false') Dir.chdir(app_path) do - `rails generate model user username:string password:string; - rails generate migration add_email_to_users email:string; - rake db:migrate` + `bin/rails generate model user username:string password:string; + bin/rails generate migration add_email_to_users email:string; + bin/rake db:migrate` - output = `rake db:migrate:status` + output = `bin/rake db:migrate:status` assert_match(/up\s+\d{3,}\s+Create users/, output) assert_match(/up\s+\d{3,}\s+Add email to users/, output) - `rake db:rollback STEP=2` - output = `rake db:migrate:status` + `bin/rake db:rollback STEP=2` + output = `bin/rake db:migrate:status` assert_match(/down\s+\d{3,}\s+Create users/, output) assert_match(/down\s+\d{3,}\s+Add email to users/, output) - `rake db:migrate:redo` - output = `rake db:migrate:status` + `bin/rake db:migrate:redo` + output = `bin/rake db:migrate:status` assert_match(/up\s+\d{3,}\s+Create users/, output) assert_match(/up\s+\d{3,}\s+Add email to users/, output) 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 + end + MIGRATION + + app_file "db/migrate/02_two_migration.rb", <<-MIGRATION + class TwoMigration < ActiveRecord::Migration + end + MIGRATION + + `bin/rake db:migrate` + + output = `bin/rake db:migrate:status` + + 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') Dir.chdir(app_path) do - `rails generate model book title:string; - bundle exec rake db:migrate` + `bin/rails generate model book title:string` + output = `bin/rails generate model author name:string` + version = output =~ %r{[^/]+db/migrate/(\d+)_create_authors\.rb} && $1 - assert !File.exist?("db/schema.rb") + `bin/rake db:migrate db:rollback db:forward db:migrate:up db:migrate:down VERSION=#{version}` + assert !File.exist?("db/schema.rb"), "should not dump schema when configured not to" end add_to_config('config.active_record.dump_schema_after_migration = true') Dir.chdir(app_path) do - `rails generate model author name:string; - bundle exec rake db:migrate` + `bin/rails generate model reviews book_id:integer` + `bin/rake db:migrate` structure_dump = File.read("db/schema.rb") - assert_match(/create_table "authors"/, structure_dump) + assert_match(/create_table "reviews"/, structure_dump) end end test 'default schema generation after migration' do Dir.chdir(app_path) do - `rails generate model book title:string; - bundle exec rake db:migrate` + `bin/rails generate model book title:string; + bin/rake db:migrate` structure_dump = File.read("db/schema.rb") assert_match(/create_table "books"/, structure_dump) @@ -187,12 +211,12 @@ module ApplicationTests test 'test migration status migrated file is deleted' do Dir.chdir(app_path) do - `rails generate model user username:string password:string; - rails generate migration add_email_to_users email:string; - rake db:migrate + `bin/rails generate model user username:string password:string; + bin/rails generate migration add_email_to_users email:string; + bin/rake db:migrate rm db/migrate/*email*.rb` - output = `rake db:migrate:status` + output = `bin/rake db:migrate:status` File.write('test.txt', output) assert_match(/up\s+\d{14}\s+Create users/, output) diff --git a/railties/test/application/rake/notes_test.rb b/railties/test/application/rake/notes_test.rb index 95087bf29f..c87515f00f 100644 --- a/railties/test/application/rake/notes_test.rb +++ b/railties/test/application/rake/notes_test.rb @@ -74,7 +74,7 @@ module ApplicationTests app_file "some_other_dir/blah.rb", "# TODO: note in some_other directory" - run_rake_notes "SOURCE_ANNOTATION_DIRECTORIES='some_other_dir' bundle exec rake notes" do |output, lines| + run_rake_notes "SOURCE_ANNOTATION_DIRECTORIES='some_other_dir' bin/rake notes" do |output, lines| assert_match(/note in app directory/, output) assert_match(/note in config directory/, output) assert_match(/note in db directory/, output) @@ -102,7 +102,7 @@ module ApplicationTests end EOS - run_rake_notes "bundle exec rake notes_custom" do |output, lines| + run_rake_notes "bin/rake notes_custom" do |output, lines| assert_match(/\[FIXME\] note in lib directory/, output) assert_match(/\[TODO\] note in test directory/, output) assert_no_match(/OPTIMIZE/, output) @@ -114,6 +114,7 @@ module ApplicationTests end 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" @@ -127,7 +128,7 @@ module ApplicationTests private - def run_rake_notes(command = 'bundle exec rake notes') + def run_rake_notes(command = 'bin/rake notes') boot_rails load_tasks diff --git a/railties/test/application/rake/restart_test.rb b/railties/test/application/rake/restart_test.rb new file mode 100644 index 0000000000..4cae199e6b --- /dev/null +++ b/railties/test/application/rake/restart_test.rb @@ -0,0 +1,39 @@ +require "isolation/abstract_unit" + +module ApplicationTests + module RakeTests + class RakeRestartTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + boot_rails + end + + def teardown + teardown_app + end + + test 'rake restart touches tmp/restart.txt' do + Dir.chdir(app_path) do + `rake restart` + assert File.exist?("tmp/restart.txt") + + prev_mtime = File.mtime("tmp/restart.txt") + sleep(1) + `rake 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 + Dir.chdir(app_path) do + FileUtils.remove_dir('tmp') + `rake restart` + assert File.exist?('tmp/restart.txt') + end + end + end + end +end diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb index e8c8de9f73..0da0928b48 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" @@ -36,7 +35,7 @@ module ApplicationTests Rails.application.initialize! RUBY - assert_match("SuperMiddleware", Dir.chdir(app_path){ `rake middleware` }) + assert_match("SuperMiddleware", Dir.chdir(app_path){ `bin/rake middleware` }) end def test_initializers_are_executed_in_rake_tasks @@ -51,7 +50,7 @@ module ApplicationTests end RUBY - output = Dir.chdir(app_path){ `rake do_nothing` } + output = Dir.chdir(app_path){ `bin/rake do_nothing` } assert_match "Doing something...", output end @@ -72,7 +71,7 @@ module ApplicationTests end RUBY - output = Dir.chdir(app_path) { `rake do_nothing` } + output = Dir.chdir(app_path) { `bin/rake do_nothing` } assert_match 'Hello world', output end @@ -93,14 +92,14 @@ module ApplicationTests RUBY Dir.chdir(app_path) do - assert system('rake do_nothing RAILS_ENV=production'), + assert system('bin/rake do_nothing RAILS_ENV=production'), 'should not be pre-required for rake even eager_load=true' end end def test_code_statistics_sanity - assert_match "Code LOC: 5 Test LOC: 0 Code to Test Ratio: 1:0.0", - Dir.chdir(app_path){ `rake stats` } + assert_match "Code LOC: 7 Test LOC: 0 Code to Test Ratio: 1:0.0", + Dir.chdir(app_path){ `bin/rake stats` } end def test_rake_routes_calls_the_route_inspector @@ -110,7 +109,7 @@ module ApplicationTests end RUBY - output = Dir.chdir(app_path){ `rake routes` } + output = Dir.chdir(app_path){ `bin/rake routes` } assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output end @@ -123,7 +122,7 @@ module ApplicationTests RUBY ENV['CONTROLLER'] = 'cart' - output = Dir.chdir(app_path){ `rake routes` } + output = Dir.chdir(app_path){ `bin/rake routes` } assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output end @@ -133,7 +132,7 @@ module ApplicationTests end RUBY - assert_equal <<-MESSAGE.strip_heredoc, Dir.chdir(app_path){ `rake routes` } + assert_equal <<-MESSAGE.strip_heredoc, Dir.chdir(app_path){ `bin/rake routes` } You don't have any routes defined! Please add some routes in config/routes.rb. @@ -151,21 +150,21 @@ module ApplicationTests end RUBY - output = Dir.chdir(app_path){ `rake log_something RAILS_ENV=production && cat log/production.log` } + output = Dir.chdir(app_path){ `bin/rake log_something RAILS_ENV=production && cat log/production.log` } assert_match "Sample log message", output end def test_loading_specific_fixtures Dir.chdir(app_path) do - `rails generate model user username:string password:string; - rails generate model product name:string; - rake db:migrate` + `bin/rails generate model user username:string password:string; + bin/rails generate model product name:string; + bin/rake db:migrate` end require "#{rails_root}/config/environment" # loading a specific fixture - errormsg = Dir.chdir(app_path) { `rake db:fixtures:load FIXTURES=products` } + errormsg = Dir.chdir(app_path) { `bin/rake db:fixtures:load FIXTURES=products` } assert $?.success?, errormsg assert_equal 2, ::AppTemplate::Application::Product.count @@ -174,42 +173,64 @@ module ApplicationTests def test_loading_only_yml_fixtures Dir.chdir(app_path) do - `rake db:migrate` + `bin/rake db:migrate` end app_file "test/fixtures/products.csv", "" require "#{rails_root}/config/environment" - errormsg = Dir.chdir(app_path) { `rake db:fixtures:load` } + errormsg = Dir.chdir(app_path) { `bin/rake db:fixtures:load` } assert $?.success?, errormsg end def test_scaffold_tests_pass_by_default output = Dir.chdir(app_path) do - `rails generate scaffold user username:string password:string; - bundle exec rake db:migrate test` + `bin/rails generate scaffold user username:string password:string; + bin/rake db:migrate test` end - assert_match(/7 runs, 13 assertions, 0 failures, 0 errors/, output) + assert_match(/7 runs, 12 assertions, 0 failures, 0 errors/, output) assert_no_match(/Errors running/, output) end - def test_scaffold_with_references_columns_tests_pass_by_default + def test_api_scaffold_tests_pass_by_default + add_to_config <<-RUBY + config.api_only = true + RUBY + + app_file "app/controllers/application_controller.rb", <<-RUBY + class ApplicationController < ActionController::API + end + RUBY + output = Dir.chdir(app_path) do - `rails generate scaffold LineItems product:references cart:belongs_to; - bundle exec rake db:migrate test` + `bin/rails generate scaffold user username:string password:string; + bin/rake db:migrate test` end - assert_match(/7 runs, 13 assertions, 0 failures, 0 errors/, output) + 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" + + output = Dir.chdir(app_path) do + `bin/rails generate scaffold LineItems product:references cart:belongs_to; + bin/rake db:migrate test` + end + + assert_match(/7 runs, 12 assertions, 0 failures, 0 errors/, output) assert_no_match(/Errors running/, output) end def test_db_test_clone_when_using_sql_format add_to_config "config.active_record.schema_format = :sql" output = Dir.chdir(app_path) do - `rails generate scaffold user username:string; - bundle exec rake db:migrate; - bundle exec rake db:test:clone 2>&1 --trace` + `bin/rails generate scaffold user username:string; + bin/rake db:migrate; + bin/rake db:test:clone 2>&1 --trace` end assert_match(/Execute db:test:clone_structure/, output) end @@ -217,9 +238,9 @@ module ApplicationTests def test_db_test_prepare_when_using_sql_format add_to_config "config.active_record.schema_format = :sql" output = Dir.chdir(app_path) do - `rails generate scaffold user username:string; - bundle exec rake db:migrate; - bundle exec rake db:test:prepare 2>&1 --trace` + `bin/rails generate scaffold user username:string; + bin/rake db:migrate; + bin/rake db:test:prepare 2>&1 --trace` end assert_match(/Execute db:test:load_structure/, output) end @@ -227,7 +248,7 @@ module ApplicationTests def test_rake_dump_structure_should_respect_db_structure_env_variable Dir.chdir(app_path) do # ensure we have a schema_migrations table to dump - `bundle exec rake db:migrate db:structure:dump DB_STRUCTURE=db/my_structure.sql` + `bin/rake db:migrate db:structure:dump SCHEMA=db/my_structure.sql` end assert File.exist?(File.join(app_path, 'db', 'my_structure.sql')) end @@ -236,8 +257,8 @@ module ApplicationTests add_to_config "config.active_record.schema_format = :sql" output = Dir.chdir(app_path) do - `rails g model post title:string; - bundle exec rake db:migrate:redo 2>&1 --trace;` + `bin/rails g model post title:string; + bin/rake db:migrate:redo 2>&1 --trace;` end # expect only Invoke db:structure:dump (first_time) @@ -246,23 +267,23 @@ module ApplicationTests def test_rake_dump_schema_cache Dir.chdir(app_path) do - `rails generate model post title:string; - rails generate model product name:string; - bundle exec rake db:migrate db:schema:cache:dump` + `bin/rails generate model post title:string; + bin/rails generate model product name:string; + bin/rake db:migrate db:schema:cache:dump` end assert File.exist?(File.join(app_path, 'db', 'schema_cache.dump')) end def test_rake_clear_schema_cache Dir.chdir(app_path) do - `bundle exec rake db:schema:cache:dump db:schema:cache:clear` + `bin/rake db:schema:cache:dump db:schema:cache:clear` end assert !File.exist?(File.join(app_path, 'db', 'schema_cache.dump')) end def test_copy_templates Dir.chdir(app_path) do - `bundle exec rake rails:templates:copy` + `bin/rake rails:templates:copy` %w(controller mailer scaffold).each do |dir| assert File.exist?(File.join(app_path, 'lib', 'templates', 'erb', dir)) end @@ -277,10 +298,17 @@ module ApplicationTests app_file "template.rb", "" output = Dir.chdir(app_path) do - `bundle exec rake rails:template LOCATION=template.rb` + `bin/rake rails:template LOCATION=template.rb` end assert_match(/Hello, World!/, output) end + + def test_tmp_clear_should_work_if_folder_missing + FileUtils.remove_dir("#{app_path}/tmp") + errormsg = Dir.chdir(app_path) { `bin/rake tmp:clear` } + assert_predicate $?, :success? + assert_empty errormsg + end end end diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb index 8576a2b738..0777714d35 100644 --- a/railties/test/application/routing_test.rb +++ b/railties/test/application/routing_test.rb @@ -21,6 +21,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" @@ -63,6 +69,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" @@ -123,6 +135,26 @@ module ApplicationTests assert_equal '/archives', last_response.body end + test "mount named rack app" do + controller :foo, <<-RUBY + class FooController < ApplicationController + def index + render text: my_blog_path + end + end + RUBY + + app_file 'config/routes.rb', <<-RUBY + Rails.application.routes.draw do + mount lambda { |env| [200, {}, [env["PATH_INFO"]]] }, at: "/blog", as: "my_blog" + get '/foo' => 'foo#index' + end + RUBY + + get '/foo' + assert_equal '/blog', last_response.body + end + test "multiple controllers" do controller :foo, <<-RUBY class FooController < ApplicationController diff --git a/railties/test/application/runner_test.rb b/railties/test/application/runner_test.rb index 6595c40f8b..0c180339b4 100644 --- a/railties/test/application/runner_test.rb +++ b/railties/test/application/runner_test.rb @@ -25,15 +25,15 @@ module ApplicationTests end def test_should_include_runner_in_shebang_line_in_help_without_option - assert_match "/rails runner", Dir.chdir(app_path) { `bundle exec rails runner` } + assert_match "/rails runner", Dir.chdir(app_path) { `bin/rails runner` } end def test_should_include_runner_in_shebang_line_in_help - assert_match "/rails runner", Dir.chdir(app_path) { `bundle exec rails runner --help` } + assert_match "/rails runner", Dir.chdir(app_path) { `bin/rails runner --help` } end def test_should_run_ruby_statement - assert_match "42", Dir.chdir(app_path) { `bundle exec rails runner "puts User.count"` } + assert_match "42", Dir.chdir(app_path) { `bin/rails runner "puts User.count"` } end def test_should_run_file @@ -41,7 +41,7 @@ module ApplicationTests puts User.count SCRIPT - assert_match "42", Dir.chdir(app_path) { `bundle exec rails runner "bin/count_users.rb"` } + assert_match "42", Dir.chdir(app_path) { `bin/rails runner "bin/count_users.rb"` } end def test_should_set_dollar_0_to_file @@ -49,7 +49,7 @@ module ApplicationTests puts $0 SCRIPT - assert_match "bin/dollar0.rb", Dir.chdir(app_path) { `bundle exec rails runner "bin/dollar0.rb"` } + assert_match "bin/dollar0.rb", Dir.chdir(app_path) { `bin/rails runner "bin/dollar0.rb"` } end def test_should_set_dollar_program_name_to_file @@ -57,7 +57,7 @@ module ApplicationTests puts $PROGRAM_NAME SCRIPT - assert_match "bin/program_name.rb", Dir.chdir(app_path) { `bundle exec rails runner "bin/program_name.rb"` } + assert_match "bin/program_name.rb", Dir.chdir(app_path) { `bin/rails runner "bin/program_name.rb"` } end def test_with_hook @@ -67,22 +67,22 @@ module ApplicationTests end RUBY - assert_match "true", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.application.config.ran"` } + assert_match "true", Dir.chdir(app_path) { `bin/rails runner "puts Rails.application.config.ran"` } end def test_default_environment - assert_match "development", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.env"` } + assert_match "development", Dir.chdir(app_path) { `bin/rails runner "puts Rails.env"` } end def test_environment_with_rails_env with_rails_env "production" do - assert_match "production", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.env"` } + assert_match "production", Dir.chdir(app_path) { `bin/rails runner "puts Rails.env"` } end end def test_environment_with_rack_env with_rack_env "production" do - assert_match "production", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.env"` } + assert_match "production", Dir.chdir(app_path) { `bin/rails runner "puts Rails.env"` } end end end diff --git a/railties/test/application/test_runner_test.rb b/railties/test/application/test_runner_test.rb index 032b11a95f..4965ab7da0 100644 --- a/railties/test/application/test_runner_test.rb +++ b/railties/test/application/test_runner_test.rb @@ -1,13 +1,13 @@ require 'isolation/abstract_unit' require 'active_support/core_ext/string/strip' +require 'env_helpers' module ApplicationTests class TestRunnerTest < ActiveSupport::TestCase - include ActiveSupport::Testing::Isolation + include ActiveSupport::Testing::Isolation, EnvHelpers def setup build_app - ENV['RAILS_ENV'] = nil create_schema end @@ -15,20 +15,6 @@ module ApplicationTests teardown_app end - def test_run_in_test_environment - app_file 'test/unit/env_test.rb', <<-RUBY - require 'test_helper' - - class EnvTest < ActiveSupport::TestCase - def test_env - puts "Current Environment: \#{Rails.env}" - end - end - RUBY - - assert_match "Current Environment: test", run_test_command('test/unit/env_test.rb') - end - def test_run_single_file create_test_file :models, 'foo' create_test_file :models, 'bar' @@ -47,16 +33,15 @@ module ApplicationTests def; end RUBY - error_stream = Tempfile.new('error') - redirect_stderr(error_stream) { run_test_command('test/models/error_test.rb') } - assert_match "syntax error", error_stream.read + 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' - run_test_models_command.tap do |output| + run_test_command("test/models").tap do |output| assert_match "FooTest", output assert_match "BarTest", output assert_match "2 runs, 2 assertions, 0 failures", output @@ -67,7 +52,7 @@ module ApplicationTests create_test_file :helpers, 'foo_helper' create_test_file :helpers, 'bar_helper' create_test_file :controllers, 'foobar_controller' - run_test_helpers_command.tap do |output| + run_test_command("test/helpers").tap do |output| assert_match "FooHelperTest", output assert_match "BarHelperTest", output assert_match "2 runs, 2 assertions, 0 failures", output @@ -75,6 +60,7 @@ module ApplicationTests end 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' @@ -91,7 +77,7 @@ module ApplicationTests create_test_file :controllers, 'foo_controller' create_test_file :controllers, 'bar_controller' create_test_file :models, 'foo' - run_test_controllers_command.tap do |output| + run_test_command("test/controllers").tap do |output| assert_match "FooControllerTest", output assert_match "BarControllerTest", output assert_match "2 runs, 2 assertions, 0 failures", output @@ -102,7 +88,7 @@ module ApplicationTests create_test_file :mailers, 'foo_mailer' create_test_file :mailers, 'bar_mailer' create_test_file :models, 'foo' - run_test_mailers_command.tap do |output| + run_test_command("test/mailers").tap do |output| assert_match "FooMailerTest", output assert_match "BarMailerTest", output assert_match "2 runs, 2 assertions, 0 failures", output @@ -113,7 +99,7 @@ module ApplicationTests create_test_file :jobs, 'foo_job' create_test_file :jobs, 'bar_job' create_test_file :models, 'foo' - run_test_jobs_command.tap do |output| + run_test_command("test/jobs").tap do |output| assert_match "FooJobTest", output assert_match "BarJobTest", output assert_match "2 runs, 2 assertions, 0 failures", output @@ -121,6 +107,7 @@ module ApplicationTests end 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' @@ -136,7 +123,7 @@ module ApplicationTests def test_run_integration create_test_file :integration, 'foo_integration' create_test_file :models, 'foo' - run_test_integration_command.tap do |output| + run_test_command("test/integration").tap do |output| assert_match "FooIntegration", output assert_match "1 runs, 1 assertions, 0 failures", output end @@ -166,7 +153,7 @@ module ApplicationTests end RUBY - run_test_command('test/unit/chu_2_koi_test.rb test_rikka').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 @@ -187,7 +174,7 @@ module ApplicationTests end RUBY - run_test_command('test/unit/chu_2_koi_test.rb /rikka/').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,18 +182,18 @@ module ApplicationTests def test_load_fixtures_when_running_test_suites create_model_with_fixture - suites = [:models, :helpers, [:units, :unit], :controllers, :mailers, - [:functionals, :functional], :integration] + suites = [:models, :helpers, :controllers, :mailers, :integration] suites.each do |suite, directory| directory ||= suite create_fixture_test directory - assert_match "3 users", run_task(["test:#{suite}"]) + assert_match "3 users", run_test_command("test/#{suite}") Dir.chdir(app_path) { FileUtils.rm_f "test/#{directory}" } end end 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' assert_match "3 users", run_task(["test models/user"]) @@ -214,6 +201,7 @@ module ApplicationTests 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 require 'test_helper' @@ -228,19 +216,17 @@ module ApplicationTests assert_match "development", run_test_command('test/unit/env_test.rb') end - def test_run_different_environment_using_e_tag - env = "development" - app_file 'test/unit/env_test.rb', <<-RUBY - require 'test_helper' + def test_run_in_test_environment_by_default + create_env_test - class EnvTest < ActiveSupport::TestCase - def test_env - puts Rails.env - end - end - RUBY + assert_match "Current Environment: test", run_test_command('test/unit/env_test.rb') + end - assert_match env, run_test_command("test/unit/env_test.rb RAILS_ENV=#{env}") + def test_run_different_environment + create_env_test + + assert_match "Current Environment: development", + run_test_command("-e development test/unit/env_test.rb") end def test_generated_scaffold_works_with_rails_test @@ -248,18 +234,141 @@ module ApplicationTests assert_match "0 failures, 0 errors, 0 skips", run_test_command('') end - private - def run_task(tasks) - Dir.chdir(app_path) { `bundle exec rake #{tasks.join ' '}` } + def test_run_multiple_folders + 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 end + end - def run_test_command(arguments = 'test/unit/test_test.rb') - run_task ['test', arguments] + def test_run_with_ruby_command + app_file 'test/models/post_test.rb', <<-RUBY + require 'test_helper' + + class PostTest < ActiveSupport::TestCase + test 'declarative syntax works' do + puts 'PostTest' + assert true + end + end + RUBY + + 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 + end end - %w{ mailers models helpers units controllers functionals integration jobs }.each do |type| - define_method("run_test_#{type}_command") do - run_task ["test:#{type}"] + end + + def test_mix_files_and_line_filters + create_test_file :models, 'account' + app_file 'test/models/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/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_multiple_line_filters + 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_filter_without_line_runs_all_tests + create_test_file :models, 'account' + + run_test_command('test/models/account_test.rb:').tap do |output| + assert_match 'AccountTest', 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') + 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') + 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') + end + end + + def test_run_app_without_rails_loaded + # Simulate a real Rails app boot. + 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('') + end + + def test_output_inline_by_default + create_test_file :models, 'post', pass: false + + output = run_test_command('test/models/post_test.rb') + assert_match %r{Running:\n\nPostTest\nF\n\nwups!\n\nbin/rails test test/models/post_test.rb:6}, 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 + + private + def run_test_command(arguments = 'test/unit/test_test.rb') + Dir.chdir(app_path) { `bin/rails t #{arguments}` } end def create_model_with_fixture @@ -292,27 +401,42 @@ module ApplicationTests RUBY end - def create_schema - app_file 'db/schema.rb', '' + def create_backtrace_test + app_file 'test/unit/backtrace_test.rb', <<-RUBY + require 'test_helper' + + class BacktraceTest < ActiveSupport::TestCase + def test_backtrace + puts Minitest.backtrace_filter + end + end + RUBY end - def redirect_stderr(target_stream) - previous_stderr = STDERR.dup - $stderr.reopen(target_stream) - yield - target_stream.rewind - ensure - $stderr = previous_stderr + def create_schema + 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 + require 'test_helper' + + class EnvTest < ActiveSupport::TestCase + def test_env + puts "Current Environment: \#{Rails.env}" end end RUBY @@ -325,7 +449,7 @@ module ApplicationTests end def run_migration - Dir.chdir(app_path) { `bundle exec rake db:migrate` } + Dir.chdir(app_path) { `bin/rake db:migrate` } end end end diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb index c724c867ec..0e997f4ba7 100644 --- a/railties/test/application/test_test.rb +++ b/railties/test/application/test_test.rb @@ -44,7 +44,7 @@ module ApplicationTests def test_index get '/posts' assert_response :success - assert_template "index" + assert_includes @response.body, 'Posts#index' end end RUBY @@ -64,7 +64,8 @@ module ApplicationTests RUBY output = run_test_file('unit/failing_test.rb', env: { "BACKTRACE" => "1" }) - assert_match %r{/app/test/unit/failing_test\.rb}, output + 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 @@ -193,6 +194,98 @@ module ApplicationTests assert_successful_test_run('models/user_test.rb') end + # TODO: would be nice if we could detect the schema change automatically. + # For now, the user has to synchronize the schema manually. + # This test-case serves as a reminder for this use-case. + test "manually synchronize test schema after rollback" do + output = script('generate model user name:string') + version = output.match(/(\d+)_create_users\.rb/)[1] + + app_file 'test/models/user_test.rb', <<-RUBY + require 'test_helper' + + class UserTest < ActiveSupport::TestCase + test "user" do + assert_equal ["id", "name"], User.columns_hash.keys + end + end + RUBY + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: #{version}) do + create_table :users do |t| + t.string :name + end + end + RUBY + + assert_successful_test_run "models/user_test.rb" + + # Simulate `db:rollback` + edit of the migration file + `db:migrate` + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: #{version}) do + create_table :users do |t| + t.string :name + t.integer :age + end + end + RUBY + + assert_successful_test_run "models/user_test.rb" + + Dir.chdir(app_path) { `bin/rake db:test:prepare` } + + assert_unsuccessful_run "models/user_test.rb", <<-ASSERTION +Expected: ["id", "name"] + Actual: ["id", "name", "age"] + ASSERTION + end + + test "hooks for plugins" do + output = script('generate model user name:string') + version = output.match(/(\d+)_create_users\.rb/)[1] + + app_file 'lib/tasks/hooks.rake', <<-RUBY + task :before_hook do + has_user_table = ActiveRecord::Base.connection.table_exists?('users') + puts "before: " + has_user_table.to_s + end + + task :after_hook do + has_user_table = ActiveRecord::Base.connection.table_exists?('users') + puts "after: " + has_user_table.to_s + end + + Rake::Task["db:test:prepare"].enhance [:before_hook] do + Rake::Task[:after_hook].invoke + end + RUBY + app_file 'test/models/user_test.rb', <<-RUBY + require 'test_helper' + class UserTest < ActiveSupport::TestCase + test "user" do + User.create! name: "Jon" + end + end + RUBY + + # Simulate `db:migrate` + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: #{version}) do + create_table :users do |t| + t.string :name + end + end + RUBY + + output = assert_successful_test_run "models/user_test.rb" + assert_includes output, "before: false\nafter: true" + + # running tests again won't trigger a schema update + output = assert_successful_test_run "models/user_test.rb" + assert_not_includes output, "before:" + assert_not_includes output, "after:" + end + private def assert_unsuccessful_run(name, message) result = run_test_file(name) @@ -208,23 +301,7 @@ module ApplicationTests end def run_test_file(name, options = {}) - ruby '-Itest', "#{app_path}/test/#{name}", options - end - - def ruby(*args) - options = args.extract_options! - env = options.fetch(:env, {}) - env["RUBYLIB"] = $:.join(':') - - Dir.chdir(app_path) do - `#{env_string(env)} #{Gem.ruby} #{args.join(' ')} 2>&1` - end - end - - def env_string(variables) - variables.map do |key, value| - "#{key}='#{value}'" - end.join " " + Dir.chdir(app_path) { `bin/rails test "#{app_path}/test/#{name}" 2>&1` } end end end diff --git a/railties/test/application/url_generation_test.rb b/railties/test/application/url_generation_test.rb index efbc853d7b..894e18cb39 100644 --- a/railties/test/application/url_generation_test.rb +++ b/railties/test/application/url_generation_test.rb @@ -15,7 +15,7 @@ module ApplicationTests require "action_view/railtie" class MyApp < Rails::Application - config.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4" + secrets.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4" config.session_store :cookie_store, key: "_myapp_session" config.active_support.deprecation = :log config.eager_load = false @@ -42,5 +42,18 @@ module ApplicationTests get "/" assert_equal "/", last_response.body end + + def test_routes_know_the_relative_root + boot_rails + require "rails" + require "action_controller/railtie" + require "action_view/railtie" + + relative_url = '/hello' + ENV["RAILS_RELATIVE_URL_ROOT"] = relative_url + app = Class.new(Rails::Application) + assert_equal relative_url, app.routes.relative_url_root + ENV["RAILS_RELATIVE_URL_ROOT"] = nil + end end end |