diff options
Diffstat (limited to 'railties/test')
52 files changed, 1570 insertions, 317 deletions
diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb index 491faf4af9..643cc6b0ee 100644 --- a/railties/test/abstract_unit.rb +++ b/railties/test/abstract_unit.rb @@ -8,6 +8,7 @@ require 'fileutils' require 'active_support' require 'action_controller' +require 'action_view' require 'rails/all' module TestApp diff --git a/railties/test/app_rails_loader_test.rb b/railties/test/app_rails_loader_test.rb index 63ed9eaef0..92cb3233d8 100644 --- a/railties/test/app_rails_loader_test.rb +++ b/railties/test/app_rails_loader_test.rb @@ -1,48 +1,68 @@ +require 'tmpdir' require 'abstract_unit' require 'rails/app_rails_loader' class AppRailsLoaderTest < ActiveSupport::TestCase + def write(filename, contents=nil) + FileUtils.mkdir_p(File.dirname(filename)) + File.write(filename, contents) + end + + def expects_exec(exe) + Rails::AppRailsLoader.expects(:exec).with(Rails::AppRailsLoader::RUBY, exe) + end setup do - File.stubs(:exists?).returns(false) + @tmp = Dir.mktmpdir('railties-rails-loader-test-suite') + @cwd = Dir.pwd + Dir.chdir(@tmp) end - ['bin/rails', 'script/rails'].each do |exe| - test "is in a rails application if #{exe} exists and contains APP_PATH" do - File.stubs(:exists?).with(exe).returns(true) - File.stubs(:read).with(exe).returns('APP_PATH') - assert Rails::AppRailsLoader.find_executable - end + ['bin', 'script'].each do |script_dir| + exe = "#{script_dir}/rails" - test "is not in a rails application if #{exe} exists but doesn't contain APP_PATH" do - File.stubs(:exists?).with(exe).returns(true) - File.stubs(:read).with(exe).returns("railties #{exe}") - assert !Rails::AppRailsLoader.find_executable - end + test "is not in a Rails application if #{exe} is not found in the current or parent directories" do + File.stubs(:exist?).with('bin/rails').returns(false) + File.stubs(:exist?).with('script/rails').returns(false) - test "is in a rails application if parent directory has #{exe} containing APP_PATH" do - File.stubs(:exists?).with("/foo/bar/#{exe}").returns(false) - File.stubs(:exists?).with("/foo/#{exe}").returns(true) - File.stubs(:read).with("/foo/#{exe}").returns('APP_PATH') - assert Rails::AppRailsLoader.find_executable_in_parent_path(Pathname.new("/foo/bar")) + assert !Rails::AppRailsLoader.exec_app_rails end - test "is not in a rails application if at the root directory and doesn't have #{exe}" do - Pathname.any_instance.stubs(:root?).returns true - assert !Rails::AppRailsLoader.find_executable - end + ['APP_PATH', 'ENGINE_PATH'].each do |keyword| + test "is in a Rails application if #{exe} exists and contains #{keyword}" do + write exe, keyword - test "is in a rails engine if parent directory has #{exe} containing ENGINE_PATH" do - File.stubs(:exists?).with("/foo/bar/#{exe}").returns(false) - File.stubs(:exists?).with("/foo/#{exe}").returns(true) - File.stubs(:read).with("/foo/#{exe}").returns('ENGINE_PATH') - assert Rails::AppRailsLoader.find_executable_in_parent_path(Pathname.new("/foo/bar")) - end + expects_exec exe + Rails::AppRailsLoader.exec_app_rails + end - test "is in a rails engine if #{exe} exists containing ENGINE_PATH" do - File.stubs(:exists?).with(exe).returns(true) - File.stubs(:read).with(exe).returns('ENGINE_PATH') - assert Rails::AppRailsLoader.find_executable + test "is not in a Rails application if #{exe} exists but doesn't contain #{keyword}" do + write exe + + assert !Rails::AppRailsLoader.exec_app_rails + end + + test "is in a Rails application if parent directory has #{exe} containing #{keyword} and chdirs to the root directory" do + write "foo/bar/#{exe}" + write "foo/#{exe}", keyword + + Dir.chdir('foo/bar') + + expects_exec exe + Rails::AppRailsLoader.exec_app_rails + + # Compare the realpath in case either of them has symlinks. + # + # This happens in particular in Mac OS X, where @tmp starts + # with "/var", and Dir.pwd with "/private/var", due to a + # default system symlink var -> private/var. + assert_equal File.realpath("#@tmp/foo"), File.realpath(Dir.pwd) + end end end + + teardown do + Dir.chdir(@cwd) + FileUtils.rm_rf(@tmp) + end end diff --git a/railties/test/application/asset_debugging_test.rb b/railties/test/application/asset_debugging_test.rb index 1eddfac664..9a571fac3a 100644 --- a/railties/test/application/asset_debugging_test.rb +++ b/railties/test/application/asset_debugging_test.rb @@ -14,7 +14,7 @@ module ApplicationTests app_file "app/views/posts/index.html.erb", "<%= javascript_include_tag 'application' %>" app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get '/posts', to: "posts#index" end RUBY @@ -48,7 +48,7 @@ module ApplicationTests assert_no_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js"><\/script>/, last_response.body) end - test "assets aren't concatened when compile is true is on and debug_assets params is true" do + test "assets aren't concatenated when compile is true is on and debug_assets params is true" do add_to_env_config "production", "config.assets.compile = true" ENV["RAILS_ENV"] = "production" diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index 638df8ca23..b235b51d90 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -37,14 +37,15 @@ module ApplicationTests end def assert_no_file_exists(filename) - assert !File.exists?(filename), "#{filename} does exist" + assert !File.exist?(filename), "#{filename} does exist" end test "assets routes have higher priority" do + app_file "app/assets/images/rails.png", "notactuallyapng" app_file "app/assets/javascripts/demo.js.erb", "a = <%= image_path('rails.png').inspect %>;" app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get '*path', to: lambda { |env| [200, { "Content-Type" => "text/html" }, ["Not an asset"]] } end RUBY @@ -86,11 +87,11 @@ module ApplicationTests def test_precompile_does_not_hit_the_database app_file "app/assets/javascripts/application.js", "alert();" app_file "app/assets/javascripts/foo/application.js", "alert();" - app_file "app/controllers/user_controller.rb", <<-eoruby - class UserController < ApplicationController; end + app_file "app/controllers/users_controller.rb", <<-eoruby + class UsersController < ApplicationController; end eoruby app_file "app/models/user.rb", <<-eoruby - class User < ActiveRecord::Base; end + class User < ActiveRecord::Base; raise 'should not be reached'; end eoruby ENV['RAILS_ENV'] = 'production' @@ -164,6 +165,29 @@ module ApplicationTests assert_file_exists("#{app_path}/public/assets/something-*.js") end + test 'precompile use assets defined in app env config' do + add_to_env_config 'production', 'config.assets.precompile = [ "something.js" ]' + + app_file 'app/assets/javascripts/something.js.erb', 'alert();' + + precompile! 'RAILS_ENV=production' + + assert_file_exists("#{app_path}/public/assets/something-*.js") + end + + test 'precompile use assets defined in app 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" ]' + + app_file 'app/assets/javascripts/something.js.erb', 'alert();' + app_file 'app/assets/javascripts/another.js.erb', 'alert();' + + precompile! 'RAILS_ENV=production' + + assert_file_exists("#{app_path}/public/assets/something-*.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 add_to_config "config.assets.digest = true" add_to_config "config.action_controller.perform_caching = false" @@ -221,7 +245,8 @@ module ApplicationTests assert !defined?(Uglifier) end - test "precompile properly refers files referenced with asset_path and and run in the provided RAILS_ENV" do + test "precompile properly refers files referenced with asset_path and runs in the provided RAILS_ENV" do + app_file "app/assets/images/rails.png", "notactuallyapng" app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>" # digest is default in false, we must enable it for test environment add_to_env_config "test", "config.assets.digest = true" @@ -233,6 +258,8 @@ module ApplicationTests end 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", "//= depend_on rails.png\np { url: <%= asset_path('rails.png') %> }" ENV["RAILS_ENV"] = "production" @@ -251,6 +278,7 @@ module ApplicationTests 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') %>" add_to_config "config.assets.compile = true" add_to_config "config.assets.digest = true" @@ -265,19 +293,19 @@ module ApplicationTests test "precompile should handle utf8 filenames" do filename = "レイルズ.png" - app_file "app/assets/images/#{filename}", "not a image really" + app_file "app/assets/images/#{filename}", "not an image really" add_to_config "config.assets.precompile = [ /\.png$/, /application.(css|js)$/ ]" precompile! manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first assets = ActiveSupport::JSON.decode(File.read(manifest)) - assert asset_path = assets["assets"].find { |(k, _)| k !~ /rails.png/ && k =~ /.png/ }[1] + assert asset_path = assets["assets"].find { |(k, _)| k && k =~ /.png/ }[1] require "#{app_path}/config/environment" get "/assets/#{URI.parser.escape(asset_path)}" - assert_match "not a image really", last_response.body + assert_match "not an image really", last_response.body assert_file_exists("#{app_path}/public/assets/#{asset_path}") end @@ -308,7 +336,7 @@ module ApplicationTests app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();" app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get '/omg', :to => "omg#index" end RUBY @@ -371,18 +399,6 @@ module ApplicationTests assert_equal "Post;\n", File.read(Dir["#{app_path}/public/assets/application-*.js"].first) end - test "assets can't access model information when precompiling if not initializing the app" do - app_file "app/models/post.rb", "class Post; end" - app_file "app/assets/javascripts/application.js", "//= require_tree ." - app_file "app/assets/javascripts/xmlhr.js.erb", "<%= defined?(Post) || :NoPost %>" - - add_to_config "config.assets.digest = false" - add_to_config "config.assets.initialize_on_precompile = false" - - precompile! - assert_equal "NoPost;\n", File.read(Dir["#{app_path}/public/assets/application-*.js"].first) - end - test "initialization on the assets group should set assets_dir" do require "#{app_path}/config/application" Rails.application.initialize!(:assets) @@ -431,6 +447,7 @@ module ApplicationTests end test "asset urls should be protocol-relative if no request is in scope" do + app_file "app/assets/images/rails.png", "notreallyapng" app_file "app/assets/javascripts/image_loader.js.erb", 'var src="<%= image_path("rails.png") %>";' add_to_config "config.assets.precompile = %w{image_loader.js}" add_to_config "config.asset_host = 'example.com'" @@ -441,6 +458,7 @@ module ApplicationTests test "asset paths should use RAILS_RELATIVE_URL_ROOT by default" do ENV["RAILS_RELATIVE_URL_ROOT"] = "/sub/uri" + app_file "app/assets/images/rails.png", "notreallyapng" app_file "app/assets/javascripts/app.js.erb", 'var src="<%= image_path("rails.png") %>";' add_to_config "config.assets.precompile = %w{app.js}" @@ -468,7 +486,7 @@ module ApplicationTests app_file "app/views/posts/index.html.erb", "<%= javascript_include_tag 'application' %>" app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get '/posts', :to => "posts#index" end RUBY diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 7b45623f6c..03a735b1c1 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -62,6 +62,7 @@ module ApplicationTests require "#{app_path}/config/environment" ActiveRecord::Migrator.stubs(:needs_migration?).returns(true) + ActiveRecord::NullMigration.any_instance.stubs(:mtime).returns(1) get "/foo" assert_equal 500, last_response.status @@ -158,12 +159,12 @@ module ApplicationTests RUBY require "#{app_path}/config/application" - assert AppTemplate::Application.initialize! + assert Rails.application.initialize! end test "application is always added to eager_load namespaces" do require "#{app_path}/config/application" - assert AppTemplate::Application, AppTemplate::Application.config.eager_load_namespaces + assert Rails.application, Rails.application.config.eager_load_namespaces end test "the application can be eager loaded even when there are no frameworks" do @@ -599,7 +600,7 @@ module ApplicationTests assert_equal :log, ActionController::Parameters.action_on_unpermitted_parameters end - test "config.action_controller.action_on_unpermitted_parameters is :log by defaul on test" do + test "config.action_controller.action_on_unpermitted_parameters is :log by default on test" do ENV["RAILS_ENV"] = "test" require "#{app_path}/config/environment" @@ -670,5 +671,20 @@ module ApplicationTests 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 + end + assert_equal Logger::INFO, Rails.logger.level + end + + test "respond_to? accepts include_private" do + make_basic_app + + assert_not Rails.configuration.respond_to?(:method_missing) + assert Rails.configuration.respond_to?(:method_missing, true) + end end end diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb index af495bb450..31bc003dcb 100644 --- a/railties/test/application/console_test.rb +++ b/railties/test/application/console_test.rb @@ -126,37 +126,28 @@ class FullStackConsoleTest < ActiveSupport::TestCase assert_output "> " end - def kill(pid) - Process.kill('QUIT', pid) - Process.wait(pid) - rescue Errno::ESRCH - end - def spawn_console - pid = Process.spawn( + Process.spawn( "#{app_path}/bin/rails console --sandbox", in: @slave, out: @slave, err: @slave ) assert_output "> ", 30 - pid end def test_sandbox - pid = spawn_console + spawn_console write_prompt "Post.count", "=> 0" write_prompt "Post.create" write_prompt "Post.count", "=> 1" + @master.puts "quit" - kill pid - - pid = spawn_console + spawn_console write_prompt "Post.count", "=> 0" write_prompt "Post.transaction { Post.create; raise }" write_prompt "Post.count", "=> 0" - ensure - kill pid if pid + @master.puts "quit" end end diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index bc794e1602..83104acf3c 100644 --- a/railties/test/application/initializers/frameworks_test.rb +++ b/railties/test/application/initializers/frameworks_test.rb @@ -41,7 +41,7 @@ module ApplicationTests test "allows me to configure default url options for ActionMailer" do app_file "config/environments/development.rb", <<-RUBY - AppTemplate::Application.configure do + Rails.application.configure do config.action_mailer.default_url_options = { :host => "test.rails" } end RUBY @@ -52,7 +52,7 @@ module ApplicationTests test "does not include url helpers as action methods" do app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get "/foo", :to => lambda { |env| [200, {}, []] }, :as => :foo end RUBY @@ -115,7 +115,7 @@ module ApplicationTests RUBY app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get "/:controller(/:action)" end RUBY @@ -182,7 +182,7 @@ module ApplicationTests end require "#{app_path}/config/environment" ActiveRecord::Base.connection.drop_table("posts") # force drop posts table for test. - assert ActiveRecord::Base.connection.schema_cache.tables["posts"] + assert ActiveRecord::Base.connection.schema_cache.tables("posts") end test "expire schema cache dump" do @@ -192,7 +192,7 @@ module ApplicationTests end silence_warnings { require "#{app_path}/config/environment" - assert !ActiveRecord::Base.connection.schema_cache.tables["posts"] + assert !ActiveRecord::Base.connection.schema_cache.tables("posts") } end diff --git a/railties/test/application/initializers/i18n_test.rb b/railties/test/application/initializers/i18n_test.rb index 489b7ddb92..97df073ec7 100644 --- a/railties/test/application/initializers/i18n_test.rb +++ b/railties/test/application/initializers/i18n_test.rb @@ -45,7 +45,7 @@ module ApplicationTests end # Load paths - test "no config locales dir present should return empty load path" do + test "no config locales directory present should return empty load path" do FileUtils.rm_rf "#{app_path}/config/locales" load_app assert_equal [], Rails.application.config.i18n.load_path @@ -84,7 +84,7 @@ en: RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get '/i18n', :to => lambda { |env| [200, {}, [Foo.instance_variable_get('@foo')]] } end RUBY @@ -108,7 +108,7 @@ en: YAML app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get '/i18n', :to => lambda { |env| [200, {}, [I18n.t(:foo)]] } end RUBY diff --git a/railties/test/application/initializers/load_path_test.rb b/railties/test/application/initializers/load_path_test.rb index 31811e7f92..b36628ee37 100644 --- a/railties/test/application/initializers/load_path_test.rb +++ b/railties/test/application/initializers/load_path_test.rb @@ -23,7 +23,7 @@ module ApplicationTests assert $:.include?("#{app_path}/app/models") end - test "initializing an application allows to load code on lib path inside application class definitation" do + test "initializing an application allows to load code on lib path inside application class definition" do app_file "lib/foo.rb", <<-RUBY module Foo; end RUBY @@ -72,9 +72,10 @@ module ApplicationTests end test "load environment with global" do + $initialize_test_set_from_env = nil app_file "config/environments/development.rb", <<-RUBY $initialize_test_set_from_env = 'success' - AppTemplate::Application.configure do + Rails.application.configure do config.cache_classes = true config.time_zone = "Brasilia" end @@ -88,8 +89,8 @@ module ApplicationTests require "#{app_path}/config/environment" assert_equal "success", $initialize_test_set_from_env - assert AppTemplate::Application.config.cache_classes - assert_equal "Brasilia", AppTemplate::Application.config.time_zone + assert Rails.application.config.cache_classes + assert_equal "Brasilia", Rails.application.config.time_zone end end end diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb index ad7172c514..4f30f30f95 100644 --- a/railties/test/application/loading_test.rb +++ b/railties/test/application/loading_test.rb @@ -36,7 +36,7 @@ class LoadingTest < ActiveSupport::TestCase test "models without table do not panic on scope definitions when loaded" do app_file "app/models/user.rb", <<-MODEL class User < ActiveRecord::Base - default_scope where(published: true) + default_scope { where(published: true) } end MODEL @@ -48,7 +48,7 @@ class LoadingTest < ActiveSupport::TestCase test "load config/environments/environment before Bootstrap initializers" do app_file "config/environments/development.rb", <<-RUBY - AppTemplate::Application.configure do + Rails.application.configure do config.development_environment_loaded = true end RUBY @@ -60,7 +60,7 @@ class LoadingTest < ActiveSupport::TestCase RUBY require "#{app_path}/config/environment" - assert ::AppTemplate::Application.config.loaded + assert ::Rails.application.config.loaded end test "descendants loaded after framework initialization are cleaned on each request without cache classes" do @@ -75,7 +75,7 @@ class LoadingTest < ActiveSupport::TestCase MODEL app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get '/load', to: lambda { |env| [200, {}, Post.all] } get '/unload', to: lambda { |env| [200, {}, []] } end @@ -96,7 +96,7 @@ class LoadingTest < ActiveSupport::TestCase test "initialize cant be called twice" do require "#{app_path}/config/environment" - assert_raise(RuntimeError) { ::AppTemplate::Application.initialize! } + assert_raise(RuntimeError) { Rails.application.initialize! } end test "reload constants on development" do @@ -105,7 +105,7 @@ class LoadingTest < ActiveSupport::TestCase RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get '/c', to: lambda { |env| [200, {"Content-Type" => "text/plain"}, [User.counter.to_s]] } end RUBY @@ -144,7 +144,7 @@ class LoadingTest < ActiveSupport::TestCase RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get '/c', to: lambda { |env| [200, {"Content-Type" => "text/plain"}, [User.counter.to_s]] } end RUBY @@ -179,8 +179,8 @@ class LoadingTest < ActiveSupport::TestCase RUBY app_file 'config/routes.rb', <<-RUBY - $counter = 0 - AppTemplate::Application.routes.draw do + $counter ||= 0 + Rails.application.routes.draw do get '/c', to: lambda { |env| User; [200, {"Content-Type" => "text/plain"}, [$counter.to_s]] } end RUBY @@ -205,13 +205,46 @@ class LoadingTest < ActiveSupport::TestCase assert_equal "2", last_response.body end + test "dependencies reloading is followed by routes reloading" do + add_to_config <<-RUBY + config.cache_classes = false + RUBY + + app_file 'config/routes.rb', <<-RUBY + $counter ||= 1 + $counter *= 2 + Rails.application.routes.draw do + get '/c', to: lambda { |env| User; [200, {"Content-Type" => "text/plain"}, [$counter.to_s]] } + end + RUBY + + app_file "app/models/user.rb", <<-MODEL + class User + $counter += 1 + end + MODEL + + require 'rack/test' + extend Rack::Test::Methods + + require "#{rails_root}/config/environment" + + get "/c" + assert_equal "3", last_response.body + + app_file "db/schema.rb", "" + + get "/c" + assert_equal "7", last_response.body + end + test "columns migrations also trigger reloading" do add_to_config <<-RUBY config.cache_classes = false RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get '/title', to: lambda { |env| [200, {"Content-Type" => "text/plain"}, [Post.new.title]] } get '/body', to: lambda { |env| [200, {"Content-Type" => "text/plain"}, [Post.new.body]] } end @@ -270,7 +303,7 @@ class LoadingTest < ActiveSupport::TestCase RUBY app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get "/:controller(/:action)" end RUBY @@ -288,10 +321,10 @@ class LoadingTest < ActiveSupport::TestCase require "#{app_path}/config/application" assert !Rails.initialized? - assert !AppTemplate::Application.initialized? + assert !Rails.application.initialized? Rails.initialize! assert Rails.initialized? - assert AppTemplate::Application.initialized? + assert Rails.application.initialized? end protected diff --git a/railties/test/application/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb index b8e0c9be60..b4db840e68 100644 --- a/railties/test/application/middleware/cache_test.rb +++ b/railties/test/application/middleware/cache_test.rb @@ -45,7 +45,7 @@ module ApplicationTests RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get ':controller(/:action)' end RUBY diff --git a/railties/test/application/middleware/cookies_test.rb b/railties/test/application/middleware/cookies_test.rb index 18af7abafc..bbb7627be9 100644 --- a/railties/test/application/middleware/cookies_test.rb +++ b/railties/test/application/middleware/cookies_test.rb @@ -33,7 +33,7 @@ module ApplicationTests assert_equal false, ActionDispatch::Cookies::CookieJar.always_write_cookie end - test 'always_write_cookie can be overrided' do + test 'always_write_cookie can be overridden' do add_to_config <<-RUBY config.action_dispatch.always_write_cookie = false RUBY diff --git a/railties/test/application/middleware/remote_ip_test.rb b/railties/test/application/middleware/remote_ip_test.rb index f0d3438aa4..946b82eeb3 100644 --- a/railties/test/application/middleware/remote_ip_test.rb +++ b/railties/test/application/middleware/remote_ip_test.rb @@ -1,5 +1,4 @@ require 'isolation/abstract_unit' -# FIXME remove DummyKeyGenerator and this require in 4.1 require 'active_support/key_generator' module ApplicationTests @@ -10,7 +9,7 @@ module ApplicationTests remote_ip = nil env = Rack::MockRequest.env_for("/").merge(env).merge!( 'action_dispatch.show_exceptions' => false, - 'action_dispatch.key_generator' => ActiveSupport::DummyKeyGenerator.new('b3c631c314c0bbca50c1b2843150fe33') + 'action_dispatch.key_generator' => ActiveSupport::LegacyKeyGenerator.new('b3c631c314c0bbca50c1b2843150fe33') ) endpoint = Proc.new do |e| @@ -34,6 +33,16 @@ module ApplicationTests end end + test "works with both headers individually" do + make_basic_app + assert_nothing_raised(ActionDispatch::RemoteIp::IpSpoofAttackError) do + assert_equal "1.1.1.1", remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1") + end + assert_nothing_raised(ActionDispatch::RemoteIp::IpSpoofAttackError) do + assert_equal "1.1.1.2", remote_ip("HTTP_CLIENT_IP" => "1.1.1.2") + end + end + test "can disable IP spoofing check" do make_basic_app do |app| app.config.action_dispatch.ip_spoofing_check = false diff --git a/railties/test/application/middleware/session_test.rb b/railties/test/application/middleware/session_test.rb index a5fdfbf887..14a56176f5 100644 --- a/railties/test/application/middleware/session_test.rb +++ b/railties/test/application/middleware/session_test.rb @@ -49,7 +49,7 @@ module ApplicationTests test "session is empty and isn't saved on unverified request when using :null_session protect method" do app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get ':controller(/:action)' post ':controller(/:action)' end @@ -90,7 +90,7 @@ module ApplicationTests test "cookie jar is empty and isn't saved on unverified request when using :null_session protect method" do app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get ':controller(/:action)' post ':controller(/:action)' end @@ -131,7 +131,7 @@ module ApplicationTests test "session using encrypted cookie store" do app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get ':controller(/:action)' end RUBY @@ -157,10 +157,6 @@ module ApplicationTests end RUBY - add_to_config <<-RUBY - config.session_store :encrypted_cookie_store, key: '_myapp_session' - RUBY - require "#{app_path}/config/environment" get '/foo/write_session' @@ -178,9 +174,9 @@ module ApplicationTests assert_equal 1, encryptor.decrypt_and_verify(last_response.body)['foo'] end - test "session using upgrade signature to encryption cookie store works the same way as encrypted cookie store" do + test "session upgrading signature to encryption cookie store works the same way as encrypted cookie store" do app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get ':controller(/:action)' end RUBY @@ -208,7 +204,6 @@ module ApplicationTests add_to_config <<-RUBY config.secret_token = "3b7cd727ee24e8444053437c36cc66c4" - config.session_store :upgrade_signature_to_encryption_cookie_store, key: '_myapp_session' RUBY require "#{app_path}/config/environment" @@ -228,9 +223,9 @@ module ApplicationTests assert_equal 1, encryptor.decrypt_and_verify(last_response.body)['foo'] end - test "session using upgrade signature to encryption cookie store upgrades session to encrypted mode" do + test "session upgrading signature to encryption cookie store upgrades session to encrypted mode" do app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get ':controller(/:action)' end RUBY @@ -264,7 +259,6 @@ module ApplicationTests add_to_config <<-RUBY config.secret_token = "3b7cd727ee24e8444053437c36cc66c4" - config.session_store :upgrade_signature_to_encryption_cookie_store, key: '_myapp_session' RUBY require "#{app_path}/config/environment" @@ -287,5 +281,63 @@ module ApplicationTests get '/foo/read_raw_cookie' assert_equal 2, encryptor.decrypt_and_verify(last_response.body)['foo'] end + + test "session upgrading legacy signed cookies to new signed cookies" do + app_file 'config/routes.rb', <<-RUBY + Rails.application.routes.draw do + get ':controller(/:action)' + end + RUBY + + controller :foo, <<-RUBY + class FooController < ActionController::Base + def write_raw_session + # {"session_id"=>"1965d95720fffc123941bdfb7d2e6870", "foo"=>1} + cookies[:_myapp_session] = "BAh7B0kiD3Nlc3Npb25faWQGOgZFRkkiJTE5NjVkOTU3MjBmZmZjMTIzOTQxYmRmYjdkMmU2ODcwBjsAVEkiCGZvbwY7AEZpBg==--315fb9931921a87ae7421aec96382f0294119749" + render nothing: true + end + + def write_session + session[:foo] = session[:foo] + 1 + render nothing: true + end + + def read_session + render text: session[:foo] + end + + def read_signed_cookie + render text: cookies.signed[:_myapp_session]['foo'] + end + + def read_raw_cookie + render text: cookies[:_myapp_session] + end + end + RUBY + + add_to_config <<-RUBY + config.secret_token = "3b7cd727ee24e8444053437c36cc66c4" + config.secret_key_base = nil + RUBY + + require "#{app_path}/config/environment" + + get '/foo/write_raw_session' + get '/foo/read_session' + assert_equal '1', last_response.body + + get '/foo/write_session' + get '/foo/read_session' + assert_equal '2', last_response.body + + get '/foo/read_signed_cookie' + assert_equal '2', last_response.body + + verifier = ActiveSupport::MessageVerifier.new(app.config.secret_token) + + get '/foo/read_raw_cookie' + assert_equal 2, verifier.verify(last_response.body)['foo'] + end end end diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb index d8076c7151..20d1d76d78 100644 --- a/railties/test/application/middleware_test.rb +++ b/railties/test/application/middleware_test.rb @@ -19,7 +19,7 @@ module ApplicationTests end test "default middleware stack" do - add_to_config "config.action_dispatch.x_sendfile_header = 'X-Sendfile'" + add_to_config "config.active_record.migration_error = :page_load" boot! @@ -37,6 +37,7 @@ module ApplicationTests "ActionDispatch::RemoteIp", "ActionDispatch::Reloader", "ActionDispatch::Callbacks", + "ActiveRecord::Migration::CheckPending", "ActiveRecord::ConnectionAdapters::ConnectionManagement", "ActiveRecord::QueryCache", "ActionDispatch::Cookies", @@ -49,12 +50,6 @@ module ApplicationTests ], middleware end - test "Rack::Sendfile is not included by default" do - boot! - - assert !middleware.include?("Rack::Sendfile"), "Rack::Sendfile is not included in the default stack unless you set config.action_dispatch.x_sendfile_header" - end - test "Rack::Cache is not included by default" do boot! @@ -69,6 +64,14 @@ module ApplicationTests assert_equal "Rack::Cache", middleware.first end + test "ActiveRecord::Migration::CheckPending is present when active_record.migration_error is set to :page_load" do + add_to_config "config.active_record.migration_error = :page_load" + + boot! + + assert middleware.include?("ActiveRecord::Migration::CheckPending") + end + test "ActionDispatch::SSL is present when force_ssl is set" do add_to_config "config.force_ssl = true" boot! @@ -80,7 +83,7 @@ module ApplicationTests add_to_config "config.ssl_options = { host: 'example.com' }" boot! - assert_equal AppTemplate::Application.middleware.first.args, [{host: 'example.com'}] + assert_equal Rails.application.middleware.first.args, [{host: 'example.com'}] end test "removing Active Record omits its middleware" do @@ -88,6 +91,7 @@ module ApplicationTests boot! assert !middleware.include?("ActiveRecord::ConnectionAdapters::ConnectionManagement") assert !middleware.include?("ActiveRecord::QueryCache") + assert !middleware.include?("ActiveRecord::Migration::CheckPending") end test "removes lock if cache classes is set" do @@ -135,24 +139,30 @@ module ApplicationTests end test "insert middleware after" do - add_to_config "config.middleware.insert_after ActionDispatch::Static, Rack::Config" + add_to_config "config.middleware.insert_after Rack::Sendfile, Rack::Config" boot! assert_equal "Rack::Config", middleware.second end + test 'unshift middleware' do + add_to_config 'config.middleware.unshift Rack::Config' + boot! + assert_equal 'Rack::Config', middleware.first + end + test "Rails.cache does not respond to middleware" do add_to_config "config.cache_store = :memory_store" boot! - assert_equal "Rack::Runtime", middleware.third + assert_equal "Rack::Runtime", middleware.fourth end test "Rails.cache does respond to middleware" do boot! - assert_equal "Rack::Runtime", middleware.fourth + assert_equal "Rack::Runtime", middleware.fifth end test "insert middleware before" do - add_to_config "config.middleware.insert_before ActionDispatch::Static, Rack::Config" + add_to_config "config.middleware.insert_before Rack::Sendfile, Rack::Config" boot! assert_equal "Rack::Config", middleware.first end @@ -217,7 +227,7 @@ module ApplicationTests end def middleware - AppTemplate::Application.middleware.map(&:klass).map(&:name) + Rails.application.middleware.map(&:klass).map(&:name) end end end diff --git a/railties/test/application/multiple_applications_test.rb b/railties/test/application/multiple_applications_test.rb new file mode 100644 index 0000000000..5bfea599e0 --- /dev/null +++ b/railties/test/application/multiple_applications_test.rb @@ -0,0 +1,148 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class MultipleApplicationsTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app(initializers: true) + boot_rails + require "#{rails_root}/config/environment" + end + + def teardown + teardown_app + end + + def test_cloning_an_application_makes_a_shallow_copy_of_config + 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" + end + + def test_initialization_of_multiple_copies_of_same_application + application1 = AppTemplate::Application.new + application2 = AppTemplate::Application.new + + assert_not_equal Rails.application.object_id, application1.object_id, "New applications should not be the same as the original application" + assert_not_equal Rails.application.object_id, application2.object_id, "New applications should not be the same as the original application" + end + + def test_initialization_of_application_with_previous_config + application1 = AppTemplate::Application.new(config: Rails.application.config) + application2 = AppTemplate::Application.new + + assert_equal Rails.application.config, application1.config, "Creating a new application while setting an initial config should result in the same config" + assert_not_equal Rails.application.config, application2.config, "New applications without setting an initial config should not have the same config" + end + + def test_initialization_of_application_with_previous_railties + application1 = AppTemplate::Application.new(railties: Rails.application.railties) + application2 = AppTemplate::Application.new + + assert_equal Rails.application.railties, application1.railties + assert_not_equal Rails.application.railties, application2.railties + end + + def test_initialize_new_application_with_all_previous_initialization_variables + application1 = AppTemplate::Application.new( + config: Rails.application.config, + railties: Rails.application.railties, + routes_reloader: Rails.application.routes_reloader, + reloaders: Rails.application.reloaders, + routes: Rails.application.routes, + helpers: Rails.application.helpers, + app_env_config: Rails.application.env_config + ) + + assert_equal Rails.application.config, application1.config + assert_equal Rails.application.railties, application1.railties + assert_equal Rails.application.routes_reloader, application1.routes_reloader + assert_equal Rails.application.reloaders, application1.reloaders + assert_equal Rails.application.routes, application1.routes + assert_equal Rails.application.helpers, application1.helpers + assert_equal Rails.application.env_config, application1.env_config + end + + def test_rake_tasks_defined_on_different_applications_go_to_the_same_class + $run_count = 0 + + application1 = AppTemplate::Application.new + application1.rake_tasks do + $run_count += 1 + end + + application2 = AppTemplate::Application.new + application2.rake_tasks do + $run_count += 1 + end + + require "#{app_path}/config/environment" + + assert_equal 0, $run_count, "The count should stay at zero without any calls to the rake tasks" + require 'rake' + require 'rake/testtask' + require 'rdoc/task' + Rails.application.load_tasks + assert_equal 2, $run_count, "Calling a rake task should result in two increments to the count" + end + + def test_multiple_applications_can_be_initialized + assert_nothing_raised { AppTemplate::Application.new } + end + + def test_initializers_run_on_different_applications_go_to_the_same_class + application1 = AppTemplate::Application.new + $run_count = 0 + + AppTemplate::Application.initializer :init0 do + $run_count += 1 + end + + application1.initializer :init1 do + $run_count += 1 + end + + AppTemplate::Application.new.initializer :init2 do + $run_count += 1 + end + + assert_equal 0, $run_count, "Without loading the initializers, the count should be 0" + + # Set config.eager_load to false so that an eager_load warning doesn't pop up + AppTemplate::Application.new { config.eager_load = false }.initialize! + + assert_equal 3, $run_count, "There should have been three initializers that incremented the count" + end + + def test_runners_run_on_different_applications_go_to_the_same_class + $run_count = 0 + AppTemplate::Application.runner { $run_count += 1 } + AppTemplate::Application.new.runner { $run_count += 1 } + + assert_equal 0, $run_count, "Without loading the runners, the count should be 0" + Rails.application.load_runner + assert_equal 2, $run_count, "There should have been two runners that increment the count" + end + + def test_isolate_namespace_on_an_application + assert_nil Rails.application.railtie_namespace, "Before isolating namespace, the railtie namespace should be nil" + Rails.application.isolate_namespace(AppTemplate) + assert_equal Rails.application.railtie_namespace, AppTemplate, "After isolating namespace, we should have a namespace" + end + + 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" + + assert_equal "a_different_secret_key", app.config.secret_key_base, "The configuration's secret key should be set." + 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 "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 + end +end diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb index 9e711f25bd..4d348c6b4b 100644 --- a/railties/test/application/rake/dbs_test.rb +++ b/railties/test/application/rake/dbs_test.rb @@ -33,12 +33,12 @@ module ApplicationTests Dir.chdir(app_path) do output = `bundle exec rake db:create` assert_equal output, "" - assert File.exists?(expected[:database]) + assert File.exist?(expected[:database]) assert_equal expected[:database], ActiveRecord::Base.connection_config[:database] output = `bundle exec rake db:drop` assert_equal output, "" - assert !File.exists?(expected[:database]) + assert !File.exist?(expected[:database]) end end diff --git a/railties/test/application/rake/notes_test.rb b/railties/test/application/rake/notes_test.rb index 3508f4225a..01d751e822 100644 --- a/railties/test/application/rake/notes_test.rb +++ b/railties/test/application/rake/notes_test.rb @@ -24,6 +24,8 @@ module ApplicationTests app_file "app/assets/javascripts/application.js", "// TODO: note in js" app_file "app/assets/stylesheets/application.css", "// TODO: note in css" app_file "app/assets/stylesheets/application.css.scss", "// TODO: note in scss" + app_file "app/assets/stylesheets/application.css.sass", "// TODO: note in sass" + app_file "app/assets/stylesheets/application.css.less", "// TODO: note in less" app_file "app/controllers/application_controller.rb", 1000.times.map { "" }.join("\n") << "# TODO: note in ruby" app_file "lib/tasks/task.rake", "# TODO: note in rake" @@ -46,9 +48,11 @@ module ApplicationTests assert_match(/note in js/, output) assert_match(/note in css/, output) assert_match(/note in scss/, output) + assert_match(/note in sass/, output) + assert_match(/note in less/, output) assert_match(/note in rake/, output) - assert_equal 9, lines.size + assert_equal 11, lines.size lines.each do |line| assert_equal 4, line[0].size diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb index 09f2ad1209..2169304aa4 100644 --- a/railties/test/application/rake_test.rb +++ b/railties/test/application/rake_test.rb @@ -9,7 +9,6 @@ module ApplicationTests def setup build_app boot_rails - FileUtils.rm_rf("#{app_path}/config/environments") end def teardown @@ -30,11 +29,11 @@ module ApplicationTests app_file "config/environment.rb", <<-RUBY SuperMiddleware = Struct.new(:app) - AppTemplate::Application.configure do + Rails.application.configure do config.middleware.use SuperMiddleware end - AppTemplate::Application.initialize! + Rails.application.initialize! RUBY assert_match("SuperMiddleware", Dir.chdir(app_path){ `rake middleware` }) @@ -56,10 +55,8 @@ module ApplicationTests assert_match "Doing something...", output end - def test_does_not_explode_when_accessing_a_model_with_eager_load + def test_does_not_explode_when_accessing_a_model add_to_config <<-RUBY - config.eager_load = true - rake_tasks do task do_nothing: :environment do Hello.new.world @@ -67,88 +64,72 @@ module ApplicationTests end RUBY - app_file "app/models/hello.rb", <<-RUBY - class Hello - def world - puts "Hello world" + app_file 'app/models/hello.rb', <<-RUBY + class Hello + def world + puts 'Hello world' + end end - end RUBY - output = Dir.chdir(app_path){ `rake do_nothing` } - assert_match "Hello world", output + output = Dir.chdir(app_path) { `rake do_nothing` } + assert_match 'Hello world', output 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` } - end - - def test_rake_test_error_output - Dir.chdir(app_path){ `rake db:migrate` } - - app_file "test/models/one_model_test.rb", <<-RUBY - raise 'models' + def test_should_not_eager_load_model_for_rake + add_to_config <<-RUBY + rake_tasks do + task do_nothing: :environment do + end + end RUBY - app_file "test/controllers/one_controller_test.rb", <<-RUBY - raise 'controllers' + add_to_env_config 'production', <<-RUBY + config.eager_load = true RUBY - app_file "test/integration/one_integration_test.rb", <<-RUBY - raise 'integration' + app_file 'app/models/hello.rb', <<-RUBY + raise 'should not be pre-required for rake even eager_load=true' RUBY - silence_stderr do - output = Dir.chdir(app_path) { `rake test 2>&1` } - assert_match 'models', output - assert_match 'controllers', output - assert_match 'integration', output + Dir.chdir(app_path) do + assert system('rake do_nothing RAILS_ENV=production'), + 'should not be pre-required for rake even eager_load=true' end end - def test_rake_test_uncommitted_always_find_git_in_parent_dir - app_name = File.basename(app_path) - app_dir = File.dirname(app_path) - moved_app_name = app_name + '_moved' - - Dir.chdir(app_dir) do - # Go from "./app/" to "./app/app_moved" - FileUtils.mv(app_name, moved_app_name) - FileUtils.mkdir(app_name) - FileUtils.mv(moved_app_name, app_name) - # Initialize the git repository and start the test. - Dir.chdir(app_name) do - `git init` - Dir.chdir(moved_app_name){ `rake db:migrate` } - silence_stderr { Dir.chdir(moved_app_name) { `rake test:uncommitted` } } - assert_equal 0, $?.exitstatus - 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` } end - def test_rake_test_uncommitted_fails_with_no_scm - Dir.chdir(app_path){ `rake db:migrate` } - Dir.chdir(app_path) do - silence_stderr { `rake test:uncommitted` } - assert_equal 1, $?.exitstatus - end + def test_rake_routes_calls_the_route_inspector + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + get '/cart', to: 'cart#show' + end + RUBY + + output = Dir.chdir(app_path){ `rake routes` } + assert_equal "Prefix Verb URI Pattern Controller#Action\ncart GET /cart(.:format) cart#show\n", output end - def test_rake_routes_calls_the_route_inspector + def test_rake_routes_with_controller_environment app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get '/cart', to: 'cart#show' + get '/basketball', to: 'basketball#index' end RUBY + ENV['CONTROLLER'] = 'cart' output = Dir.chdir(app_path){ `rake routes` } assert_equal "Prefix Verb URI Pattern Controller#Action\ncart GET /cart(.:format) cart#show\n", output end def test_rake_routes_displays_message_when_no_routes_are_defined app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do end RUBY @@ -209,7 +190,7 @@ module ApplicationTests bundle exec rake db:migrate db:test:clone test` end - assert_match(/7 tests, 13 assertions, 0 failures, 0 errors/, output) + assert_match(/7 runs, 13 assertions, 0 failures, 0 errors/, output) assert_no_match(/Errors running/, output) end @@ -219,7 +200,7 @@ module ApplicationTests bundle exec rake db:migrate db:test:clone test` end - assert_match(/7 tests, 13 assertions, 0 failures, 0 errors/, output) + assert_match(/7 runs, 13 assertions, 0 failures, 0 errors/, output) assert_no_match(/Errors running/, output) end @@ -246,7 +227,7 @@ module ApplicationTests # ensure we have a schema_migrations table to dump `bundle exec rake db:migrate db:structure:dump DB_STRUCTURE=db/my_structure.sql` end - assert File.exists?(File.join(app_path, 'db', 'my_structure.sql')) + assert File.exist?(File.join(app_path, 'db', 'my_structure.sql')) end def test_rake_dump_structure_should_be_called_twice_when_migrate_redo @@ -267,24 +248,24 @@ module ApplicationTests rails generate model product name:string; bundle exec rake db:migrate db:schema:cache:dump` end - assert File.exists?(File.join(app_path, 'db', 'schema_cache.dump')) + assert File.exist?(File.join(app_path, 'db', 'schema_cache.dump')) end def test_rake_clear_schema_cache Dir.chdir(app_path) do `bundle exec rake db:schema:cache:dump db:schema:cache:clear` end - assert !File.exists?(File.join(app_path, 'db', 'schema_cache.dump')) + assert !File.exist?(File.join(app_path, 'db', 'schema_cache.dump')) end def test_copy_templates Dir.chdir(app_path) do `bundle exec rake rails:templates:copy` %w(controller mailer scaffold).each do |dir| - assert File.exists?(File.join(app_path, 'lib', 'templates', 'erb', dir)) + assert File.exist?(File.join(app_path, 'lib', 'templates', 'erb', dir)) end %w(controller helper scaffold_controller assets).each do |dir| - assert File.exists?(File.join(app_path, 'lib', 'templates', 'rails', dir)) + assert File.exist?(File.join(app_path, 'lib', 'templates', 'rails', dir)) end end end diff --git a/railties/test/application/rendering_test.rb b/railties/test/application/rendering_test.rb new file mode 100644 index 0000000000..b01febd768 --- /dev/null +++ b/railties/test/application/rendering_test.rb @@ -0,0 +1,45 @@ +require 'isolation/abstract_unit' +require 'rack/test' + +module ApplicationTests + class RoutingTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + include Rack::Test::Methods + + def setup + build_app + boot_rails + end + + def teardown + teardown_app + end + + test "Unknown format falls back to HTML template" do + app_file 'config/routes.rb', <<-RUBY + Rails.application.routes.draw do + get 'pages/:id', to: 'pages#show' + end + RUBY + + app_file 'app/controllers/pages_controller.rb', <<-RUBY + class PagesController < ApplicationController + layout false + + def show + end + end + RUBY + + app_file 'app/views/pages/show.html.erb', <<-RUBY + <%= params[:id] %> + RUBY + + get '/pages/foo' + assert_equal 200, last_response.status + + get '/pages/foo.bar' + assert_equal 200, last_response.status + end + end +end diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb index 22de640236..8576a2b738 100644 --- a/railties/test/application/routing_test.rb +++ b/railties/test/application/routing_test.rb @@ -48,7 +48,7 @@ module ApplicationTests RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do root to: "foo#index" end RUBY @@ -100,7 +100,7 @@ module ApplicationTests RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get ':controller(/:action)' end RUBY @@ -111,7 +111,7 @@ module ApplicationTests test "mount rack app" do app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do mount lambda { |env| [200, {}, [env["PATH_INFO"]]] }, at: "/blog" # The line below is required because mount sometimes # fails when a resource route is added. @@ -141,7 +141,7 @@ module ApplicationTests RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get ':controller(/:action)' end RUBY @@ -173,7 +173,7 @@ module ApplicationTests RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get 'admin/foo', to: 'admin/foo#index' get 'foo', to: 'foo#index' end @@ -188,7 +188,7 @@ module ApplicationTests test "routes appending blocks" do app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get ':controller/:action' end RUBY @@ -205,7 +205,7 @@ module ApplicationTests assert_equal 'WIN', last_response.body app_file 'config/routes.rb', <<-R - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get 'lol' => 'hello#index' end R @@ -229,7 +229,7 @@ module ApplicationTests RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get 'foo', to: 'foo#bar' end RUBY @@ -240,7 +240,7 @@ module ApplicationTests assert_equal 'bar', last_response.body app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get 'foo', to: 'foo#baz' end RUBY @@ -261,7 +261,7 @@ module ApplicationTests end app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get 'foo', to: ::InitializeRackApp end RUBY @@ -277,6 +277,30 @@ module ApplicationTests end end + def test_root_path + app('development') + + controller :foo, <<-RUBY + class FooController < ApplicationController + def index + render :text => "foo" + end + end + RUBY + + app_file 'config/routes.rb', <<-RUBY + Rails.application.routes.draw do + get 'foo', :to => 'foo#index' + root :to => 'foo#index' + end + RUBY + + remove_file 'public/index.html' + + get '/' + assert_equal 'foo', last_response.body + end + test 'routes are added and removed when reloading' do app('development') @@ -297,7 +321,7 @@ module ApplicationTests RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get 'foo', to: 'foo#index' end RUBY @@ -313,7 +337,7 @@ module ApplicationTests end app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get 'foo', to: 'foo#index' get 'bar', to: 'bar#index' end @@ -330,7 +354,7 @@ module ApplicationTests assert_equal '/bar', Rails.application.routes.url_helpers.bar_path app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get 'foo', to: 'foo#index' end RUBY @@ -348,6 +372,51 @@ module ApplicationTests end end + test 'named routes are cleared when reloading' do + app('development') + + controller :foo, <<-RUBY + class FooController < ApplicationController + def index + render text: "foo" + end + end + RUBY + + controller :bar, <<-RUBY + class BarController < ApplicationController + def index + render text: "bar" + end + end + RUBY + + app_file 'config/routes.rb', <<-RUBY + Rails.application.routes.draw do + get ':locale/foo', to: 'foo#index', as: 'foo' + end + RUBY + + get '/en/foo' + assert_equal 'foo', last_response.body + assert_equal '/en/foo', Rails.application.routes.url_helpers.foo_path(:locale => 'en') + + app_file 'config/routes.rb', <<-RUBY + Rails.application.routes.draw do + get ':locale/bar', to: 'bar#index', as: 'foo' + end + RUBY + + Rails.application.reload_routes! + + get '/en/foo' + assert_equal 404, last_response.status + + get '/en/bar' + assert_equal 'bar', last_response.body + assert_equal '/en/bar', Rails.application.routes.url_helpers.foo_path(:locale => 'en') + end + test 'resource routing with irregular inflection' do app_file 'config/initializers/inflection.rb', <<-RUBY ActiveSupport::Inflector.inflections do |inflect| @@ -356,7 +425,7 @@ module ApplicationTests RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do resources :yazilar end RUBY diff --git a/railties/test/application/test_runner_test.rb b/railties/test/application/test_runner_test.rb new file mode 100644 index 0000000000..118f22995e --- /dev/null +++ b/railties/test/application/test_runner_test.rb @@ -0,0 +1,320 @@ +require 'isolation/abstract_unit' +require 'active_support/core_ext/string/strip' + +module ApplicationTests + class TestRunnerTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + ENV['RAILS_ENV'] = nil + create_schema + end + + def teardown + 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' + assert_match "1 runs, 1 assertions, 0 failures", run_test_command("test/models/foo_test.rb") + end + + def test_run_multiple_files + create_test_file :models, 'foo' + create_test_file :models, 'bar' + assert_match "2 runs, 2 assertions, 0 failures", run_test_command("test/models/foo_test.rb test/models/bar_test.rb") + end + + def test_run_file_with_syntax_error + app_file 'test/models/error_test.rb', <<-RUBY + require 'test_helper' + 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 + 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| + assert_match "FooTest", output + assert_match "BarTest", output + assert_match "2 runs, 2 assertions, 0 failures", output + end + end + + def test_run_helpers + 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| + assert_match "FooHelperTest", output + assert_match "BarHelperTest", output + assert_match "2 runs, 2 assertions, 0 failures", output + end + end + + def test_run_units + create_test_file :models, 'foo' + create_test_file :helpers, 'bar_helper' + create_test_file :unit, 'baz_unit' + create_test_file :controllers, 'foobar_controller' + run_test_units_command.tap do |output| + assert_match "FooTest", output + assert_match "BarHelperTest", output + assert_match "BazUnitTest", output + assert_match "3 runs, 3 assertions, 0 failures", output + end + end + + def test_run_controllers + create_test_file :controllers, 'foo_controller' + create_test_file :controllers, 'bar_controller' + create_test_file :models, 'foo' + run_test_controllers_command.tap do |output| + assert_match "FooControllerTest", output + assert_match "BarControllerTest", output + assert_match "2 runs, 2 assertions, 0 failures", output + end + end + + def test_run_mailers + create_test_file :mailers, 'foo_mailer' + create_test_file :mailers, 'bar_mailer' + create_test_file :models, 'foo' + run_test_mailers_command.tap do |output| + assert_match "FooMailerTest", output + assert_match "BarMailerTest", output + assert_match "2 runs, 2 assertions, 0 failures", output + end + end + + def test_run_functionals + create_test_file :mailers, 'foo_mailer' + create_test_file :controllers, 'bar_controller' + create_test_file :functional, 'baz_functional' + create_test_file :models, 'foo' + run_test_functionals_command.tap do |output| + assert_match "FooMailerTest", output + assert_match "BarControllerTest", output + assert_match "BazFunctionalTest", output + assert_match "3 runs, 3 assertions, 0 failures", output + end + end + + def test_run_integration + create_test_file :integration, 'foo_integration' + create_test_file :models, 'foo' + run_test_integration_command.tap do |output| + assert_match "FooIntegration", output + assert_match "1 runs, 1 assertions, 0 failures", output + end + end + + def test_run_all_suites + suites = [:models, :helpers, :unit, :controllers, :mailers, :functional, :integration] + suites.each { |suite| create_test_file suite, "foo_#{suite}" } + run_test_command('') .tap do |output| + suites.each { |suite| assert_match "Foo#{suite.to_s.camelize}Test", output } + assert_match "7 runs, 7 assertions, 0 failures", output + end + end + + def test_run_named_test + app_file 'test/unit/chu_2_koi_test.rb', <<-RUBY + require 'test_helper' + + class Chu2KoiTest < ActiveSupport::TestCase + def test_rikka + puts 'Rikka' + end + + def test_sanae + puts 'Sanae' + end + end + RUBY + + run_test_command('test/unit/chu_2_koi_test.rb test_rikka').tap do |output| + assert_match "Rikka", output + assert_no_match "Sanae", output + end + end + + def test_run_matched_test + app_file 'test/unit/chu_2_koi_test.rb', <<-RUBY + require 'test_helper' + + class Chu2KoiTest < ActiveSupport::TestCase + def test_rikka + puts 'Rikka' + end + + def test_sanae + puts 'Sanae' + end + end + RUBY + + run_test_command('test/unit/chu_2_koi_test.rb /rikka/').tap do |output| + assert_match "Rikka", output + assert_no_match "Sanae", output + end + end + + def test_load_fixtures_when_running_test_suites + create_model_with_fixture + suites = [:models, :helpers, [:units, :unit], :controllers, :mailers, + [:functionals, :functional], :integration] + + suites.each do |suite, directory| + directory ||= suite + create_fixture_test directory + assert_match "3 users", run_task(["test:#{suite}"]) + Dir.chdir(app_path) { FileUtils.rm_f "test/#{directory}" } + end + end + + def test_run_with_model + create_model_with_fixture + create_fixture_test 'models', 'user' + assert_match "3 users", run_task(["test models/user"]) + assert_match "3 users", run_task(["test app/models/user.rb"]) + end + + def test_run_different_environment_using_env_var + app_file 'test/unit/env_test.rb', <<-RUBY + require 'test_helper' + + class EnvTest < ActiveSupport::TestCase + def test_env + puts Rails.env + end + end + RUBY + + ENV['RAILS_ENV'] = 'development' + 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' + + class EnvTest < ActiveSupport::TestCase + def test_env + puts Rails.env + end + end + RUBY + + assert_match env, run_test_command("test/unit/env_test.rb RAILS_ENV=#{env}") + end + + def test_generated_scaffold_works_with_rails_test + create_scaffold + 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 ' '}` } + end + + def run_test_command(arguments = 'test/unit/test_test.rb') + run_task ['test', arguments] + end + %w{ mailers models helpers units controllers functionals integration }.each do |type| + define_method("run_test_#{type}_command") do + run_task ["test:#{type}"] + end + end + + def create_model_with_fixture + script 'generate model user name:string' + + app_file 'test/fixtures/users.yml', <<-YAML.strip_heredoc + vampire: + id: 1 + name: Koyomi Araragi + crab: + id: 2 + name: Senjougahara Hitagi + cat: + id: 3 + name: Tsubasa Hanekawa + YAML + + run_migration + end + + def create_fixture_test(path = :unit, name = 'test') + app_file "test/#{path}/#{name}_test.rb", <<-RUBY + require 'test_helper' + + class #{name.camelize}Test < ActiveSupport::TestCase + def test_fixture + puts "\#{User.count} users (\#{__FILE__})" + end + end + RUBY + end + + def create_schema + app_file 'db/schema.rb', '' + end + + def redirect_stderr(target_stream) + previous_stderr = STDERR.dup + $stderr.reopen(target_stream) + yield + target_stream.rewind + ensure + $stderr = previous_stderr + end + + def create_test_file(path = :unit, name = 'test') + 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 + end + end + RUBY + end + + def create_scaffold + script 'generate scaffold user name:string' + Dir.chdir(app_path) { File.exist?('app/models/user.rb') } + run_migration + end + + def run_migration + Dir.chdir(app_path) { `bundle exec rake db:migrate` } + end + end +end diff --git a/railties/test/application/url_generation_test.rb b/railties/test/application/url_generation_test.rb index 0905757442..efbc853d7b 100644 --- a/railties/test/application/url_generation_test.rb +++ b/railties/test/application/url_generation_test.rb @@ -12,6 +12,7 @@ module ApplicationTests boot_rails require "rails" require "action_controller/railtie" + require "action_view/railtie" class MyApp < Rails::Application config.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4" @@ -20,7 +21,7 @@ module ApplicationTests config.eager_load = false end - MyApp.initialize! + Rails.application.initialize! class ::ApplicationController < ActionController::Base end diff --git a/railties/test/commands/console_test.rb b/railties/test/commands/console_test.rb index 3c784b43be..a34beaedb3 100644 --- a/railties/test/commands/console_test.rb +++ b/railties/test/commands/console_test.rb @@ -114,9 +114,10 @@ class Rails::ConsoleTest < ActiveSupport::TestCase assert_match('dev', options[:environment]) end - private - attr_reader :output + private :output + + private def start(argv = []) rails_console = Rails::Console.new(app, parse_arguments(argv)) diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb index 38fe8ca544..edb92b3aa2 100644 --- a/railties/test/commands/dbconsole_test.rb +++ b/railties/test/commands/dbconsole_test.rb @@ -172,8 +172,10 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase assert_match(/Usage:.*dbconsole/, stdout) end - private attr_reader :aborted, :output + private :aborted, :output + + private def dbconsole @dbconsole ||= Rails::DBConsole.new(nil) diff --git a/railties/test/commands/server_test.rb b/railties/test/commands/server_test.rb index cb57b3c0cd..ba688f1e9e 100644 --- a/railties/test/commands/server_test.rb +++ b/railties/test/commands/server_test.rb @@ -27,16 +27,62 @@ class Rails::ServerTest < ActiveSupport::TestCase end def test_environment_with_rails_env - with_rails_env 'production' do - server = Rails::Server.new - assert_equal 'production', server.options[:environment] + with_rack_env nil do + with_rails_env 'production' do + server = Rails::Server.new + assert_equal 'production', server.options[:environment] + end end end def test_environment_with_rack_env - with_rack_env 'production' do - server = Rails::Server.new - assert_equal 'production', server.options[:environment] + with_rails_env nil do + with_rack_env 'production' do + server = Rails::Server.new + assert_equal 'production', server.options[:environment] + end + end + end + + def test_log_stdout + with_rack_env nil do + with_rails_env nil do + args = [] + options = Rails::Server::Options.new.parse!(args) + assert_equal true, options[:log_stdout] + + args = ["-e", "development"] + options = Rails::Server::Options.new.parse!(args) + assert_equal true, options[:log_stdout] + + args = ["-e", "production"] + options = Rails::Server::Options.new.parse!(args) + assert_equal false, options[:log_stdout] + + with_rack_env 'development' do + args = [] + options = Rails::Server::Options.new.parse!(args) + assert_equal true, options[:log_stdout] + end + + with_rack_env 'production' do + args = [] + options = Rails::Server::Options.new.parse!(args) + assert_equal false, options[:log_stdout] + end + + with_rails_env 'development' do + args = [] + options = Rails::Server::Options.new.parse!(args) + assert_equal true, options[:log_stdout] + end + + with_rails_env 'production' do + args = [] + options = Rails::Server::Options.new.parse!(args) + assert_equal false, options[:log_stdout] + end + end end end end diff --git a/railties/test/env_helpers.rb b/railties/test/env_helpers.rb index 6223c85bbf..330fe150ca 100644 --- a/railties/test/env_helpers.rb +++ b/railties/test/env_helpers.rb @@ -1,7 +1,10 @@ +require 'rails' + module EnvHelpers private def with_rails_env(env) + Rails.instance_variable_set :@_env, nil switch_env 'RAILS_ENV', env do switch_env 'RACK_ENV', nil do yield @@ -10,6 +13,7 @@ module EnvHelpers end def with_rack_env(env) + Rails.instance_variable_set :@_env, nil switch_env 'RACK_ENV', env do switch_env 'RAILS_ENV', nil do yield diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb index f8fa8ee153..0db40c1d32 100644 --- a/railties/test/generators/actions_test.rb +++ b/railties/test/generators/actions_test.rb @@ -103,7 +103,7 @@ class ActionsTest < Rails::Generators::TestCase run_generator autoload_paths = 'config.autoload_paths += %w["#{Rails.root}/app/extras"]' action :environment, autoload_paths, env: 'development' - assert_file "config/environments/development.rb", /Application\.configure do\n #{Regexp.escape(autoload_paths)}/ + assert_file "config/environments/development.rb", /Rails\.application\.configure do\n #{Regexp.escape(autoload_paths)}/ end def test_environment_with_block_should_include_block_contents_in_environment_initializer_block diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 0697035871..39d4acb7b2 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -4,6 +4,7 @@ require 'generators/shared_generator_tests' DEFAULT_APP_FILES = %w( .gitignore + README.rdoc Gemfile Rakefile config.ru @@ -53,9 +54,10 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_assets run_generator - assert_file "app/views/layouts/application.html.erb", /stylesheet_link_tag\s+"application"/ - assert_file "app/views/layouts/application.html.erb", /javascript_include_tag\s+"application"/ - assert_file "app/assets/stylesheets/application.css" + + assert_file("app/views/layouts/application.html.erb", /stylesheet_link_tag\s+"application", media: "all", "data-turbolinks-track" => true/) + assert_file("app/views/layouts/application.html.erb", /javascript_include_tag\s+"application", "data-turbolinks-track" => true/) + assert_file("app/assets/stylesheets/application.css") end def test_invalid_application_name_raises_an_error @@ -65,7 +67,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_invalid_application_name_is_fixed run_generator [File.join(destination_root, "things-43")] - assert_file "things-43/config/environment.rb", /Things43::Application\.initialize!/ + assert_file "things-43/config/environment.rb", /Rails\.application\.initialize!/ assert_file "things-43/config/application.rb", /^module Things43$/ end @@ -111,7 +113,7 @@ class AppGeneratorTest < Rails::Generators::TestCase destination_root: app_moved_root, shell: @shell generator.send(:app_const) quietly { generator.send(:create_config_files) } - assert_file "myapp_moved/config/environment.rb", /Myapp::Application\.initialize!/ + assert_file "myapp_moved/config/environment.rb", /Rails\.application\.initialize!/ assert_file "myapp_moved/config/initializers/session_store.rb", /_myapp_session/ end @@ -131,7 +133,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_application_names_are_not_singularized run_generator [File.join(destination_root, "hats")] - assert_file "hats/config/environment.rb", /Hats::Application\.initialize!/ + assert_file "hats/config/environment.rb", /Rails\.application\.initialize!/ end def test_gemfile_has_no_whitespace_errors @@ -183,9 +185,6 @@ class AppGeneratorTest < Rails::Generators::TestCase run_generator([destination_root, "-d", "jdbcmysql"]) assert_file "config/database.yml", /mysql/ assert_gem "activerecord-jdbcmysql-adapter" - # TODO: When the JRuby guys merge jruby-openssl in - # jruby this will be removed - assert_gem "jruby-openssl" if defined?(JRUBY_VERSION) end def test_config_jdbcsqlite3_database @@ -224,6 +223,11 @@ class AppGeneratorTest < Rails::Generators::TestCase end end + def test_generator_if_skip_action_view_is_given + run_generator [destination_root, "--skip-action-view"] + assert_file "config/application.rb", /#\s+require\s+["']action_view\/railtie["']/ + end + def test_generator_if_skip_sprockets_is_given run_generator [destination_root, "--skip-sprockets"] assert_file "config/application.rb" do |content| @@ -232,8 +236,8 @@ class AppGeneratorTest < Rails::Generators::TestCase end assert_file "Gemfile" do |content| assert_no_match(/sass-rails/, content) - assert_no_match(/coffee-rails/, content) assert_no_match(/uglifier/, content) + assert_match(/coffee-rails/, content) end assert_file "config/environments/development.rb" do |content| assert_no_match(/config\.assets\.debug = true/, content) @@ -251,7 +255,7 @@ class AppGeneratorTest < Rails::Generators::TestCase if defined?(JRUBY_VERSION) assert_gem "therubyrhino" else - assert_file "Gemfile", /# gem\s+["']therubyracer["']+, platforms: :ruby$/ + assert_file "Gemfile", /# gem\s+["']therubyracer["']+, \s+platforms: :ruby$/ end end @@ -260,6 +264,11 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file 'test' end + def test_creation_of_app_assets_images_directory + run_generator + assert_file "app/assets/images" + end + def test_creation_of_vendor_assets_javascripts_directory run_generator assert_file "vendor/assets/javascripts" @@ -276,7 +285,7 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_match %r{^//= require jquery}, contents assert_match %r{^//= require jquery_ujs}, contents end - assert_gem "jquery-rails" + assert_file "Gemfile", /^gem 'jquery-rails'/ end def test_other_javascript_libraries @@ -290,16 +299,40 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_javascript_is_skipped_if_required run_generator [destination_root, "--skip-javascript"] - assert_file "app/assets/javascripts/application.js" do |contents| - assert_no_match %r{^//=\s+require\s}, contents + + assert_no_file "app/assets/javascripts" + assert_no_file "vendor/assets/javascripts" + + assert_file "app/views/layouts/application.html.erb" do |contents| + assert_match(/stylesheet_link_tag\s+"application", media: "all" %>/, contents) + assert_no_match(/javascript_include_tag\s+"application" \%>/, contents) + end + + assert_file "Gemfile" do |content| + assert_no_match(/coffee-rails/, content) end end + def test_inclusion_of_web_console + run_generator + assert_file "Gemfile", /gem 'web-console', \s+group: :development/ + end + + def test_inclusion_of_jbuilder + run_generator + assert_file "Gemfile", /gem 'jbuilder'/ + end + def test_inclusion_of_debugger run_generator assert_file "Gemfile", /# gem 'debugger'/ end + def test_inclusion_of_lazy_loaded_sdoc + run_generator + assert_file 'Gemfile', /gem 'sdoc', \s+group: :doc, require: false/ + end + def test_template_from_dir_pwd FileUtils.cd(Rails.root) assert_match(/It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"])) @@ -338,7 +371,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_new_hash_style run_generator [destination_root] assert_file "config/initializers/session_store.rb" do |file| - assert_match(/config.session_store :encrypted_cookie_store, key: '_.+_session'/, file) + assert_match(/config.session_store :cookie_store, key: '_.+_session'/, file) end end @@ -347,6 +380,16 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_no_match(/run bundle install/, output) end + def test_application_name_with_spaces + path = File.join(destination_root, "foo bar".shellescape) + + # This also applies to MySQL apps but not with SQLite + run_generator [path, "-d", 'postgresql'] + + assert_file "foo bar/config/database.yml", /database: foo_bar_development/ + assert_file "foo bar/config/initializers/session_store.rb", /key: '_foo_bar/ + end + protected def action(*args, &block) diff --git a/railties/test/generators/argv_scrubber_test.rb b/railties/test/generators/argv_scrubber_test.rb new file mode 100644 index 0000000000..a94350cbd7 --- /dev/null +++ b/railties/test/generators/argv_scrubber_test.rb @@ -0,0 +1,136 @@ +require 'active_support/test_case' +require 'active_support/testing/autorun' +require 'rails/generators/rails/app/app_generator' +require 'tempfile' + +module Rails + module Generators + class ARGVScrubberTest < ActiveSupport::TestCase # :nodoc: + # Future people who read this... These tests are just to surround the + # current behavior of the ARGVScrubber, they do not mean that the class + # *must* act this way, I just want to prevent regressions. + + def test_version + ['-v', '--version'].each do |str| + scrubber = ARGVScrubber.new [str] + output = nil + exit_code = nil + scrubber.extend(Module.new { + define_method(:puts) { |str| output = str } + define_method(:exit) { |code| exit_code = code } + }) + scrubber.prepare! + assert_equal "Rails #{Rails::VERSION::STRING}", output + assert_equal 0, exit_code + end + end + + def test_default_help + argv = ['zomg', 'how', 'are', 'you'] + scrubber = ARGVScrubber.new argv + args = scrubber.prepare! + assert_equal ['--help'] + argv.drop(1), args + end + + def test_prepare_returns_args + scrubber = ARGVScrubber.new ['hi mom'] + args = scrubber.prepare! + assert_equal '--help', args.first + end + + def test_no_mutations + scrubber = ARGVScrubber.new ['hi mom'].freeze + args = scrubber.prepare! + assert_equal '--help', args.first + end + + def test_new_command_no_rc + scrubber = Class.new(ARGVScrubber) { + def self.default_rc_file + File.join(Dir.tmpdir, 'whatever') + end + }.new ['new'] + args = scrubber.prepare! + assert_equal [], args + end + + def test_new_homedir_rc + file = Tempfile.new 'myrcfile' + file.puts '--hello-world' + file.flush + + message = nil + scrubber = Class.new(ARGVScrubber) { + define_singleton_method(:default_rc_file) do + file.path + end + define_method(:puts) { |msg| message = msg } + }.new ['new'] + args = scrubber.prepare! + assert_equal ['--hello-world'], args + assert_match 'hello-world', message + assert_match file.path, message + ensure + file.close + file.unlink + end + + def test_rc_whitespace_separated + file = Tempfile.new 'myrcfile' + file.puts '--hello --world' + file.flush + + message = nil + scrubber = Class.new(ARGVScrubber) { + define_method(:puts) { |msg| message = msg } + }.new ['new', "--rc=#{file.path}"] + args = scrubber.prepare! + assert_equal ['--hello', '--world'], args + ensure + file.close + file.unlink + end + + def test_new_rc_option + file = Tempfile.new 'myrcfile' + file.puts '--hello-world' + file.flush + + message = nil + scrubber = Class.new(ARGVScrubber) { + define_method(:puts) { |msg| message = msg } + }.new ['new', "--rc=#{file.path}"] + args = scrubber.prepare! + assert_equal ['--hello-world'], args + assert_match 'hello-world', message + assert_match file.path, message + ensure + file.close + file.unlink + end + + def test_new_rc_option_and_custom_options + file = Tempfile.new 'myrcfile' + file.puts '--hello' + file.puts '--world' + file.flush + + scrubber = Class.new(ARGVScrubber) { + define_method(:puts) { |msg| } + }.new ['new', 'tenderapp', '--love', "--rc=#{file.path}"] + + args = scrubber.prepare! + assert_equal ["tenderapp", "--hello", "--world", "--love"], args + ensure + file.close + file.unlink + end + + def test_no_rc + scrubber = ARGVScrubber.new ['new', '--no-rc'] + args = scrubber.prepare! + assert_equal [], args + end + end + end +end diff --git a/railties/test/generators/controller_generator_test.rb b/railties/test/generators/controller_generator_test.rb index 5205deafd9..9c664a903a 100644 --- a/railties/test/generators/controller_generator_test.rb +++ b/railties/test/generators/controller_generator_test.rb @@ -82,4 +82,9 @@ class ControllerGeneratorTest < Rails::Generators::TestCase assert_instance_method :bar, controller end end + + def test_namespaced_routes_are_created_in_routes + run_generator ["admin/dashboard", "index"] + assert_file "config/routes.rb", /namespace :admin do\n\s+get "dashboard\/index"\n/ + end end diff --git a/railties/test/generators/generator_generator_test.rb b/railties/test/generators/generator_generator_test.rb index f4c975fc18..dcfeaaa8e0 100644 --- a/railties/test/generators/generator_generator_test.rb +++ b/railties/test/generators/generator_generator_test.rb @@ -16,6 +16,9 @@ class GeneratorGeneratorTest < Rails::Generators::TestCase assert_file "lib/generators/awesome/awesome_generator.rb", /class AwesomeGenerator < Rails::Generators::NamedBase/ + assert_file "test/lib/generators/awesome_generator_test.rb", + /class AwesomeGeneratorTest < Rails::Generators::TestCase/, + /require 'generators\/awesome\/awesome_generator'/ end def test_namespaced_generator_skeleton @@ -29,6 +32,9 @@ class GeneratorGeneratorTest < Rails::Generators::TestCase assert_file "lib/generators/rails/awesome/awesome_generator.rb", /class Rails::AwesomeGenerator < Rails::Generators::NamedBase/ + assert_file "test/lib/generators/rails/awesome_generator_test.rb", + /class Rails::AwesomeGeneratorTest < Rails::Generators::TestCase/, + /require 'generators\/rails\/awesome\/awesome_generator'/ end def test_generator_skeleton_is_created_without_file_name_namespace @@ -42,6 +48,9 @@ class GeneratorGeneratorTest < Rails::Generators::TestCase assert_file "lib/generators/awesome_generator.rb", /class AwesomeGenerator < Rails::Generators::NamedBase/ + assert_file "test/lib/generators/awesome_generator_test.rb", + /class AwesomeGeneratorTest < Rails::Generators::TestCase/, + /require 'generators\/awesome_generator'/ end def test_namespaced_generator_skeleton_without_file_name_namespace @@ -55,5 +64,8 @@ class GeneratorGeneratorTest < Rails::Generators::TestCase assert_file "lib/generators/rails/awesome_generator.rb", /class Rails::AwesomeGenerator < Rails::Generators::NamedBase/ + assert_file "test/lib/generators/rails/awesome_generator_test.rb", + /class Rails::AwesomeGeneratorTest < Rails::Generators::TestCase/, + /require 'generators\/rails\/awesome_generator'/ end end diff --git a/railties/test/generators/generator_test.rb b/railties/test/generators/generator_test.rb new file mode 100644 index 0000000000..7871399dd7 --- /dev/null +++ b/railties/test/generators/generator_test.rb @@ -0,0 +1,85 @@ +require 'active_support/test_case' +require 'active_support/testing/autorun' +require 'rails/generators/app_base' + +module Rails + module Generators + class GeneratorTest < ActiveSupport::TestCase + def make_builder_class + Class.new(AppBase) do + add_shared_options_for "application" + + # include a module to get around thor's method_added hook + include(Module.new { + def gemfile_entries; super; end + def invoke_all; super; self; end + def add_gem_entry_filter; super; end + def gemfile_entry(*args); super; end + }) + end + end + + def test_construction + klass = make_builder_class + assert klass.start(['new', 'blah']) + end + + def test_add_gem + klass = make_builder_class + generator = klass.start(['new', 'blah']) + generator.gemfile_entry 'tenderlove' + assert_includes generator.gemfile_entries.map(&:name), 'tenderlove' + end + + def test_add_gem_with_version + klass = make_builder_class + generator = klass.start(['new', 'blah']) + generator.gemfile_entry 'tenderlove', '2.0.0' + assert generator.gemfile_entries.find { |gfe| + gfe.name == 'tenderlove' && gfe.version == '2.0.0' + } + end + + def test_add_github_gem + klass = make_builder_class + generator = klass.start(['new', 'blah']) + generator.gemfile_entry 'tenderlove', github: 'hello world' + assert generator.gemfile_entries.find { |gfe| + gfe.name == 'tenderlove' && gfe.options[:github] == 'hello world' + } + end + + def test_add_path_gem + klass = make_builder_class + generator = klass.start(['new', 'blah']) + generator.gemfile_entry 'tenderlove', path: 'hello world' + assert generator.gemfile_entries.find { |gfe| + gfe.name == 'tenderlove' && gfe.options[:path] == 'hello world' + } + end + + def test_filter + klass = make_builder_class + generator = klass.start(['new', 'blah']) + gems = generator.gemfile_entries + generator.add_gem_entry_filter { |gem| + gem.name != gems.first.name + } + assert_equal gems.drop(1), generator.gemfile_entries + end + + def test_two_filters + klass = make_builder_class + generator = klass.start(['new', 'blah']) + gems = generator.gemfile_entries + generator.add_gem_entry_filter { |gem| + gem.name != gems.first.name + } + generator.add_gem_entry_filter { |gem| + gem.name != gems[1].name + } + assert_equal gems.drop(2), generator.gemfile_entries + end + end + end +end diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb index 7fdd54fc30..32a3d072c9 100644 --- a/railties/test/generators/generators_test_helper.rb +++ b/railties/test/generators/generators_test_helper.rb @@ -16,6 +16,7 @@ Rails.application.load_generators require 'active_record' require 'action_dispatch' +require 'action_view' module GeneratorsTestHelper def self.included(base) diff --git a/railties/test/generators/named_base_test.rb b/railties/test/generators/named_base_test.rb index 2bc2c33a72..ac5cfff229 100644 --- a/railties/test/generators/named_base_test.rb +++ b/railties/test/generators/named_base_test.rb @@ -117,6 +117,25 @@ class NamedBaseTest < Rails::Generators::TestCase assert Rails::Generators.hidden_namespaces.include?('hidden') end + def test_scaffold_plural_names_with_model_name_option + g = generator ['Admin::Foo'], model_name: 'User' + assert_name g, 'user', :singular_name + assert_name g, 'User', :name + assert_name g, 'user', :file_path + assert_name g, 'User', :class_name + assert_name g, 'user', :file_name + assert_name g, 'User', :human_name + assert_name g, 'users', :plural_name + assert_name g, 'user', :i18n_scope + assert_name g, 'users', :table_name + assert_name g, 'Admin::Foos', :controller_name + assert_name g, %w(admin), :controller_class_path + assert_name g, 'Admin::Foos', :controller_class_name + assert_name g, 'admin/foos', :controller_file_path + assert_name g, 'foos', :controller_file_name + assert_name g, 'admin.foos', :controller_i18n_scope + end + protected def assert_name(generator, value, method) diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb index a4d8b3d1b0..e17925ff65 100644 --- a/railties/test/generators/namespaced_generators_test.rb +++ b/railties/test/generators/namespaced_generators_test.rb @@ -44,7 +44,7 @@ class NamespacedControllerGeneratorTest < NamespacedGeneratorTestCase end end - def test_helpr_is_also_namespaced + def test_helper_is_also_namespaced run_generator assert_file "app/helpers/test_app/account_helper.rb", /module TestApp/, / module AccountHelper/ assert_file "test/helpers/test_app/account_helper_test.rb", /module TestApp/, / class AccountHelperTest/ diff --git a/railties/test/generators/plugin_new_generator_test.rb b/railties/test/generators/plugin_generator_test.rb index 34441ef679..068eb66bc6 100644 --- a/railties/test/generators/plugin_new_generator_test.rb +++ b/railties/test/generators/plugin_generator_test.rb @@ -1,5 +1,5 @@ require 'generators/generators_test_helper' -require 'rails/generators/rails/plugin_new/plugin_new_generator' +require 'rails/generators/rails/plugin/plugin_generator' require 'generators/shared_generator_tests' DEFAULT_PLUGIN_FILES = %w( @@ -18,7 +18,7 @@ DEFAULT_PLUGIN_FILES = %w( test/dummy ) -class PluginNewGeneratorTest < Rails::Generators::TestCase +class PluginGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper destination File.join(Rails.root, "tmp/bukkits") arguments [destination_root] @@ -124,7 +124,7 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase run_generator [destination_root, "--skip_active_record"] assert_no_file "test/dummy/config/database.yml" assert_file "test/test_helper.rb" do |contents| - assert_no_match /ActiveRecord/, contents + assert_no_match(/ActiveRecord/, contents) end end @@ -168,14 +168,14 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase run_generator FileUtils.cd destination_root quietly { system 'bundle install' } - assert_match(/1 tests, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test`) + assert_match(/1 runs, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test`) end def test_ensure_that_tests_works_in_full_mode run_generator [destination_root, "--full", "--skip_active_record"] FileUtils.cd destination_root quietly { system 'bundle install' } - assert_match(/1 tests, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test`) + assert_match(/1 runs, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test`) end def test_ensure_that_migration_tasks_work_with_mountable_option @@ -292,7 +292,7 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase assert_no_file "bukkits.gemspec" assert_file "Gemfile" do |contents| assert_no_match('gemspec', contents) - assert_match(/gem "rails", "~> #{Rails::VERSION::STRING}"/, contents) + assert_match(/gem "rails", "~> #{Rails.version}"/, contents) assert_match(/group :development do\n gem "sqlite3"\nend/, contents) assert_no_match(/# gem "jquery-rails"/, contents) end @@ -303,7 +303,7 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase assert_no_file "bukkits.gemspec" assert_file "Gemfile" do |contents| assert_no_match('gemspec', contents) - assert_match(/gem "rails", "~> #{Rails::VERSION::STRING}"/, contents) + assert_match(/gem "rails", "~> #{Rails.version}"/, contents) assert_match(/group :development do\n gem "sqlite3"\nend/, contents) end end diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb index 013cb78252..26e56a162c 100644 --- a/railties/test/generators/scaffold_controller_generator_test.rb +++ b/railties/test/generators/scaffold_controller_generator_test.rb @@ -166,4 +166,13 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase assert_match(/render action: 'new'/, content) end end + + def test_model_name_option + run_generator ["Admin::User", "--model-name=User"] + assert_file "app/controllers/admin/users_controller.rb" do |content| + assert_instance_method :index, content do |m| + assert_match("@users = User.all", m) + end + end + end end diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb index 357f472a3f..524bbde2b7 100644 --- a/railties/test/generators/scaffold_generator_test.rb +++ b/railties/test/generators/scaffold_generator_test.rb @@ -239,13 +239,27 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase assert_file "config/routes.rb", /\.routes\.draw do\s*\|map\|\s*$/ end - def test_scaffold_generator_no_assets + def test_scaffold_generator_no_assets_with_switch_no_assets run_generator [ "posts", "--no-assets" ] - assert_file "app/assets/stylesheets/scaffold.css" + assert_no_file "app/assets/stylesheets/scaffold.css" assert_no_file "app/assets/javascripts/posts.js" assert_no_file "app/assets/stylesheets/posts.css" end + def test_scaffold_generator_no_assets_with_switch_assets_false + run_generator [ "posts", "--assets=false" ] + assert_no_file "app/assets/stylesheets/scaffold.css" + assert_no_file "app/assets/javascripts/posts.js" + assert_no_file "app/assets/stylesheets/posts.css" + end + + def test_scaffold_generator_no_assets_with_switch_resource_route_false + run_generator [ "posts", "--resource-route=false" ] + assert_file "config/routes.rb" do |route| + assert_no_match(/resources :posts$/, route) + end + end + def test_scaffold_generator_no_stylesheets run_generator [ "posts", "--no-stylesheets" ] assert_no_file "app/assets/stylesheets/scaffold.css" @@ -271,4 +285,69 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase end end end + + def test_scaffold_generator_belongs_to + run_generator ["account", "name", "currency:belongs_to"] + + assert_file "app/models/account.rb", /belongs_to :currency/ + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_match(/t\.string :name/, up) + assert_match(/t\.belongs_to :currency/, up) + end + end + + assert_file "app/controllers/accounts_controller.rb" do |content| + assert_instance_method :account_params, content do |m| + assert_match(/permit\(:name, :currency_id\)/, m) + end + end + + assert_file "app/views/accounts/_form.html.erb" do |content| + assert_match(/^\W{4}<%= f\.text_field :name %>/, content) + assert_match(/^\W{4}<%= f\.text_field :currency_id %>/, content) + end + end + + def test_scaffold_generator_password_digest + run_generator ["user", "name", "password:digest"] + + assert_file "app/models/user.rb", /has_secure_password/ + + assert_migration "db/migrate/create_users.rb" do |m| + assert_method :change, m do |up| + assert_match(/t\.string :name/, up) + assert_match(/t\.string :password_digest/, up) + end + end + + assert_file "app/controllers/users_controller.rb" do |content| + assert_instance_method :user_params, content do |m| + assert_match(/permit\(:name, :password, :password_confirmation\)/, m) + end + end + + assert_file "app/views/users/_form.html.erb" do |content| + assert_match(/<%= f\.password_field :password %>/, content) + assert_match(/<%= f\.password_field :password_confirmation %>/, content) + end + + assert_file "app/views/users/index.html.erb" do |content| + assert_no_match(/password/, content) + end + + assert_file "app/views/users/show.html.erb" do |content| + assert_no_match(/password/, content) + end + + assert_file "test/controllers/users_controller_test.rb" do |content| + assert_match(/password: 'secret'/, content) + assert_match(/password_confirmation: 'secret'/, content) + end + + assert_file "test/fixtures/users.yml" do |content| + assert_match(/password_digest: <%= BCrypt::Password.create\('secret'\) %>/, content) + end + end end diff --git a/railties/test/generators/shared_generator_tests.rb b/railties/test/generators/shared_generator_tests.rb index 2724882a23..7184639d23 100644 --- a/railties/test/generators/shared_generator_tests.rb +++ b/railties/test/generators/shared_generator_tests.rb @@ -46,11 +46,6 @@ module SharedGeneratorTests assert_no_file "test" end - def test_options_before_application_name_raises_an_error - content = capture(:stderr){ run_generator(["--pretend", destination_root]) } - assert_match(/Options should be given after the \w+ name. For details run: rails( plugin new)? --help\n/, content) - end - def test_name_collision_raises_an_error reserved_words = %w[application destroy plugin runner test] reserved_words.each do |reserved| @@ -77,9 +72,9 @@ module SharedGeneratorTests end def test_template_raises_an_error_with_invalid_path - content = capture(:stderr){ run_generator([destination_root, "-m", "non/existant/path"]) } + content = capture(:stderr){ run_generator([destination_root, "-m", "non/existent/path"]) } assert_match(/The template \[.*\] could not be loaded/, content) - assert_match(/non\/existant\/path/, content) + assert_match(/non\/existent\/path/, content) end def test_template_is_executed_when_supplied diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index 9953aa929b..eac28badfe 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -15,7 +15,7 @@ class GeneratorsTest < Rails::Generators::TestCase end def test_simple_invoke - assert File.exists?(File.join(@path, 'generators', 'model_generator.rb')) + assert File.exist?(File.join(@path, 'generators', 'model_generator.rb')) TestUnit::Generators::ModelGenerator.expects(:start).with(["Account"], {}) Rails::Generators.invoke("test_unit:model", ["Account"]) end @@ -31,7 +31,7 @@ class GeneratorsTest < Rails::Generators::TestCase end def test_should_give_higher_preference_to_rails_generators - assert File.exists?(File.join(@path, 'generators', 'model_generator.rb')) + assert File.exist?(File.join(@path, 'generators', 'model_generator.rb')) Rails::Generators::ModelGenerator.expects(:start).with(["Account"], {}) warnings = capture(:stderr){ Rails::Generators.invoke :model, ["Account"] } assert warnings.empty? @@ -106,7 +106,7 @@ class GeneratorsTest < Rails::Generators::TestCase def test_rails_generators_help_does_not_include_app_nor_plugin_new output = capture(:stdout){ Rails::Generators.help } assert_no_match(/app/, output) - assert_no_match(/plugin_new/, output) + assert_no_match(/[^:]plugin/, output) end def test_rails_generators_with_others_information @@ -164,7 +164,7 @@ class GeneratorsTest < Rails::Generators::TestCase Rails::Generators.invoke "super_shoulda:model", ["Account"] end - def test_developer_options_are_overwriten_by_user_options + def test_developer_options_are_overwritten_by_user_options Rails::Generators.options[:with_options] = { generate: false } self.class.class_eval(<<-end_eval, __FILE__, __LINE__ + 1) diff --git a/railties/test/initializable_test.rb b/railties/test/initializable_test.rb index 16e259be5d..ed9573453b 100644 --- a/railties/test/initializable_test.rb +++ b/railties/test/initializable_test.rb @@ -20,14 +20,6 @@ module InitializableTests end end - module Word - include Rails::Initializable - - initializer :word do - $word = "bird" - end - end - class Parent include Rails::Initializable @@ -235,4 +227,4 @@ module InitializableTests assert_equal [1, 2, 3, 4], $arr end end -end
\ No newline at end of file +end diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index 68d96bae94..913e2b5e29 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -135,6 +135,7 @@ module TestHelpers def make_basic_app require "rails" require "action_controller/railtie" + require "action_view/railtie" app = Class.new(Rails::Application) app.config.eager_load = false @@ -163,7 +164,7 @@ module TestHelpers RUBY app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get ':controller(/:action)' end RUBY @@ -242,6 +243,12 @@ module TestHelpers end end + def gsub_app_file(path, regexp, *args, &block) + path = "#{app_path}/#{path}" + content = File.read(path).gsub(regexp, *args, &block) + File.open(path, 'wb') { |f| f.write(content) } + end + def remove_file(path) FileUtils.rm_rf "#{app_path}/#{path}" end diff --git a/railties/test/paths_test.rb b/railties/test/paths_test.rb index 12f18b9dbf..ed4559ec6f 100644 --- a/railties/test/paths_test.rb +++ b/railties/test/paths_test.rb @@ -3,7 +3,7 @@ require 'rails/paths' class PathsTest < ActiveSupport::TestCase def setup - File.stubs(:exists?).returns(true) + File.stubs(:exist?).returns(true) @root = Rails::Paths::Root.new("/foo/bar") end @@ -180,7 +180,7 @@ class PathsTest < ActiveSupport::TestCase assert_equal 1, @root.eager_load.select {|p| p == @root["app"].expanded.first }.size end - test "paths added to a eager_load path should be added to the eager_load collection" do + test "paths added to an eager_load path should be added to the eager_load collection" do @root["app"] = "/app" @root["app"].eager_load! @root["app"] << "/app2" diff --git a/railties/test/rack_logger_test.rb b/railties/test/rack_logger_test.rb index 3a9392fd26..6ebd47fff9 100644 --- a/railties/test/rack_logger_test.rb +++ b/railties/test/rack_logger_test.rb @@ -1,3 +1,4 @@ +require 'abstract_unit' require 'active_support/testing/autorun' require 'active_support/test_case' require 'rails/rack/logger' @@ -38,7 +39,7 @@ module Rails def setup @subscriber = Subscriber.new @notifier = ActiveSupport::Notifications.notifier - notifier.subscribe 'action_dispatch.request', subscriber + notifier.subscribe 'request.action_dispatch', subscriber end def teardown @@ -56,11 +57,14 @@ module Rails end def test_notification_on_raise - logger = TestLogger.new { raise } + logger = TestLogger.new do + # using an exception class that is not a StandardError subclass on purpose + raise NotImplementedError + end assert_difference('subscriber.starts.length') do assert_difference('subscriber.finishes.length') do - assert_raises(RuntimeError) do + assert_raises(NotImplementedError) do logger.call 'REQUEST_METHOD' => 'GET' end end diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb index a9b237d0a5..e45a5228a1 100644 --- a/railties/test/rails_info_controller_test.rb +++ b/railties/test/rails_info_controller_test.rb @@ -1,5 +1,7 @@ require 'abstract_unit' +ActionController::Base.superclass.send(:include, ActionView::Layouts) + module ActionController class Base include ActionController::Testing diff --git a/railties/test/rails_info_test.rb b/railties/test/rails_info_test.rb index b9fb071d23..44a5fd1904 100644 --- a/railties/test/rails_info_test.rb +++ b/railties/test/rails_info_test.rb @@ -37,8 +37,13 @@ class InfoTest < ActiveSupport::TestCase assert_property 'Goodbye', 'World' end + def test_rails_version + assert_property 'Rails version', + File.read(File.realpath('../../../RAILS_VERSION', __FILE__)).chomp + end + def test_framework_version - assert_property 'Active Support version', ActiveSupport::VERSION::STRING + assert_property 'Active Support version', ActiveSupport.version.to_s end def test_frameworks_exist diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb index 37d0be107c..3075ffee0d 100644 --- a/railties/test/railties/engine_test.rb +++ b/railties/test/railties/engine_test.rb @@ -90,8 +90,8 @@ module RailtiesTest Dir.chdir(app_path) do output = `bundle exec rake bukkits:install:migrations` - assert File.exists?("#{app_path}/db/migrate/2_create_users.bukkits.rb") - assert File.exists?("#{app_path}/db/migrate/3_add_last_name_to_users.bukkits.rb") + assert File.exist?("#{app_path}/db/migrate/2_create_users.bukkits.rb") + assert File.exist?("#{app_path}/db/migrate/3_add_last_name_to_users.bukkits.rb") assert_match(/Copied migration 2_create_users.bukkits.rb from bukkits/, output) assert_match(/Copied migration 3_add_last_name_to_users.bukkits.rb from bukkits/, output) assert_match(/NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/, output) @@ -105,7 +105,7 @@ module RailtiesTest assert_not_nil bukkits_migration_order, "Expected migration to be skipped" migrations_count = Dir["#{app_path}/db/migrate/*.rb"].length - output = `bundle exec rake railties:install:migrations` + `bundle exec rake railties:install:migrations` assert_equal migrations_count, Dir["#{app_path}/db/migrate/*.rb"].length end @@ -136,7 +136,7 @@ module RailtiesTest Dir.chdir(@plugin.path) do output = `bundle exec rake app:bukkits:install:migrations` - assert File.exists?("#{app_path}/db/migrate/0_add_first_name_to_users.bukkits.rb") + assert File.exist?("#{app_path}/db/migrate/0_add_first_name_to_users.bukkits.rb") assert_match(/Copied migration 0_add_first_name_to_users.bukkits.rb from bukkits/, output) assert_equal 1, Dir["#{app_path}/db/migrate/*.rb"].length end @@ -187,7 +187,7 @@ module RailtiesTest assert_equal "Hello bukkits\n", response[2].body end - test "adds its views to view paths with lower proriority than app ones" do + test "adds its views to view paths with lower priority than app ones" do @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY class BukkitController < ActionController::Base def index @@ -270,7 +270,7 @@ module RailtiesTest RUBY app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get 'foo', :to => 'foo#index' end RUBY @@ -345,7 +345,7 @@ YAML #{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/locale/en.yml #{RAILS_FRAMEWORK_ROOT}/activemodel/lib/active_model/locale/en.yml #{RAILS_FRAMEWORK_ROOT}/activerecord/lib/active_record/locale/en.yml - #{RAILS_FRAMEWORK_ROOT}/actionpack/lib/action_view/locale/en.yml + #{RAILS_FRAMEWORK_ROOT}/actionview/lib/action_view/locale/en.yml #{@plugin.path}/config/locales/en.yml #{app_path}/config/locales/en.yml #{app_path}/app/locales/en.yml @@ -416,11 +416,6 @@ YAML boot_rails end - test "Rails::Engine itself does not respond to config" do - boot_rails - assert !Rails::Engine.respond_to?(:config) - end - test "initializers are executed after application configuration initializers" do @plugin.write "lib/bukkits.rb", <<-RUBY module Bukkits @@ -472,7 +467,7 @@ YAML RUBY app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do mount(Bukkits::Engine => "/bukkits") end RUBY @@ -607,7 +602,7 @@ YAML RUBY app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get "/bar" => "bar#index", as: "bar" mount Bukkits::Engine => "/bukkits", as: "bukkits" end @@ -725,7 +720,7 @@ YAML RUBY app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do mount Bukkits::Engine => "/bukkits", as: "bukkits" end RUBY @@ -769,7 +764,7 @@ YAML RUBY app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do mount Bukkits::Awesome::Engine => "/bukkits", :as => "bukkits" end RUBY @@ -833,7 +828,7 @@ YAML add_to_config "isolate_namespace AppTemplate" app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do end + Rails.application.routes.draw do end RUBY boot_rails @@ -1211,7 +1206,7 @@ YAML RUBY app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do get '/bar' => 'bar#index', :as => 'bar' mount Bukkits::Engine => "/bukkits", :as => "bukkits" end @@ -1241,12 +1236,6 @@ YAML assert_equal '/foo/bukkits/bukkit', last_response.body end - test "engines method is properly deprecated" do - boot_rails - - assert_deprecated { app.railties.engines } - end - private def app Rails.application diff --git a/railties/test/railties/generators_test.rb b/railties/test/railties/generators_test.rb index 0abb2b7578..7348d70c56 100644 --- a/railties/test/railties/generators_test.rb +++ b/railties/test/railties/generators_test.rb @@ -44,7 +44,7 @@ module RailtiesTests Dir.chdir(engine_path) do File.open("Gemfile", "w") do |f| f.write <<-GEMFILE.gsub(/^ {12}/, '') - source "http://rubygems.org" + source "https://rubygems.org" gem 'rails', path: '#{RAILS_FRAMEWORK_ROOT}' gem 'sqlite3' diff --git a/railties/test/railties/mounted_engine_test.rb b/railties/test/railties/mounted_engine_test.rb index 80559a6e36..0ef2ff2e2e 100644 --- a/railties/test/railties/mounted_engine_test.rb +++ b/railties/test/railties/mounted_engine_test.rb @@ -13,9 +13,10 @@ module ApplicationTests @simple_plugin = engine "weblog" @plugin = engine "blog" + @metrics_plugin = engine "metrics" app_file 'config/routes.rb', <<-RUBY - AppTemplate::Application.routes.draw do + Rails.application.routes.draw do mount Weblog::Engine, :at => '/', :as => 'weblog' resources :posts get "/engine_route" => "application_generating#engine_route" @@ -28,6 +29,7 @@ module ApplicationTests scope "/:user", :user => "anonymous" do mount Blog::Engine => "/blog" end + mount Metrics::Engine => "/metrics" root :to => 'main#index' end RUBY @@ -54,6 +56,34 @@ module ApplicationTests end RUBY + @metrics_plugin.write "lib/metrics.rb", <<-RUBY + module Metrics + class Engine < ::Rails::Engine + isolate_namespace(Metrics) + end + end + RUBY + + @metrics_plugin.write "config/routes.rb", <<-RUBY + Metrics::Engine.routes.draw do + get '/generate_blog_route', to: 'generating#generate_blog_route' + get '/generate_blog_route_in_view', to: 'generating#generate_blog_route_in_view' + end + RUBY + + @metrics_plugin.write "app/controllers/metrics/generating_controller.rb", <<-RUBY + module Metrics + class GeneratingController < ActionController::Base + def generate_blog_route + render text: blog.post_path(1) + end + + def generate_blog_route_in_view + render inline: "<%= blog.post_path(1) -%>" + end + end + end + RUBY @plugin.write "app/models/blog/post.rb", <<-RUBY module Blog @@ -201,6 +231,21 @@ module ApplicationTests get "/somone/blog/application_route_in_view" assert_equal "/", last_response.body + # test generating engine's route from other engine + get "/metrics/generate_blog_route" + assert_equal '/anonymous/blog/posts/1', last_response.body + + get "/metrics/generate_blog_route_in_view" + assert_equal '/anonymous/blog/posts/1', last_response.body + + # test generating engine's route from other engine with default_url_options + get "/metrics/generate_blog_route", {}, 'SCRIPT_NAME' => '/foo' + assert_equal '/foo/anonymous/blog/posts/1', last_response.body + + get "/metrics/generate_blog_route_in_view", {}, 'SCRIPT_NAME' => '/foo' + assert_equal '/foo/anonymous/blog/posts/1', last_response.body + + # test generating application's route from engine with default_url_options get "/someone/blog/generate_application_route", {}, 'SCRIPT_NAME' => '/foo' assert_equal "/foo/", last_response.body diff --git a/railties/test/railties/railtie_test.rb b/railties/test/railties/railtie_test.rb index c80b0f63af..4cbd4822be 100644 --- a/railties/test/railties/railtie_test.rb +++ b/railties/test/railties/railtie_test.rb @@ -19,33 +19,26 @@ module RailtiesTest @app ||= Rails.application end - test "Rails::Railtie itself does not respond to config" do - assert !Rails::Railtie.respond_to?(:config) + test "cannot instantiate a Railtie object" do + assert_raise(RuntimeError) { Rails::Railtie.new } end test "Railtie provides railtie_name" do begin class ::FooBarBaz < Rails::Railtie ; end - assert_equal "foo_bar_baz", ::FooBarBaz.railtie_name + assert_equal "foo_bar_baz", FooBarBaz.railtie_name ensure Object.send(:remove_const, :"FooBarBaz") end end - test "railtie_name can be set manualy" do + test "railtie_name can be set manually" do class Foo < Rails::Railtie railtie_name "bar" end assert_equal "bar", Foo.railtie_name end - test "cannot inherit from a railtie" do - class Foo < Rails::Railtie ; end - assert_raise RuntimeError do - class Bar < Foo; end - end - end - test "config is available to railtie" do class Foo < Rails::Railtie ; end assert_nil Foo.config.action_controller.foo @@ -65,7 +58,7 @@ module RailtiesTest config.foo.greetings = "hello" end require "#{app_path}/config/application" - assert_equal "hello", AppTemplate::Application.config.foo.greetings + assert_equal "hello", Rails.application.config.foo.greetings end test "railtie can add to_prepare callbacks" do @@ -103,7 +96,7 @@ module RailtiesTest require 'rake/testtask' require 'rdoc/task' - AppTemplate::Application.load_tasks + Rails.application.load_tasks assert $ran_block end @@ -127,7 +120,7 @@ module RailtiesTest require 'rake/testtask' require 'rdoc/task' - AppTemplate::Application.load_tasks + Rails.application.load_tasks assert $ran_block.include?("my_tie") end @@ -143,7 +136,7 @@ module RailtiesTest require "#{app_path}/config/environment" assert !$ran_block - AppTemplate::Application.load_generators + Rails.application.load_generators assert $ran_block end @@ -159,7 +152,7 @@ module RailtiesTest require "#{app_path}/config/environment" assert !$ran_block - AppTemplate::Application.load_console + Rails.application.load_console assert $ran_block end @@ -175,7 +168,7 @@ module RailtiesTest require "#{app_path}/config/environment" assert !$ran_block - AppTemplate::Application.load_runner + Rails.application.load_runner assert $ran_block end diff --git a/railties/test/test_info_test.rb b/railties/test/test_info_test.rb new file mode 100644 index 0000000000..b9c3a9c0c7 --- /dev/null +++ b/railties/test/test_info_test.rb @@ -0,0 +1,60 @@ +require 'abstract_unit' +require 'rails/test_unit/sub_test_task' + +module Rails + class TestInfoTest < ActiveSupport::TestCase + def test_test_files + info = new_test_info ['test'] + assert_predicate info.files, :empty? + assert_nil info.opts + assert_equal ['test'], info.tasks + end + + def test_with_file + info = new_test_info ['test', __FILE__] + assert_equal [__FILE__], info.files + assert_nil info.opts + assert_equal ['test'], info.tasks + end + + def test_with_opts + info = new_test_info ['test', __FILE__, '/foo/'] + assert_equal [__FILE__], info.files + assert_equal '-n /foo/', info.opts + assert_equal ['test'], info.tasks + end + + def test_with_model_shorthand + info = new_test_info ['test', 'models/foo', '/foo/'] + + def info.test_file?(file) + file == "test/models/foo_test.rb" || super + end + + assert_equal ['test/models/foo_test.rb'], info.files + assert_equal '-n /foo/', info.opts + assert_equal ['test'], info.tasks + end + + def test_with_model_path + info = new_test_info ['test', 'app/models/foo.rb', '/foo/'] + + def info.test_file?(file) + file == "test/models/foo_test.rb" || super + end + + assert_equal ['test/models/foo_test.rb'], info.files + assert_equal '-n /foo/', info.opts + assert_equal ['test'], info.tasks + end + + private + def new_test_info(tasks) + Class.new(TestTask::TestInfo) { + def task_defined?(task) + task == "test" + end + }.new tasks + end + end +end |