diff options
Diffstat (limited to 'railties/test')
67 files changed, 2360 insertions, 1173 deletions
diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb index 1c3f8a701a..29ebdc6511 100644 --- a/railties/test/abstract_unit.rb +++ b/railties/test/abstract_unit.rb @@ -1,11 +1,10 @@ require File.expand_path("../../../load_paths", __FILE__) require 'stringio' -require 'test/unit' +require 'minitest/autorun' require 'fileutils' require 'active_support' -require 'active_support/core_ext/logger' require 'action_controller' require 'rails/all' diff --git a/railties/test/application/asset_debugging_test.rb b/railties/test/application/asset_debugging_test.rb index 1b99af22a4..a2a7f184b8 100644 --- a/railties/test/application/asset_debugging_test.rb +++ b/railties/test/application/asset_debugging_test.rb @@ -2,7 +2,7 @@ require 'isolation/abstract_unit' require 'rack/test' module ApplicationTests - class AssetDebuggingTest < Test::Unit::TestCase + class AssetDebuggingTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation include Rack::Test::Methods diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index dfd950aae3..1469c9af4d 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -4,7 +4,7 @@ require 'active_support/core_ext/kernel/reporting' require 'rack/test' module ApplicationTests - class AssetsTest < Test::Unit::TestCase + class AssetsTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation include Rack::Test::Methods @@ -17,12 +17,14 @@ module ApplicationTests teardown_app end - def app - @app ||= Rails.application + def precompile! + quietly do + Dir.chdir(app_path){ `bundle exec rake assets:precompile` } + end end test "assets routes have higher priority" do - app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();" + 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 @@ -33,12 +35,12 @@ module ApplicationTests require "#{app_path}/config/environment" get "/assets/demo.js" - assert_match "alert()", last_response.body + assert_equal 'a = "/assets/rails.png";', last_response.body.strip end test "assets do not require compressors until it is used" do app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();" - app_file "config/initializers/compile.rb", "Rails.application.config.assets.compile = true" + add_to_env_config "production", "config.assets.compile = true" ENV["RAILS_ENV"] = "production" require "#{app_path}/config/environment" @@ -54,43 +56,58 @@ module ApplicationTests app_file "app/assets/javascripts/foo/application.js", "alert();" ENV["RAILS_ENV"] = nil - capture(:stdout) do - Dir.chdir(app_path){ `bundle exec rake assets:precompile` } - end + precompile! + files = Dir["#{app_path}/public/assets/application-*.js"] + files << Dir["#{app_path}/public/assets/application.js"].first files << Dir["#{app_path}/public/assets/foo/application-*.js"].first + files << Dir["#{app_path}/public/assets/foo/application.js"].first files.each do |file| assert_not_nil file, "Expected application.js asset to be generated, but none found" - assert_equal "alert()", File.read(file) + assert_equal "alert();", File.read(file) end end - test "precompile application.js and application.css and all other files not ending with .js or .css by default" do + test "precompile application.js and application.css and all other non JS/CSS files" do app_file "app/assets/javascripts/application.js", "alert();" app_file "app/assets/stylesheets/application.css", "body{}" + + app_file "app/assets/javascripts/someapplication.js", "alert();" + app_file "app/assets/stylesheets/someapplication.css", "body{}" + app_file "app/assets/javascripts/something.min.js", "alert();" app_file "app/assets/stylesheets/something.min.css", "body{}" + app_file "app/assets/javascripts/something.else.js.erb", "alert();" + app_file "app/assets/stylesheets/something.else.css.erb", "body{}" + images_should_compile = ["a.png", "happyface.png", "happy_face.png", "happy.face.png", - "happy-face.png", "happy.happy_face.png", "happy_happy.face.png", + "happy-face.png", "happy.happy_face.png", "happy_happy.face.png", "happy.happy.face.png", "happy", "happy.face", "-happyface", "-happy.png", "-happy.face.png", "_happyface", "_happy.face.png", "_happy.png"] + images_should_compile.each do |filename| app_file "app/assets/images/#{filename}", "happy" end - capture(:stdout) do - Dir.chdir(app_path){ `bundle exec rake assets:precompile` } - end + precompile! images_should_compile.each do |filename| assert File.exists?("#{app_path}/public/assets/#{filename}") end + assert File.exists?("#{app_path}/public/assets/application.js") assert File.exists?("#{app_path}/public/assets/application.css") + + assert !File.exists?("#{app_path}/public/assets/someapplication.js") + assert !File.exists?("#{app_path}/public/assets/someapplication.css") + assert !File.exists?("#{app_path}/public/assets/something.min.js") assert !File.exists?("#{app_path}/public/assets/something.min.css") + + assert !File.exists?("#{app_path}/public/assets/something.else.js") + assert !File.exists?("#{app_path}/public/assets/something.else.css") end test "asset pipeline should use a Sprockets::Index when config.assets.digest is true" do @@ -109,10 +126,7 @@ module ApplicationTests # digest is default in false, we must enable it for test environment add_to_config "config.assets.digest = true" - capture(:stdout) do - Dir.chdir(app_path){ `bundle exec rake assets:precompile` } - end - + precompile! manifest = "#{app_path}/public/assets/manifest.yml" assets = YAML.load_file(manifest) @@ -126,12 +140,8 @@ module ApplicationTests # digest is default in false, we must enable it for test environment add_to_config "config.assets.digest = true" add_to_config "config.assets.manifest = '#{app_path}/shared'" - FileUtils.mkdir "#{app_path}/shared" - - capture(:stdout) do - Dir.chdir(app_path){ `bundle exec rake assets:precompile` } - end + precompile! manifest = "#{app_path}/shared/manifest.yml" assets = YAML.load_file(manifest) @@ -139,16 +149,13 @@ module ApplicationTests assert_match(/application-([0-z]+)\.css/, assets["application.css"]) end - test "the manifest file should be saved by default in the same assets folder" do app_file "app/assets/javascripts/application.js", "alert();" # digest is default in false, we must enable it for test environment add_to_config "config.assets.digest = true" add_to_config "config.assets.prefix = '/x'" - capture(:stdout) do - Dir.chdir(app_path){ `bundle exec rake assets:precompile` } - end + precompile! manifest = "#{app_path}/public/x/manifest.yml" assets = YAML.load_file(manifest) @@ -160,9 +167,7 @@ module ApplicationTests app_file "app/assets/javascripts/application.js", "alert();" add_to_config "config.assets.digest = false" - capture(:stdout) do - Dir.chdir(app_path){ `bundle exec rake assets:precompile` } - end + precompile! assert File.exists?("#{app_path}/public/assets/application.js") assert File.exists?("#{app_path}/public/assets/application.css") @@ -176,12 +181,11 @@ module ApplicationTests test "assets do not require any assets group gem when manifest file is present" do app_file "app/assets/javascripts/application.js", "alert();" - app_file "config/initializers/serve_static_assets.rb", "Rails.application.config.serve_static_assets = true" + add_to_env_config "production", "config.serve_static_assets = true" ENV["RAILS_ENV"] = "production" - capture(:stdout) do - Dir.chdir(app_path){ `bundle exec rake assets:precompile` } - end + precompile! + manifest = "#{app_path}/public/assets/manifest.yml" assets = YAML.load_file(manifest) asset_path = assets["application.js"] @@ -205,15 +209,15 @@ module ApplicationTests RUBY ENV["RAILS_ENV"] = "production" - capture(:stdout) do - Dir.chdir(app_path){ `bundle exec rake assets:precompile` } - end + precompile! # Create file after of precompile app_file "app/assets/javascripts/app.js", "alert();" require "#{app_path}/config/environment" - class ::PostsController < ActionController::Base ; end + class ::PostsController < ActionController::Base + def show_detailed_exceptions?() true end + end get '/posts' assert_match(/AssetNotPrecompiledError/, last_response.body) @@ -231,9 +235,7 @@ module ApplicationTests RUBY ENV["RAILS_ENV"] = "development" - capture(:stdout) do - Dir.chdir(app_path){ `bundle exec rake assets:precompile` } - end + precompile! # Create file after of precompile app_file "app/assets/javascripts/app.js", "alert();" @@ -246,24 +248,44 @@ module ApplicationTests assert_match(/app.js isn't precompiled/, last_response.body) end - test "precompile appends the md5 hash to files referenced with asset_path and run in the provided RAILS_ENV" do + test "precompile properly refers files referenced with asset_path and and run in the provided RAILS_ENV" do 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_config "config.assets.digest = true" + add_to_env_config "test", "config.assets.digest = true" - # capture(:stdout) do + quietly do Dir.chdir(app_path){ `bundle exec rake assets:precompile RAILS_ENV=test` } - # end + end + file = Dir["#{app_path}/public/assets/application.css"].first + assert_match(/\/assets\/rails\.png/, File.read(file)) file = Dir["#{app_path}/public/assets/application-*.css"].first assert_match(/\/assets\/rails-([0-z]+)\.png/, File.read(file)) end + test "precompile shouldn't use the digests present in manifest.yml" do + app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>" + + ENV["RAILS_ENV"] = "production" + precompile! + + manifest = "#{app_path}/public/assets/manifest.yml" + assets = YAML.load_file(manifest) + asset_path = assets["application.css"] + + app_file "app/assets/images/rails.png", "image changed" + + precompile! + assets = YAML.load_file(manifest) + + assert_not_equal asset_path, assets["application.css"] + end + test "precompile appends the md5 hash to files referenced with asset_path and run in production as default even using RAILS_GROUPS=assets" do app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>" add_to_config "config.assets.compile = true" ENV["RAILS_ENV"] = nil - capture(:stdout) do + quietly do Dir.chdir(app_path){ `bundle exec rake assets:precompile RAILS_GROUPS=assets` } end file = Dir["#{app_path}/public/assets/application-*.css"].first @@ -271,19 +293,16 @@ module ApplicationTests end test "precompile should handle utf8 filenames" do - app_file "app/assets/images/レイルズ.png", "not a image really" - add_to_config "config.assets.precompile = [ /\.png$$/, /application.(css|js)$/ ]" - - capture(:stdout) do - Dir.chdir(app_path){ `bundle exec rake assets:precompile` } - end - - assert File.exists?("#{app_path}/public/assets/レイルズ.png") + filename = "レイルズ.png" + app_file "app/assets/images/#{filename}", "not a image really" + add_to_config "config.assets.precompile = [ /\.png$/, /application.(css|js)$/ ]" - manifest = "#{app_path}/public/assets/manifest.yml" + precompile! + require "#{app_path}/config/environment" - assets = YAML.load_file(manifest) - assert_equal "レイルズ.png", assets["レイルズ.png"] + get "/assets/#{URI.parser.escape(filename)}" + assert_match "not a image really", last_response.body + assert File.exists?("#{app_path}/public/assets/#{filename}") end test "assets are cleaned up properly" do @@ -291,11 +310,11 @@ module ApplicationTests app_file "public/assets/application.css", "a { color: green; }" app_file "public/assets/subdir/broken.png", "not really an image file" - capture(:stdout) do + quietly do Dir.chdir(app_path){ `bundle exec rake assets:clean` } end - files = Dir["#{app_path}/public/assets/**/*", "#{app_path}/tmp/cache/*"] + files = Dir["#{app_path}/public/assets/**/*", "#{app_path}/tmp/cache/assets/*"] assert_equal 0, files.length, "Expected no assets, but found #{files.join(', ')}" end @@ -349,5 +368,154 @@ module ApplicationTests assert_match "alert();", last_response.body assert_equal 200, last_response.status end + + test "assets are concatenated when debug is off and compile is off either if debug_assets param is provided" do + app_with_assets_in_view + + # config.assets.debug and config.assets.compile are false for production environment + ENV["RAILS_ENV"] = "production" + precompile! + + require "#{app_path}/config/environment" + + class ::PostsController < ActionController::Base ; end + + # the debug_assets params isn't used if compile is off + get '/posts?debug_assets=true' + assert_match(/<script src="\/assets\/application-([0-z]+)\.js" type="text\/javascript"><\/script>/, last_response.body) + assert_no_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js" type="text\/javascript"><\/script>/, last_response.body) + end + + test "assets aren't concatened when compile is true is on and debug_assets params is true" do + app_with_assets_in_view + add_to_env_config "production", "config.assets.compile = true" + add_to_env_config "production", "config.assets.allow_debugging = true" + + ENV["RAILS_ENV"] = "production" + require "#{app_path}/config/environment" + + class ::PostsController < ActionController::Base ; end + + get '/posts?debug_assets=true' + assert_match(/<script src="\/assets\/application-([0-z]+)\.js\?body=1" type="text\/javascript"><\/script>/, last_response.body) + assert_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js\?body=1" type="text\/javascript"><\/script>/, last_response.body) + end + + test "assets can access model information when precompiling" 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", "<%= Post.name %>" + + add_to_config "config.assets.digest = false" + precompile! + assert_equal "Post;\n", File.read("#{app_path}/public/assets/application.js") + 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("#{app_path}/public/assets/application.js") + end + + test "initialization on the assets group should set assets_dir" do + require "#{app_path}/config/application" + Rails.application.initialize!(:assets) + assert_not_nil Rails.application.config.action_controller.assets_dir + end + + test "enhancements to assets:precompile should only run once" do + app_file "lib/tasks/enhance.rake", "Rake::Task['assets:precompile'].enhance { puts 'enhancement' }" + output = precompile! + assert_equal 1, output.scan("enhancement").size + end + + test "digested assets are not mistakenly removed" do + app_file "app/assets/application.js", "alert();" + add_to_config "config.assets.compile = true" + add_to_config "config.assets.digest = true" + + quietly do + Dir.chdir(app_path){ `bundle exec rake assets:clean assets:precompile` } + end + + files = Dir["#{app_path}/public/assets/application-*.js"] + assert_equal 1, files.length, "Expected digested application.js asset to be generated, but none found" + end + + test "digested assets are removed from configured path" do + app_file "public/production_assets/application.js", "alert();" + add_to_env_config "production", "config.assets.prefix = 'production_assets'" + + ENV["RAILS_ENV"] = nil + quietly do + Dir.chdir(app_path){ `bundle exec rake assets:clean` } + end + + files = Dir["#{app_path}/public/production_assets/application.js"] + assert_equal 0, files.length, "Expected application.js asset to be removed, but still exists" + end + + test "asset urls should use the request's protocol by default" do + app_with_assets_in_view + add_to_config "config.asset_host = 'example.com'" + require "#{app_path}/config/environment" + class ::PostsController < ActionController::Base; end + + get '/posts', {}, {'HTTPS'=>'off'} + assert_match('src="http://example.com/assets/application.js', last_response.body) + get '/posts', {}, {'HTTPS'=>'on'} + assert_match('src="https://example.com/assets/application.js', last_response.body) + end + + test "asset urls should be protocol-relative if no request is in scope" do + 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'" + precompile! + + assert_match 'src="//example.com/assets/rails.png"', File.read("#{app_path}/public/assets/image_loader.js") + end + + test "asset paths should use RAILS_RELATIVE_URL_ROOT by default" do + ENV["RAILS_RELATIVE_URL_ROOT"] = "/sub/uri" + + app_file "app/assets/javascripts/app.js.erb", 'var src="<%= image_path("rails.png") %>";' + add_to_config "config.assets.precompile = %w{app.js}" + precompile! + + assert_match 'src="/sub/uri/assets/rails.png"', File.read("#{app_path}/public/assets/app.js") + end + + test "assets:cache:clean should clean cache" do + ENV["RAILS_ENV"] = "production" + precompile! + + quietly do + Dir.chdir(app_path){ `bundle exec rake assets:cache:clean` } + end + + require "#{app_path}/config/environment" + assert_equal 0, Dir.entries(Rails.application.assets.cache.cache_path).size - 2 # reject [".", ".."] + end + + private + + def app_with_assets_in_view + app_file "app/assets/javascripts/application.js", "//= require_tree ." + app_file "app/assets/javascripts/xmlhr.js", "function f1() { alert(); }" + app_file "app/views/posts/index.html.erb", "<%= javascript_include_tag 'application' %>" + + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do + match '/posts', :to => "posts#index" + end + RUBY + end end end diff --git a/railties/test/application/build_original_fullpath_test.rb b/railties/test/application/build_original_fullpath_test.rb new file mode 100644 index 0000000000..647ffb097a --- /dev/null +++ b/railties/test/application/build_original_fullpath_test.rb @@ -0,0 +1,27 @@ +require "abstract_unit" + +module ApplicationTests + class BuildOriginalPathTest < ActiveSupport::TestCase + def test_include_original_PATH_info_in_ORIGINAL_FULLPATH + env = { 'PATH_INFO' => '/foo/' } + assert_equal "/foo/", Rails.application.send(:build_original_fullpath, env) + end + + def test_include_SCRIPT_NAME + env = { + 'SCRIPT_NAME' => '/foo', + 'PATH_INFO' => '/bar' + } + + assert_equal "/foo/bar", Rails.application.send(:build_original_fullpath, env) + end + + def test_include_QUERY_STRING + env = { + 'PATH_INFO' => '/foo', + 'QUERY_STRING' => 'bar', + } + assert_equal "/foo?bar", Rails.application.send(:build_original_fullpath, env) + end + end +end diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 448982f9de..ac5ac2b93e 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -1,4 +1,5 @@ require "isolation/abstract_unit" +require 'rack/test' class ::MyMailInterceptor def self.delivering_email(email); email; end @@ -13,8 +14,9 @@ end class ::MyOtherMailObserver < ::MyMailObserver; end module ApplicationTests - class ConfigurationTest < Test::Unit::TestCase + class ConfigurationTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation + include Rack::Test::Methods def new_app File.expand_path("#{app_path}/../new_app") @@ -144,7 +146,7 @@ module ApplicationTests test "frameworks are not preloaded by default" do require "#{app_path}/config/environment" - assert ActionController.autoload?(:RecordIdentifier) + assert ActionController.autoload?(:Caching) end test "frameworks are preloaded with config.preload_frameworks is set" do @@ -154,7 +156,7 @@ module ApplicationTests require "#{app_path}/config/environment" - assert !ActionController.autoload?(:RecordIdentifier) + assert !ActionController.autoload?(:Caching) end test "filter_parameters should be able to set via config.filter_parameters" do @@ -181,20 +183,14 @@ module ApplicationTests assert !$prepared require "#{app_path}/config/environment" - require 'rack/test' - extend Rack::Test::Methods get "/" assert $prepared end def assert_utf8 - if RUBY_VERSION < '1.9' - assert_equal "UTF8", $KCODE - else - assert_equal Encoding::UTF_8, Encoding.default_external - assert_equal Encoding::UTF_8, Encoding.default_internal - end + assert_equal Encoding::UTF_8, Encoding.default_external + assert_equal Encoding::UTF_8, Encoding.default_internal end test "skipping config.encoding still results in 'utf-8' as the default" do @@ -250,6 +246,55 @@ module ApplicationTests assert last_response.body =~ /csrf\-param/ end + test "default method for update can be changed" do + app_file 'app/models/post.rb', <<-RUBY + class Post + extend ActiveModel::Naming + def to_key; [1]; end + def persisted?; true; end + end + RUBY + + app_file 'app/controllers/posts_controller.rb', <<-RUBY + class PostsController < ApplicationController + def show + render :inline => "<%= begin; form_for(Post.new) {}; rescue => e; e.to_s; end %>" + end + + def update + render :text => "update" + end + end + RUBY + + add_to_config <<-RUBY + routes.prepend do + resources :posts + end + RUBY + + require "#{app_path}/config/environment" + + token = "cf50faa3fe97702ca1ae" + PostsController.any_instance.stubs(:form_authenticity_token).returns(token) + params = {:authenticity_token => token} + + get "/posts/1" + assert_match /patch/, last_response.body + + patch "/posts/1", params + assert_match /update/, last_response.body + + patch "/posts/1", params + assert_equal 200, last_response.status + + put "/posts/1", params + assert_match /update/, last_response.body + + put "/posts/1", params + assert_equal 200, last_response.status + end + test "request forgery token param can be changed" do make_basic_app do app.config.action_controller.request_forgery_protection_token = '_xsrf_token_here' @@ -286,6 +331,19 @@ module ApplicationTests assert_equal res, last_response.body # value should be unchanged end + test "sets ActionDispatch.test_app" do + make_basic_app + assert_equal Rails.application, ActionDispatch.test_app + end + + test "sets ActionDispatch::Response.default_charset" do + make_basic_app do |app| + app.config.action_dispatch.default_charset = "utf-16" + end + + assert_equal "utf-16", ActionDispatch::Response.default_charset + end + test "sets all Active Record models to whitelist all attributes by default" do add_to_config <<-RUBY config.active_record.whitelist_attributes = true @@ -306,7 +364,7 @@ module ApplicationTests require "#{app_path}/config/environment" require "mail" - ActionMailer::Base + _ = ActionMailer::Base assert_equal [::MyMailInterceptor], ::Mail.send(:class_variable_get, "@@delivery_interceptors") end @@ -319,7 +377,7 @@ module ApplicationTests require "#{app_path}/config/environment" require "mail" - ActionMailer::Base + _ = ActionMailer::Base assert_equal [::MyMailInterceptor, ::MyOtherMailInterceptor], ::Mail.send(:class_variable_get, "@@delivery_interceptors") end @@ -332,7 +390,7 @@ module ApplicationTests require "#{app_path}/config/environment" require "mail" - ActionMailer::Base + _ = ActionMailer::Base assert_equal [::MyMailObserver], ::Mail.send(:class_variable_get, "@@delivery_notification_observers") end @@ -345,7 +403,7 @@ module ApplicationTests require "#{app_path}/config/environment" require "mail" - ActionMailer::Base + _ = ActionMailer::Base assert_equal [::MyMailObserver, ::MyOtherMailObserver], ::Mail.send(:class_variable_get, "@@delivery_notification_observers") end @@ -474,23 +532,27 @@ module ApplicationTests end RUBY + app_file 'app/controllers/application_controller.rb', <<-RUBY + class ApplicationController < ActionController::Base + protect_from_forgery :with => :reset_session # as we are testing API here + end + RUBY + app_file 'app/controllers/posts_controller.rb', <<-RUBY class PostsController < ApplicationController - def index + def create render :text => params[:post].inspect end end RUBY add_to_config <<-RUBY - routes.append do + routes.prepend do resources :posts end RUBY require "#{app_path}/config/environment" - require "rack/test" - extend Rack::Test::Methods post "/posts.json", '{ "title": "foo", "name": "bar" }', "CONTENT_TYPE" => "application/json" assert_equal '{"title"=>"foo"}', last_response.body @@ -521,9 +583,16 @@ module ApplicationTests make_basic_app assert_respond_to app, :env_config - assert_equal app.env_config['action_dispatch.parameter_filter'], app.config.filter_parameters - assert_equal app.env_config['action_dispatch.secret_token'], app.config.secret_token - assert_equal app.env_config['action_dispatch.show_exceptions'], app.config.action_dispatch.show_exceptions + assert_equal app.env_config['action_dispatch.parameter_filter'], app.config.filter_parameters + assert_equal app.env_config['action_dispatch.secret_token'], app.config.secret_token + assert_equal app.env_config['action_dispatch.show_exceptions'], app.config.action_dispatch.show_exceptions + assert_equal app.env_config['action_dispatch.logger'], Rails.logger + assert_equal app.env_config['action_dispatch.backtrace_cleaner'], Rails.backtrace_cleaner + end + + test "config.colorize_logging default is true" do + make_basic_app + assert app.config.colorize_logging end end end diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb index 1528d5dd87..f372afa51c 100644 --- a/railties/test/application/console_test.rb +++ b/railties/test/application/console_test.rb @@ -1,6 +1,6 @@ require 'isolation/abstract_unit' -class ConsoleTest < Test::Unit::TestCase +class ConsoleTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup @@ -18,16 +18,20 @@ class ConsoleTest < Test::Unit::TestCase Rails.application.load_console end + def irb_context + Object.new.extend(Rails::ConsoleMethods) + end + def test_app_method_should_return_integration_session TestHelpers::Rack.send :remove_method, :app load_environment - console_session = app + console_session = irb_context.app assert_instance_of ActionDispatch::Integration::Session, console_session end def test_new_session_should_return_integration_session load_environment - session = new_session + session = irb_context.new_session assert_instance_of ActionDispatch::Integration::Session, session end @@ -41,7 +45,7 @@ class ConsoleTest < Test::Unit::TestCase ActionDispatch::Reloader.to_prepare { c = 3 } # Hide Reloading... output - silence_stream(STDOUT) { reload! } + silence_stream(STDOUT) { irb_context.reload! } assert_equal 1, a assert_equal 2, b @@ -57,7 +61,6 @@ class ConsoleTest < Test::Unit::TestCase load_environment assert User.new.respond_to?(:name) - assert !User.new.respond_to?(:age) app_file "app/models/user.rb", <<-MODEL class User @@ -66,12 +69,13 @@ class ConsoleTest < Test::Unit::TestCase MODEL assert !User.new.respond_to?(:age) - silence_stream(STDOUT) { reload! } + silence_stream(STDOUT) { irb_context.reload! } assert User.new.respond_to?(:age) end def test_access_to_helpers load_environment + helper = irb_context.helper assert_not_nil helper assert_instance_of ActionView::Base, helper assert_equal 'Once upon a time in a world...', diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb index 4365d00b1f..bf58bb3f74 100644 --- a/railties/test/application/generators_test.rb +++ b/railties/test/application/generators_test.rb @@ -1,7 +1,7 @@ require "isolation/abstract_unit" module ApplicationTests - class GeneratorsTest < Test::Unit::TestCase + class GeneratorsTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup diff --git a/railties/test/application/initializers/boot_test.rb b/railties/test/application/initializers/boot_test.rb index b1e01dc13f..04c46058cb 100644 --- a/railties/test/application/initializers/boot_test.rb +++ b/railties/test/application/initializers/boot_test.rb @@ -1,7 +1,7 @@ require "isolation/abstract_unit" module ApplicationTests - class GemBooting < Test::Unit::TestCase + class GemBooting < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup diff --git a/railties/test/application/initializers/check_ruby_version_test.rb b/railties/test/application/initializers/check_ruby_version_test.rb deleted file mode 100644 index df7e9696a9..0000000000 --- a/railties/test/application/initializers/check_ruby_version_test.rb +++ /dev/null @@ -1,39 +0,0 @@ -require "isolation/abstract_unit" - -module ApplicationTests - class CheckRubyVersionTest < Test::Unit::TestCase - include ActiveSupport::Testing::Isolation - - def setup - build_app - boot_rails - end - - def teardown - teardown_app - end - - test "rails initializes with ruby 1.8.7 or later, except for 1.9.1" do - if RUBY_VERSION < '1.8.7' - assert_rails_does_not_boot - elsif RUBY_VERSION == '1.9.1' - assert_rails_does_not_boot - else - assert_rails_boots - end - end - - def assert_rails_boots - assert_nothing_raised "It appears that rails does not boot" do - require "rails/all" - end - end - - def assert_rails_does_not_boot - $stderr = File.open("/dev/null", "w") - assert_raises(SystemExit) do - require "rails/all" - end - end - end -end diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index 446c85d65a..a08e5b2374 100644 --- a/railties/test/application/initializers/frameworks_test.rb +++ b/railties/test/application/initializers/frameworks_test.rb @@ -1,7 +1,8 @@ require "isolation/abstract_unit" +require 'set' module ApplicationTests - class FrameworksTest < Test::Unit::TestCase + class FrameworksTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup @@ -66,7 +67,7 @@ module ApplicationTests require "#{app_path}/config/environment" assert Foo.method_defined?(:foo_path) assert Foo.method_defined?(:main_app) - assert_equal ["notify"], Foo.action_methods + assert_equal Set.new(["notify"]), Foo.action_methods end test "allows to not load all helpers for controllers" do @@ -136,6 +137,13 @@ module ApplicationTests assert_equal 2, ActionDispatch::Http::URL.tld_length end + test "assignment config.encoding to default_charset" do + charset = 'Shift_JIS' + add_to_config "config.encoding = '#{charset}'" + require "#{app_path}/config/environment" + assert_equal charset, ActionDispatch::Response.default_charset + end + # AS test "if there's no config.active_support.bare, all of ActiveSupport is required" do use_frameworks [] @@ -186,5 +194,26 @@ module ApplicationTests require "#{app_path}/config/environment" assert_nil defined?(ActiveRecord::Base) end + + test "use schema cache dump" do + Dir.chdir(app_path) do + `rails generate model post title:string; + bundle exec rake db:migrate db:schema:cache:dump` + 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"] + end + + test "expire schema cache dump" do + Dir.chdir(app_path) do + `rails generate model post title:string; + bundle exec rake db:migrate db:schema:cache:dump db:rollback` + end + silence_warnings { + require "#{app_path}/config/environment" + assert !ActiveRecord::Base.connection.schema_cache.tables["posts"] + } + end end end diff --git a/railties/test/application/initializers/hooks_test.rb b/railties/test/application/initializers/hooks_test.rb index 8c7726339c..7b3e6844fd 100644 --- a/railties/test/application/initializers/hooks_test.rb +++ b/railties/test/application/initializers/hooks_test.rb @@ -1,7 +1,7 @@ require "isolation/abstract_unit" module ApplicationTests - class InitializersTest < Test::Unit::TestCase + class InitializersTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup diff --git a/railties/test/application/initializers/i18n_test.rb b/railties/test/application/initializers/i18n_test.rb index 8c2c079fb8..abb277dc1d 100644 --- a/railties/test/application/initializers/i18n_test.rb +++ b/railties/test/application/initializers/i18n_test.rb @@ -1,7 +1,7 @@ require "isolation/abstract_unit" module ApplicationTests - class I18nTest < Test::Unit::TestCase + class I18nTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup @@ -120,6 +120,9 @@ en: get "/i18n" assert_equal "1", last_response.body + # Wait a full second so we have time for changes to propagate + sleep(1) + app_file "config/locales/en.yml", <<-YAML en: foo: "2" diff --git a/railties/test/application/initializers/load_path_test.rb b/railties/test/application/initializers/load_path_test.rb index 644b8208a9..31811e7f92 100644 --- a/railties/test/application/initializers/load_path_test.rb +++ b/railties/test/application/initializers/load_path_test.rb @@ -1,7 +1,7 @@ require "isolation/abstract_unit" module ApplicationTests - class LoadPathTest < Test::Unit::TestCase + class LoadPathTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup diff --git a/railties/test/application/initializers/notifications_test.rb b/railties/test/application/initializers/notifications_test.rb index b72c14eaf0..d866a63fe0 100644 --- a/railties/test/application/initializers/notifications_test.rb +++ b/railties/test/application/initializers/notifications_test.rb @@ -1,7 +1,7 @@ require "isolation/abstract_unit" module ApplicationTests - class NotificationsTest < Test::Unit::TestCase + class NotificationsTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb index 47c6fd5c6e..92951e1676 100644 --- a/railties/test/application/loading_test.rb +++ b/railties/test/application/loading_test.rb @@ -1,6 +1,6 @@ require 'isolation/abstract_unit' -class LoadingTest < Test::Unit::TestCase +class LoadingTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup @@ -16,10 +16,11 @@ class LoadingTest < Test::Unit::TestCase @app ||= Rails.application end - def test_constants_in_app_are_autoloaded + test "constants in app are autoloaded" do app_file "app/models/post.rb", <<-MODEL class Post < ActiveRecord::Base validates_acceptance_of :title, :accept => "omg" + attr_accessible :title end MODEL @@ -33,7 +34,7 @@ class LoadingTest < Test::Unit::TestCase assert_equal 'omg', p.title end - def test_models_without_table_do_not_panic_on_scope_definitions_when_loaded + 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) @@ -63,9 +64,10 @@ class LoadingTest < Test::Unit::TestCase assert ::AppTemplate::Application.config.loaded end - def test_descendants_are_cleaned_on_each_request_without_cache_classes + test "descendants loaded after framework initialization are cleaned on each request without cache classes" do add_to_config <<-RUBY config.cache_classes = false + config.reload_classes_only_on_change = false RUBY app_file "app/models/post.rb", <<-MODEL @@ -86,18 +88,213 @@ class LoadingTest < Test::Unit::TestCase require "#{rails_root}/config/environment" setup_ar! - assert_equal [], ActiveRecord::Base.descendants + assert_equal [ActiveRecord::SchemaMigration], ActiveRecord::Base.descendants get "/load" - assert_equal [Post], ActiveRecord::Base.descendants + assert_equal [ActiveRecord::SchemaMigration, Post], ActiveRecord::Base.descendants get "/unload" - assert_equal [], ActiveRecord::Base.descendants + assert_equal [ActiveRecord::SchemaMigration], ActiveRecord::Base.descendants end - test "initialize_cant_be_called_twice" do + test "initialize cant be called twice" do require "#{app_path}/config/environment" assert_raise(RuntimeError) { ::AppTemplate::Application.initialize! } end + test "reload constants on development" do + add_to_config <<-RUBY + config.cache_classes = false + RUBY + + app_file 'config/routes.rb', <<-RUBY + AppTemplate::Application.routes.draw do + match '/c', :to => lambda { |env| [200, {"Content-Type" => "text/plain"}, [User.counter.to_s]] } + end + RUBY + + app_file "app/models/user.rb", <<-MODEL + class User + def self.counter; 1; end + end + MODEL + + require 'rack/test' + extend Rack::Test::Methods + + require "#{rails_root}/config/environment" + + get "/c" + assert_equal "1", last_response.body + + app_file "app/models/user.rb", <<-MODEL + class User + def self.counter; 2; end + end + MODEL + + get "/c" + assert_equal "2", last_response.body + end + + test "does not reload constants on development if custom file watcher always returns false" do + add_to_config <<-RUBY + config.cache_classes = false + config.file_watcher = Class.new do + def initialize(*); end + def updated?; false; end + end + RUBY + + app_file 'config/routes.rb', <<-RUBY + AppTemplate::Application.routes.draw do + match '/c', :to => lambda { |env| [200, {"Content-Type" => "text/plain"}, [User.counter.to_s]] } + end + RUBY + + app_file "app/models/user.rb", <<-MODEL + class User + def self.counter; 1; end + end + MODEL + + require 'rack/test' + extend Rack::Test::Methods + + require "#{rails_root}/config/environment" + + get "/c" + assert_equal "1", last_response.body + + app_file "app/models/user.rb", <<-MODEL + class User + def self.counter; 2; end + end + MODEL + + get "/c" + assert_equal "1", last_response.body + end + + test "added files (like db/schema.rb) also trigger reloading" do + add_to_config <<-RUBY + config.cache_classes = false + RUBY + + app_file 'config/routes.rb', <<-RUBY + $counter = 0 + AppTemplate::Application.routes.draw do + match '/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 "1", last_response.body + + app_file "db/schema.rb", "" + + get "/c" + assert_equal "2", 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 + match '/title', :to => lambda { |env| [200, {"Content-Type" => "text/plain"}, [Post.new.title]] } + match '/body', :to => lambda { |env| [200, {"Content-Type" => "text/plain"}, [Post.new.body]] } + end + RUBY + + app_file "app/models/post.rb", <<-MODEL + class Post < ActiveRecord::Base + end + MODEL + + require 'rack/test' + extend Rack::Test::Methods + + app_file "db/migrate/1_create_posts.rb", <<-MIGRATION + class CreatePosts < ActiveRecord::Migration + def change + create_table :posts do |t| + t.string :title, :default => "TITLE" + end + end + end + MIGRATION + + Dir.chdir(app_path) { `rake db:migrate`} + require "#{rails_root}/config/environment" + + get "/title" + assert_equal "TITLE", last_response.body + + app_file "db/migrate/2_add_body_to_posts.rb", <<-MIGRATION + class AddBodyToPosts < ActiveRecord::Migration + def change + add_column :posts, :body, :text, :default => "BODY" + end + end + MIGRATION + + Dir.chdir(app_path) { `rake db:migrate` } + + get "/body" + assert_equal "BODY", last_response.body + end + + test "AC load hooks can be used with metal" do + app_file "app/controllers/omg_controller.rb", <<-RUBY + begin + class OmgController < ActionController::Metal + ActiveSupport.run_load_hooks(:action_controller, self) + def show + self.response_body = ["OK"] + end + end + rescue => e + puts "Error loading metal: \#{e.class} \#{e.message}" + end + RUBY + + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do + match "/:controller(/:action)" + end + RUBY + + require "#{rails_root}/config/environment" + + require 'rack/test' + extend Rack::Test::Methods + + get '/omg/show' + assert_equal 'OK', last_response.body + end + + def test_initialize_can_be_called_at_any_time + require "#{app_path}/config/application" + + assert !Rails.initialized? + assert !AppTemplate::Application.initialized? + Rails.initialize! + assert Rails.initialized? + assert AppTemplate::Application.initialized? + end + protected def setup_ar! diff --git a/railties/test/application/middleware/best_practices_test.rb b/railties/test/application/middleware/best_practices_test.rb index 1c88b9bf06..f6783c6ca2 100644 --- a/railties/test/application/middleware/best_practices_test.rb +++ b/railties/test/application/middleware/best_practices_test.rb @@ -1,7 +1,7 @@ require 'isolation/abstract_unit' module ApplicationTests - class BestPracticesTest < Test::Unit::TestCase + class BestPracticesTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup diff --git a/railties/test/application/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb index e656ada3c0..561b020707 100644 --- a/railties/test/application/middleware/cache_test.rb +++ b/railties/test/application/middleware/cache_test.rb @@ -1,7 +1,7 @@ require 'isolation/abstract_unit' module ApplicationTests - class RoutingTest < Test::Unit::TestCase + class RoutingTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup @@ -31,6 +31,10 @@ module ApplicationTests $last_modified ||= Time.now.utc render_conditionally(:last_modified => $last_modified) end + + def keeps_if_modified_since + render :text => request.headers['If-Modified-Since'] + end private def render_conditionally(headers) if stale?(headers.merge(:public => !params[:private])) @@ -47,6 +51,16 @@ module ApplicationTests RUBY end + def test_cache_keeps_if_modified_since + simple_controller + expected = "Wed, 30 May 1984 19:43:31 GMT" + + get "/expires/keeps_if_modified_since", {}, "HTTP_IF_MODIFIED_SINCE" => expected + + assert_equal 200, last_response.status + assert_equal expected, last_response.body, "cache should have kept If-Modified-Since" + end + def test_cache_is_disabled_in_dev_mode simple_controller app("development") diff --git a/railties/test/application/middleware/cookies_test.rb b/railties/test/application/middleware/cookies_test.rb new file mode 100644 index 0000000000..18af7abafc --- /dev/null +++ b/railties/test/application/middleware/cookies_test.rb @@ -0,0 +1,47 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class CookiesTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + + def new_app + File.expand_path("#{app_path}/../new_app") + end + + def setup + build_app + boot_rails + FileUtils.rm_rf("#{app_path}/config/environments") + end + + def teardown + teardown_app + FileUtils.rm_rf(new_app) if File.directory?(new_app) + end + + test 'always_write_cookie is true by default in development' do + require 'rails' + Rails.env = 'development' + require "#{app_path}/config/environment" + assert_equal true, ActionDispatch::Cookies::CookieJar.always_write_cookie + end + + test 'always_write_cookie is false by default in production' do + require 'rails' + Rails.env = 'production' + require "#{app_path}/config/environment" + assert_equal false, ActionDispatch::Cookies::CookieJar.always_write_cookie + end + + test 'always_write_cookie can be overrided' do + add_to_config <<-RUBY + config.action_dispatch.always_write_cookie = false + RUBY + + require 'rails' + Rails.env = 'development' + require "#{app_path}/config/environment" + assert_equal false, ActionDispatch::Cookies::CookieJar.always_write_cookie + end + end +end diff --git a/railties/test/application/middleware/exceptions_test.rb b/railties/test/application/middleware/exceptions_test.rb new file mode 100644 index 0000000000..a80898092d --- /dev/null +++ b/railties/test/application/middleware/exceptions_test.rb @@ -0,0 +1,116 @@ +# encoding: utf-8 +require 'isolation/abstract_unit' +require 'rack/test' + +module ApplicationTests + class MiddlewareExceptionsTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + include Rack::Test::Methods + + def setup + build_app + boot_rails + end + + def teardown + teardown_app + end + + test "show exceptions middleware filter backtrace before logging" do + my_middleware = Struct.new(:app) do + def call(env) + raise "Failure" + end + end + + app.config.middleware.use my_middleware + + stringio = StringIO.new + Rails.logger = Logger.new(stringio) + + get "/" + assert_no_match(/action_dispatch/, stringio.string) + end + + test "renders active record exceptions as 404" do + my_middleware = Struct.new(:app) do + def call(env) + raise ActiveRecord::RecordNotFound + end + end + + app.config.middleware.use my_middleware + + get "/" + assert_equal 404, last_response.status + end + + test "uses custom exceptions app" do + add_to_config <<-RUBY + config.exceptions_app = lambda do |env| + [404, { "Content-Type" => "text/plain" }, ["YOU FAILED BRO"]] + end + RUBY + + app.config.action_dispatch.show_exceptions = true + + get "/foo" + assert_equal 404, last_response.status + assert_equal "YOU FAILED BRO", last_response.body + end + + test "unspecified route when action_dispatch.show_exceptions is not set raises an exception" do + app.config.action_dispatch.show_exceptions = false + + assert_raise(ActionController::RoutingError) do + get '/foo' + end + end + + test "unspecified route when action_dispatch.show_exceptions is set shows 404" do + app.config.action_dispatch.show_exceptions = true + + assert_nothing_raised(ActionController::RoutingError) do + get '/foo' + assert_match "The page you were looking for doesn't exist.", last_response.body + end + end + + test "unspecified route when action_dispatch.show_exceptions and consider_all_requests_local are set shows diagnostics" do + app.config.action_dispatch.show_exceptions = true + app.config.consider_all_requests_local = true + + assert_nothing_raised(ActionController::RoutingError) do + get '/foo' + assert_match "No route matches", last_response.body + end + end + + test "displays diagnostics message when exception raised in template that contains UTF-8" do + app.config.action_dispatch.show_exceptions = true + app.config.consider_all_requests_local = true + + controller :foo, <<-RUBY + class FooController < ActionController::Base + def index + end + end + RUBY + + app_file 'app/views/foo/index.html.erb', <<-ERB + <% raise 'boooom' %> + ✓測試テスト시험 + ERB + + app_file 'config/routes.rb', <<-RUBY + AppTemplate::Application.routes.draw do + match ':controller(/:action)' + end + RUBY + + post '/foo', :utf8 => '✓' + assert_match(/boooom/, last_response.body) + assert_match(/測試テスト시험/, last_response.body) + end + end +end diff --git a/railties/test/application/middleware/remote_ip_test.rb b/railties/test/application/middleware/remote_ip_test.rb index da291f061c..066f0c1c84 100644 --- a/railties/test/application/middleware/remote_ip_test.rb +++ b/railties/test/application/middleware/remote_ip_test.rb @@ -1,7 +1,7 @@ require 'isolation/abstract_unit' module ApplicationTests - class RemoteIpTest < Test::Unit::TestCase + class RemoteIpTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup diff --git a/railties/test/application/middleware/sendfile_test.rb b/railties/test/application/middleware/sendfile_test.rb index d2ad2668bb..eb791f5687 100644 --- a/railties/test/application/middleware/sendfile_test.rb +++ b/railties/test/application/middleware/sendfile_test.rb @@ -1,7 +1,7 @@ require 'isolation/abstract_unit' module ApplicationTests - class SendfileTest < Test::Unit::TestCase + class SendfileTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup @@ -57,5 +57,18 @@ module ApplicationTests get "/" assert_equal File.expand_path(__FILE__), last_response.headers["X-Lighttpd-Send-File"] end + + test "files handled by ActionDispatch::Static are handled by Rack::Sendfile" do + make_basic_app do |app| + app.config.action_dispatch.x_sendfile_header = 'X-Sendfile' + app.config.serve_static_assets = true + app.paths["public"] = File.join(rails_root, "public") + end + + app_file "public/foo.txt", "foo" + + get "/foo.txt", "HTTP_X_SENDFILE_TYPE" => "X-Sendfile" + assert_equal File.join(rails_root, "public/foo.txt"), last_response.headers["X-Sendfile"] + end end end diff --git a/railties/test/application/middleware/session_test.rb b/railties/test/application/middleware/session_test.rb new file mode 100644 index 0000000000..f4e77ee244 --- /dev/null +++ b/railties/test/application/middleware/session_test.rb @@ -0,0 +1,30 @@ +# encoding: utf-8 +require 'isolation/abstract_unit' +require 'rack/test' + +module ApplicationTests + class MiddlewareSessionTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + include Rack::Test::Methods + + def setup + build_app + boot_rails + FileUtils.rm_rf "#{app_path}/config/environments" + end + + def teardown + teardown_app + end + + def app + @app ||= Rails.application + end + + test "config.force_ssl sets cookie to secure only" do + add_to_config "config.force_ssl = true" + require "#{app_path}/config/environment" + assert app.config.session_options[:secure], "Expected session to be marked as secure" + end + end +end diff --git a/railties/test/application/middleware/show_exceptions_test.rb b/railties/test/application/middleware/show_exceptions_test.rb deleted file mode 100644 index e3f27f63c3..0000000000 --- a/railties/test/application/middleware/show_exceptions_test.rb +++ /dev/null @@ -1,41 +0,0 @@ -require 'isolation/abstract_unit' - -module ApplicationTests - class ShowExceptionsTest < Test::Unit::TestCase - include ActiveSupport::Testing::Isolation - - def setup - build_app - boot_rails - FileUtils.rm_rf "#{app_path}/config/environments" - end - - def teardown - teardown_app - end - - def app - @app ||= Rails.application - end - - test "unspecified route when set action_dispatch.show_exceptions to false" do - make_basic_app do |app| - app.config.action_dispatch.show_exceptions = false - end - - assert_raise(ActionController::RoutingError) do - get '/foo' - end - end - - test "unspecified route when set action_dispatch.show_exceptions to true" do - make_basic_app do |app| - app.config.action_dispatch.show_exceptions = true - end - - assert_nothing_raised(ActionController::RoutingError) do - get '/foo' - end - end - end -end diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb index bed5ba503f..fc5fb60174 100644 --- a/railties/test/application/middleware_test.rb +++ b/railties/test/application/middleware_test.rb @@ -1,8 +1,9 @@ require 'isolation/abstract_unit' require 'stringio' +require 'rack/test' module ApplicationTests - class MiddlewareTest < Test::Unit::TestCase + class MiddlewareTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup @@ -25,15 +26,17 @@ module ApplicationTests boot! assert_equal [ + "Rack::Sendfile", "ActionDispatch::Static", "Rack::Lock", "ActiveSupport::Cache::Strategy::LocalCache", "Rack::Runtime", "Rack::MethodOverride", + "ActionDispatch::RequestId", "Rails::Rack::Logger", # must come after Rack::MethodOverride to properly log overridden methods "ActionDispatch::ShowExceptions", + "ActionDispatch::DebugExceptions", "ActionDispatch::RemoteIp", - "Rack::Sendfile", "ActionDispatch::Reloader", "ActionDispatch::Callbacks", "ActiveRecord::ConnectionAdapters::ConnectionManagement", @@ -63,10 +66,18 @@ module ApplicationTests assert_equal "Rack::Cache", middleware.first end - test "Rack::SSL is present when force_ssl is set" do + test "ActionDispatch::SSL is present when force_ssl is set" do add_to_config "config.force_ssl = true" boot! - assert middleware.include?("Rack::SSL") + assert middleware.include?("ActionDispatch::SSL") + end + + test "ActionDispatch::SSL is configured with options when given" do + add_to_config "config.force_ssl = true" + add_to_config "config.ssl_options = { :host => 'example.com' }" + boot! + + assert_equal AppTemplate::Application.middleware.first.args, [{:host => 'example.com'}] end test "removing Active Record omits its middleware" do @@ -74,7 +85,6 @@ module ApplicationTests boot! assert !middleware.include?("ActiveRecord::ConnectionAdapters::ConnectionManagement") assert !middleware.include?("ActiveRecord::QueryCache") - assert !middleware.include?("ActiveRecord::IdentityMap::Middleware") end test "removes lock if allow concurrency is set" do @@ -95,10 +105,11 @@ module ApplicationTests assert !middleware.include?("ActionDispatch::Static") end - test "includes show exceptions even action_dispatch.show_exceptions is disabled" do + test "includes exceptions middlewares even if action_dispatch.show_exceptions is disabled" do add_to_config "config.action_dispatch.show_exceptions = false" boot! assert middleware.include?("ActionDispatch::ShowExceptions") + assert middleware.include?("ActionDispatch::DebugExceptions") end test "removes ActionDispatch::Reloader if cache_classes is true" do @@ -120,23 +131,17 @@ module ApplicationTests assert_equal "Rack::Config", middleware.second end - test "RAILS_CACHE does not respond to middleware" do + test "Rails.cache does not respond to middleware" do add_to_config "config.cache_store = :memory_store" boot! assert_equal "Rack::Runtime", middleware.third end - test "RAILS_CACHE does respond to middleware" do + test "Rails.cache does respond to middleware" do boot! assert_equal "Rack::Runtime", middleware.fourth end - test "identity map is inserted" do - add_to_config "config.active_record.identity_map = true" - boot! - assert middleware.include?("ActiveRecord::IdentityMap::Middleware") - end - test "insert middleware before" do add_to_config "config.middleware.insert_before ActionDispatch::Static, Rack::Config" boot! @@ -174,7 +179,6 @@ module ApplicationTests assert_equal etag, last_response.headers["Etag"] get "/?nothing=true" - puts last_response.body assert_equal 200, last_response.status assert_equal "", last_response.body assert_equal "text/html; charset=utf-8", last_response.headers["Content-Type"] @@ -182,24 +186,12 @@ module ApplicationTests assert_equal nil, last_response.headers["Etag"] end - # Show exceptions middleware - test "show exceptions middleware filter backtrace before logging" do - my_middleware = Struct.new(:app) do - def call(env) - raise "Failure" - end - end - - make_basic_app do |app| - app.config.middleware.use my_middleware - end - - stringio = StringIO.new - Rails.logger = Logger.new(stringio) - - env = Rack::MockRequest.env_for("/") + test "ORIGINAL_FULLPATH is passed to env" do + boot! + env = ::Rack::MockRequest.env_for("/foo/?something") Rails.application.call(env) - assert_no_match(/action_dispatch/, stringio.string) + + assert_equal "/foo/?something", env["ORIGINAL_FULLPATH"] end private diff --git a/railties/test/application/paths_test.rb b/railties/test/application/paths_test.rb index 964cff48cd..4029984ce9 100644 --- a/railties/test/application/paths_test.rb +++ b/railties/test/application/paths_test.rb @@ -1,7 +1,7 @@ require "isolation/abstract_unit" module ApplicationTests - class PathsTest < Test::Unit::TestCase + class PathsTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup @@ -15,7 +15,6 @@ module ApplicationTests app.config.session_store nil end RUBY - use_frameworks [:action_controller, :action_view, :action_mailer, :active_record] require "#{app_path}/config/environment" @paths = Rails.application.config.paths end @@ -46,7 +45,6 @@ module ApplicationTests assert_path @paths["app/views"], "app/views" assert_path @paths["lib"], "lib" assert_path @paths["vendor"], "vendor" - assert_path @paths["vendor/plugins"], "vendor/plugins" assert_path @paths["tmp"], "tmp" assert_path @paths["config"], "config" assert_path @paths["config/locales"], "config/locales/en.yml" diff --git a/railties/test/application/rack/logger_test.rb b/railties/test/application/rack/logger_test.rb index 8b2b2f1802..a77c6f472c 100644 --- a/railties/test/application/rack/logger_test.rb +++ b/railties/test/application/rack/logger_test.rb @@ -4,7 +4,7 @@ require "rack/test" module ApplicationTests module RackTests - class LoggerTest < Test::Unit::TestCase + class LoggerTest < ActiveSupport::TestCase include ActiveSupport::LogSubscriber::TestHelper include Rack::Test::Methods @@ -12,6 +12,8 @@ module ApplicationTests build_app require "#{app_path}/config/environment" super + @logger = MockLogger.new + Rails.stubs(:logger).returns(@logger) end def teardown diff --git a/railties/test/application/rackup_test.rb b/railties/test/application/rackup_test.rb index ff9cdcadc7..49ac9fc66c 100644 --- a/railties/test/application/rackup_test.rb +++ b/railties/test/application/rackup_test.rb @@ -1,12 +1,12 @@ require "isolation/abstract_unit" module ApplicationTests - class RackupTest < Test::Unit::TestCase + class RackupTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def rackup require "rack" - app, options = Rack::Builder.parse_file("#{app_path}/config.ru") + app, _ = Rack::Builder.parse_file("#{app_path}/config.ru") app end diff --git a/railties/test/application/rake/migrations_test.rb b/railties/test/application/rake/migrations_test.rb new file mode 100644 index 0000000000..0a47fd014c --- /dev/null +++ b/railties/test/application/rake/migrations_test.rb @@ -0,0 +1,158 @@ +require "isolation/abstract_unit" + +module ApplicationTests + module RakeTests + class RakeMigrationsTest < ActiveSupport::TestCase + def setup + build_app + boot_rails + FileUtils.rm_rf("#{app_path}/config/environments") + end + + def teardown + teardown_app + end + + test 'running migrations with given scope' do + Dir.chdir(app_path) do + `rails generate model user username:string password:string` + + app_file "db/migrate/01_a_migration.bukkits.rb", <<-MIGRATION + class AMigration < ActiveRecord::Migration + end + MIGRATION + + output = `rake db:migrate SCOPE=bukkits` + assert_no_match(/create_table\(:users\)/, output) + assert_no_match(/CreateUsers/, output) + assert_no_match(/add_column\(:users, :email, :string\)/, output) + + assert_match(/AMigration: migrated/, output) + + output = `rake db:migrate SCOPE=bukkits VERSION=0` + assert_no_match(/drop_table\(:users\)/, output) + assert_no_match(/CreateUsers/, output) + assert_no_match(/remove_column\(:users, :email\)/, output) + + assert_match(/AMigration: reverted/, output) + end + end + + test 'model and migration generator with change syntax' do + Dir.chdir(app_path) do + `rails generate model user username:string password:string; + rails generate migration add_email_to_users email:string` + + output = `rake db:migrate` + assert_match(/create_table\(:users\)/, output) + assert_match(/CreateUsers: migrated/, output) + assert_match(/add_column\(:users, :email, :string\)/, output) + assert_match(/AddEmailToUsers: migrated/, output) + + output = `rake db:rollback STEP=2` + assert_match(/drop_table\("users"\)/, output) + assert_match(/CreateUsers: reverted/, output) + assert_match(/remove_column\("users", :email\)/, output) + assert_match(/AddEmailToUsers: reverted/, output) + end + end + + test 'migration status when schema migrations table is not present' do + output = Dir.chdir(app_path){ `rake db:migrate:status` } + assert_equal "Schema migrations table does not exist yet.\n", output + end + + test 'test migration status' do + Dir.chdir(app_path) do + `rails generate model user username:string password:string; + rails generate migration add_email_to_users email:string; + rake db:migrate` + + output = `rake db:migrate:status` + + assert_match(/up\s+\d{14}\s+Create users/, output) + assert_match(/up\s+\d{14}\s+Add email to users/, output) + + `rake db:rollback STEP=1` + output = `rake db:migrate:status` + + assert_match(/up\s+\d{14}\s+Create users/, output) + assert_match(/down\s+\d{14}\s+Add email to users/, output) + end + end + + test 'migration status without timestamps' do + add_to_config('config.active_record.timestamped_migrations = false') + + Dir.chdir(app_path) do + `rails generate model user username:string password:string; + rails generate migration add_email_to_users email:string; + rake db:migrate` + + output = `rake db:migrate:status` + + assert_match(/up\s+\d{3,}\s+Create users/, output) + assert_match(/up\s+\d{3,}\s+Add email to users/, output) + + `rake db:rollback STEP=1` + output = `rake db:migrate:status` + + assert_match(/up\s+\d{3,}\s+Create users/, output) + assert_match(/down\s+\d{3,}\s+Add email to users/, output) + end + end + + test 'test migration status after rollback and redo' do + Dir.chdir(app_path) do + `rails generate model user username:string password:string; + rails generate migration add_email_to_users email:string; + rake db:migrate` + + output = `rake db:migrate:status` + + assert_match(/up\s+\d{14}\s+Create users/, output) + assert_match(/up\s+\d{14}\s+Add email to users/, output) + + `rake db:rollback STEP=2` + output = `rake db:migrate:status` + + assert_match(/down\s+\d{14}\s+Create users/, output) + assert_match(/down\s+\d{14}\s+Add email to users/, output) + + `rake db:migrate:redo` + output = `rake db:migrate:status` + + assert_match(/up\s+\d{14}\s+Create users/, output) + assert_match(/up\s+\d{14}\s+Add email to users/, output) + end + end + + test 'migration status after rollback and redo without timestamps' do + add_to_config('config.active_record.timestamped_migrations = false') + + Dir.chdir(app_path) do + `rails generate model user username:string password:string; + rails generate migration add_email_to_users email:string; + rake db:migrate` + + output = `rake db:migrate:status` + + assert_match(/up\s+\d{3,}\s+Create users/, output) + assert_match(/up\s+\d{3,}\s+Add email to users/, output) + + `rake db:rollback STEP=2` + output = `rake db:migrate:status` + + assert_match(/down\s+\d{3,}\s+Create users/, output) + assert_match(/down\s+\d{3,}\s+Add email to users/, output) + + `rake db:migrate:redo` + output = `rake db:migrate:status` + + assert_match(/up\s+\d{3,}\s+Create users/, output) + assert_match(/up\s+\d{3,}\s+Add email to users/, output) + end + end + end + end +end diff --git a/railties/test/application/rake/notes_test.rb b/railties/test/application/rake/notes_test.rb new file mode 100644 index 0000000000..04abf9e3a1 --- /dev/null +++ b/railties/test/application/rake/notes_test.rb @@ -0,0 +1,56 @@ +require "isolation/abstract_unit" + +module ApplicationTests + module RakeTests + class RakeNotesTest < ActiveSupport::TestCase + def setup + build_app + require "rails/all" + end + + def teardown + teardown_app + end + + test 'notes' do + app_file "app/views/home/index.html.erb", "<% # TODO: note in erb %>" + app_file "app/views/home/index.html.haml", "-# TODO: note in haml" + app_file "app/views/home/index.html.slim", "/ TODO: note in slim" + app_file "app/assets/javascripts/application.js.coffee", "# TODO: note in coffee" + app_file "app/controllers/application_controller.rb", 1000.times.map { "" }.join("\n") << "# TODO: note in ruby" + + boot_rails + require 'rake' + require 'rdoc/task' + require 'rake/testtask' + + Rails.application.load_tasks + + Dir.chdir(app_path) do + output = `bundle exec rake notes` + lines = output.scan(/\[([0-9\s]+)\](\s)/) + + assert_match /note in erb/, output + assert_match /note in haml/, output + assert_match /note in slim/, output + assert_match /note in ruby/, output + assert_match /note in coffee/, output + + assert_equal 5, lines.size + + lines.each do |line| + assert_equal 4, line[0].size + assert_equal ' ', line[1] + end + end + + end + + private + def boot_rails + super + require "#{app_path}/config/environment" + end + end + end +end diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb index c76bc3d526..27d521485c 100644 --- a/railties/test/application/rake_test.rb +++ b/railties/test/application/rake_test.rb @@ -2,7 +2,7 @@ require "isolation/abstract_unit" module ApplicationTests - class RakeTest < Test::Unit::TestCase + class RakeTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup @@ -63,26 +63,23 @@ module ApplicationTests def test_rake_test_error_output Dir.chdir(app_path){ `rake db:migrate` } - app_file "config/database.yml", <<-RUBY - development: - RUBY - app_file "test/unit/one_unit_test.rb", <<-RUBY + raise 'unit' RUBY app_file "test/functional/one_functional_test.rb", <<-RUBY - raise RuntimeError + raise 'functional' RUBY app_file "test/integration/one_integration_test.rb", <<-RUBY - raise RuntimeError + raise 'integration' RUBY silence_stderr do - output = Dir.chdir(app_path){ `rake test` } - assert_match(/Errors running test:units! #<ActiveRecord::AdapterNotSpecified/, output) - assert_match(/Errors running test:functionals! #<RuntimeError/, output) - assert_match(/Errors running test:integration! #<RuntimeError/, output) + output = Dir.chdir(app_path) { `rake test 2>&1` } + assert_match 'unit', output + assert_match 'functional', output + assert_match 'integration', output end end @@ -108,98 +105,67 @@ module ApplicationTests assert_match "Sample log message", output end - def test_model_and_migration_generator_with_change_syntax + def test_loading_specific_fixtures Dir.chdir(app_path) do - `rails generate model user username:string password:string` - `rails generate migration add_email_to_users email:string` + `rails generate model user username:string password:string; + rails generate model product name:string; + rake db:migrate` end - output = Dir.chdir(app_path){ `rake db:migrate` } - assert_match(/create_table\(:users\)/, output) - assert_match(/CreateUsers: migrated/, output) - assert_match(/add_column\(:users, :email, :string\)/, output) - assert_match(/AddEmailToUsers: migrated/, output) - - output = Dir.chdir(app_path){ `rake db:rollback STEP=2` } - assert_match(/drop_table\("users"\)/, output) - assert_match(/CreateUsers: reverted/, output) - assert_match(/remove_column\("users", :email\)/, output) - assert_match(/AddEmailToUsers: reverted/, output) - end + require "#{rails_root}/config/environment" + + # loading a specific fixture + errormsg = Dir.chdir(app_path) { `rake db:fixtures:load FIXTURES=products` } + assert $?.success?, errormsg - def test_migration_status_when_schema_migrations_table_is_not_present - output = Dir.chdir(app_path){ `rake db:migrate:status` } - assert_equal "Schema migrations table does not exist yet.\n", output + assert_equal 2, ::AppTemplate::Application::Product.count + assert_equal 0, ::AppTemplate::Application::User.count end - def test_migration_status - Dir.chdir(app_path) do - `rails generate model user username:string password:string` - `rails generate migration add_email_to_users email:string` + def test_scaffold_tests_pass_by_default + output = Dir.chdir(app_path) do + `rails generate scaffold user username:string password:string; + bundle exec rake db:migrate db:test:clone test` end - Dir.chdir(app_path) { `rake db:migrate`} - output = Dir.chdir(app_path) { `rake db:migrate:status` } - - assert_match(/up\s+\d{14}\s+Create users/, output) - assert_match(/up\s+\d{14}\s+Add email to users/, output) - - Dir.chdir(app_path) { `rake db:rollback STEP=1` } - output = Dir.chdir(app_path) { `rake db:migrate:status` } - - assert_match(/up\s+\d{14}\s+Create users/, output) - assert_match(/down\s+\d{14}\s+Add email to users/, output) + assert_match(/7 tests, 13 assertions, 0 failures, 0 errors/, output) + assert_no_match(/Errors running/, output) end - def test_migration_status_after_rollback_and_redo + def test_rake_dump_structure_should_respect_db_structure_env_variable Dir.chdir(app_path) do - `rails generate model user username:string password:string` - `rails generate migration add_email_to_users email:string` + # 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')) + end - Dir.chdir(app_path) { `rake db:migrate`} - output = Dir.chdir(app_path) { `rake db:migrate:status` } - - assert_match(/up\s+\d{14}\s+Create users/, output) - assert_match(/up\s+\d{14}\s+Add email to users/, output) - - Dir.chdir(app_path) { `rake db:rollback STEP=2` } - output = Dir.chdir(app_path) { `rake db:migrate:status` } - - assert_match(/down\s+\d{14}\s+Create users/, output) - assert_match(/down\s+\d{14}\s+Add email to users/, output) + def test_rake_dump_structure_should_be_called_twice_when_migrate_redo + add_to_config "config.active_record.schema_format = :sql" - Dir.chdir(app_path) { `rake db:migrate:redo` } - output = Dir.chdir(app_path) { `rake db:migrate:status` } + output = Dir.chdir(app_path) do + `rails g model post title:string; + bundle exec rake db:migrate:redo 2>&1 --trace;` + end - assert_match(/up\s+\d{14}\s+Create users/, output) - assert_match(/up\s+\d{14}\s+Add email to users/, output) + # expect only Invoke db:structure:dump (first_time) + assert_no_match(/^\*\* Invoke db:structure:dump\s+$/, output) end - def test_loading_specific_fixtures + def test_rake_dump_schema_cache Dir.chdir(app_path) do - `rails generate model user username:string password:string` - `rails generate model product name:string` - `rake db:migrate` + `rails generate model post title:string; + rails generate model product name:string; + bundle exec rake db:migrate db:schema:cache:dump` end - - require "#{rails_root}/config/environment" - - # loading a specific fixture - errormsg = Dir.chdir(app_path) { `rake db:fixtures:load FIXTURES=products` } - assert $?.success?, errormsg - - assert_equal 2, ::AppTemplate::Application::Product.count - assert_equal 0, ::AppTemplate::Application::User.count + assert File.exists?(File.join(app_path, 'db', 'schema_cache.dump')) end - def test_scaffold_tests_pass_by_default - content = Dir.chdir(app_path) do - `rails generate scaffold user username:string password:string` - `bundle exec rake db:migrate db:test:clone test` + def test_rake_clear_schema_cache + Dir.chdir(app_path) do + `bundle exec rake db:schema:cache:dump db:schema:cache:clear` end - - assert_match(/7 tests, 10 assertions, 0 failures, 0 errors/, content) + assert !File.exists?(File.join(app_path, 'db', 'schema_cache.dump')) end end end diff --git a/railties/test/application/route_inspect_test.rb b/railties/test/application/route_inspect_test.rb index add8256b5d..6393cfff4b 100644 --- a/railties/test/application/route_inspect_test.rb +++ b/railties/test/application/route_inspect_test.rb @@ -1,12 +1,43 @@ -require 'test/unit' +require 'minitest/autorun' require 'rails/application/route_inspector' require 'action_controller' +require 'rails/engine' module ApplicationTests - class RouteInspectTest < Test::Unit::TestCase + class RouteInspectTest < ActiveSupport::TestCase def setup @set = ActionDispatch::Routing::RouteSet.new @inspector = Rails::Application::RouteInspector.new + app = ActiveSupport::OrderedOptions.new + app.config = ActiveSupport::OrderedOptions.new + app.config.assets = ActiveSupport::OrderedOptions.new + app.config.assets.prefix = '/sprockets' + Rails.stubs(:application).returns(app) + end + + def test_displaying_routes_for_engines + engine = Class.new(Rails::Engine) do + def self.to_s + "Blog::Engine" + end + end + engine.routes.draw do + get '/cart', :to => 'cart#show' + end + + @set.draw do + get '/custom/assets', :to => 'custom_assets#show' + mount engine => "/blog", :as => "blog" + end + + output = @inspector.format @set.routes + expected = [ + "custom_assets GET /custom/assets(.:format) custom_assets#show", + " blog /blog Blog::Engine", + "\nRoutes for Blog::Engine:", + "cart GET /cart(.:format) cart#show" + ] + assert_equal expected, output end def test_cart_inspect @@ -36,6 +67,7 @@ module ApplicationTests " new_article GET /articles/new(.:format) articles#new", "edit_article GET /articles/:id/edit(.:format) articles#edit", " article GET /articles/:id(.:format) articles#show", + " PATCH /articles/:id(.:format) articles#update", " PUT /articles/:id(.:format) articles#update", " DELETE /articles/:id(.:format) articles#destroy" ] assert_equal expected, output @@ -49,12 +81,20 @@ module ApplicationTests assert_equal ["root / pages#main"], output end + def test_inspect_routes_shows_dynamic_action_route + @set.draw do + match 'api/:action' => 'api' + end + output = @inspector.format @set.routes + assert_equal [" /api/:action(.:format) api#:action"], output + end + def test_inspect_routes_shows_controller_and_action_only_route @set.draw do match ':controller/:action' end output = @inspector.format @set.routes - assert_equal [" /:controller/:action(.:format) "], output + assert_equal [" /:controller/:action(.:format) :controller#:action"], output end def test_inspect_routes_shows_controller_and_action_route_with_constraints @@ -62,7 +102,7 @@ module ApplicationTests match ':controller(/:action(/:id))', :id => /\d+/ end output = @inspector.format @set.routes - assert_equal [" /:controller(/:action(/:id))(.:format) {:id=>/\\d+/}"], output + assert_equal [" /:controller(/:action(/:id))(.:format) :controller#:action {:id=>/\\d+/}"], output end def test_rake_routes_shows_route_with_defaults @@ -93,5 +133,31 @@ module ApplicationTests output = @inspector.format @set.routes assert_equal [" /foo/:id(.:format) #{RackApp.name} {:id=>/[A-Z]\\d{5}/}"], output end + + def test_rake_routes_shows_route_with_rack_app_nested_with_dynamic_constraints + constraint = Class.new do + def to_s + "( my custom constraint )" + end + end + + @set.draw do + scope :constraint => constraint.new do + mount RackApp => '/foo' + end + end + + output = @inspector.format @set.routes + assert_equal [" /foo #{RackApp.name} {:constraint=>( my custom constraint )}"], output + end + + def test_rake_routes_dont_show_app_mounted_in_assets_prefix + @set.draw do + match '/sprockets' => RackApp + end + output = @inspector.format @set.routes + assert_no_match(/RackApp/, output.first) + assert_no_match(/\/sprockets/, output.first) + end end end diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb index a05e39658d..28ce3beea9 100644 --- a/railties/test/application/routing_test.rb +++ b/railties/test/application/routing_test.rb @@ -2,7 +2,7 @@ require 'isolation/abstract_unit' require 'rack/test' module ApplicationTests - class RoutingTest < Test::Unit::TestCase + class RoutingTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation include Rack::Test::Methods diff --git a/railties/test/application/runner_test.rb b/railties/test/application/runner_test.rb index 4468fa295e..e1d283a7fd 100644 --- a/railties/test/application/runner_test.rb +++ b/railties/test/application/runner_test.rb @@ -1,7 +1,7 @@ require 'isolation/abstract_unit' module ApplicationTests - class RunnerTest < Test::Unit::TestCase + class RunnerTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb index 27a7959e84..f6bcaa466a 100644 --- a/railties/test/application/test_test.rb +++ b/railties/test/application/test_test.rb @@ -1,7 +1,7 @@ require 'isolation/abstract_unit' module ApplicationTests - class TestTest < Test::Unit::TestCase + class TestTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup @@ -24,24 +24,7 @@ module ApplicationTests end RUBY - run_test 'unit/foo_test.rb' - end - - # Run just in Ruby < 1.9 - if defined?(Test::Unit::Util::BacktraceFilter) - test "adds backtrace cleaner" do - app_file 'test/unit/backtrace_test.rb', <<-RUBY - require 'test_helper' - - class FooTest < ActiveSupport::TestCase - def test_truth - assert Test::Unit::Util::BacktraceFilter.ancestors.include?(Rails::BacktraceFilterForTestUnit) - end - end - RUBY - - run_test 'unit/backtrace_test.rb' - end + run_test_file 'unit/foo_test.rb' end test "integration test" do @@ -66,7 +49,7 @@ module ApplicationTests end RUBY - run_test 'integration/posts_test.rb' + run_test_file 'integration/posts_test.rb' end test "performance test" do @@ -91,11 +74,11 @@ module ApplicationTests end RUBY - run_test 'performance/posts_test.rb' + run_test_file 'performance/posts_test.rb' end private - def run_test(name) + def run_test_file(name) result = ruby '-Itest', "#{app_path}/test/#{name}" assert_equal 0, $?.to_i, result end diff --git a/railties/test/application/url_generation_test.rb b/railties/test/application/url_generation_test.rb index 2b6ec26cd0..85a8a15fcc 100644 --- a/railties/test/application/url_generation_test.rb +++ b/railties/test/application/url_generation_test.rb @@ -1,7 +1,7 @@ require 'isolation/abstract_unit' module ApplicationTests - class UrlGenerationTest < Test::Unit::TestCase + class UrlGenerationTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def app diff --git a/railties/test/backtrace_cleaner_test.rb b/railties/test/backtrace_cleaner_test.rb index 80077378db..cbe7d35f6d 100644 --- a/railties/test/backtrace_cleaner_test.rb +++ b/railties/test/backtrace_cleaner_test.rb @@ -1,34 +1,6 @@ require 'abstract_unit' require 'rails/backtrace_cleaner' -if defined? Test::Unit::Util::BacktraceFilter - class TestWithBacktrace - include Test::Unit::Util::BacktraceFilter - include Rails::BacktraceFilterForTestUnit - end - - class BacktraceCleanerFilterTest < ActiveSupport::TestCase - def setup - @test = TestWithBacktrace.new - @backtrace = [ './test/rails/benchmark_test.rb', './test/rails/dependencies.rb', '/opt/local/lib/ruby/kernel.rb' ] - end - - test "test with backtrace should use the rails backtrace cleaner to clean" do - Rails.stubs(:backtrace_cleaner).returns(stub(:clean)) - Rails.backtrace_cleaner.expects(:clean).with(@backtrace, nil) - @test.send(:filter_backtrace, @backtrace) - end - - test "filter backtrace should have the same arity as Test::Unit::Util::BacktraceFilter" do - assert_nothing_raised do - @test.send(:filter_backtrace, @backtrace, '/opt/local/lib') - end - end - end -else - $stderr.puts 'No BacktraceFilter for minitest' -end - if defined? Gem class BacktraceCleanerVendorGemTest < ActiveSupport::TestCase def setup diff --git a/railties/test/commands/console_test.rb b/railties/test/commands/console_test.rb new file mode 100644 index 0000000000..9aa1d68675 --- /dev/null +++ b/railties/test/commands/console_test.rb @@ -0,0 +1,106 @@ +require 'abstract_unit' +require 'rails/commands/console' + +class Rails::ConsoleTest < ActiveSupport::TestCase + class FakeConsole + end + + def setup + end + + def test_sandbox_option + console = Rails::Console.new(app, ["--sandbox"]) + assert console.sandbox? + end + + def test_short_version_of_sandbox_option + console = Rails::Console.new(app, ["-s"]) + assert console.sandbox? + end + + def test_debugger_option + console = Rails::Console.new(app, ["--debugger"]) + assert console.debugger? + end + + def test_no_options + console = Rails::Console.new(app, []) + assert !console.debugger? + assert !console.sandbox? + end + + def test_start + app.expects(:sandbox=).with(nil) + FakeConsole.expects(:start) + + start + + assert_match /Loading \w+ environment \(Rails/, output + end + + def test_start_with_debugger + app.expects(:sandbox=).with(nil) + rails_console.expects(:require_debugger).returns(nil) + FakeConsole.expects(:start) + + start ["--debugger"] + end + + def test_start_with_sandbox + app.expects(:sandbox=).with(true) + FakeConsole.expects(:start) + + start ["--sandbox"] + + assert_match /Loading \w+ environment in sandbox \(Rails/, output + end + + def test_console_with_environment + app.expects(:sandbox=).with(nil) + FakeConsole.expects(:start) + + start ["-e production"] + + assert_match /production/, output + end + + def test_console_with_rails_environment + app.expects(:sandbox=).with(nil) + FakeConsole.expects(:start) + + start ["RAILS_ENV=production"] + + assert_match /production/, output + end + + + def test_console_defaults_to_IRB + config = mock("config", :console => nil) + app = mock("app", :config => config) + app.expects(:load_console).returns(nil) + + assert_equal IRB, Rails::Console.new(app).console + end + + private + + attr_reader :output + + def rails_console + @rails_console ||= Rails::Console.new(app) + end + + def start(argv = []) + rails_console.stubs(:arguments => argv) + @output = output = capture(:stdout) { rails_console.start } + end + + def app + @app ||= begin + config = mock("config", :console => FakeConsole) + app = mock("app", :config => config) + app.expects(:load_console) + app + end + end +end diff --git a/railties/test/commands/server_test.rb b/railties/test/commands/server_test.rb new file mode 100644 index 0000000000..8039aec873 --- /dev/null +++ b/railties/test/commands/server_test.rb @@ -0,0 +1,26 @@ +require 'abstract_unit' +require 'rails/commands/server' + +class Rails::ServerTest < ActiveSupport::TestCase + + def test_environment_with_server_option + args = ["thin", "RAILS_ENV=production"] + options = Rails::Server::Options.new.parse!(args) + assert_equal 'production', options[:environment] + assert_equal 'thin', options[:server] + end + + def test_environment_without_server_option + args = ["RAILS_ENV=production"] + options = Rails::Server::Options.new.parse!(args) + assert_equal 'production', options[:environment] + assert_nil options[:server] + end + + def test_server_option_without_environment + args = ["thin"] + options = Rails::Server::Options.new.parse!(args) + assert_nil options[:environment] + assert_equal 'thin', options[:server] + end +end diff --git a/railties/test/fixtures/lib/generators/usage_template/USAGE b/railties/test/fixtures/lib/generators/usage_template/USAGE new file mode 100644 index 0000000000..bcd63c52e2 --- /dev/null +++ b/railties/test/fixtures/lib/generators/usage_template/USAGE @@ -0,0 +1 @@ +:: <%= 1 + 1 %> ::
\ No newline at end of file diff --git a/railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb b/railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb new file mode 100644 index 0000000000..078b0f9412 --- /dev/null +++ b/railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb @@ -0,0 +1,5 @@ +require 'rails/generators' + +class UsageTemplateGenerator < Rails::Generators::Base + source_root File.expand_path("templates", File.dirname(__FILE__)) +end diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb index 94e9abb3cc..a8c8fcd5b7 100644 --- a/railties/test/generators/actions_test.rb +++ b/railties/test/generators/actions_test.rb @@ -9,8 +9,6 @@ class ActionsTest < Rails::Generators::TestCase def setup Rails.application = TestApp::Application super - @git_plugin_uri = 'git://github.com/technoweenie/restful-authentication.git' - @svn_plugin_uri = 'svn://svnhub.com/technoweenie/restful-authentication/trunk' end def teardown @@ -37,41 +35,6 @@ class ActionsTest < Rails::Generators::TestCase assert_file 'lib/test_file.rb', 'heres block data' end - def test_plugin_with_git_option_should_run_plugin_install - generator.expects(:run_ruby_script).once.with("script/rails plugin install #{@git_plugin_uri}", :verbose => false) - action :plugin, 'restful-authentication', :git => @git_plugin_uri - end - - def test_plugin_with_svn_option_should_run_plugin_install - generator.expects(:run_ruby_script).once.with("script/rails plugin install #{@svn_plugin_uri}", :verbose => false) - action :plugin, 'restful-authentication', :svn => @svn_plugin_uri - end - - def test_plugin_with_git_option_and_branch_should_run_plugin_install - generator.expects(:run_ruby_script).once.with("script/rails plugin install -b stable #{@git_plugin_uri}", :verbose => false) - action :plugin, 'restful-authentication', :git => @git_plugin_uri, :branch => 'stable' - end - - def test_plugin_with_svn_option_and_revision_should_run_plugin_install - generator.expects(:run_ruby_script).once.with("script/rails plugin install -r 1234 #{@svn_plugin_uri}", :verbose => false) - action :plugin, 'restful-authentication', :svn => @svn_plugin_uri, :revision => 1234 - end - - def test_plugin_with_git_option_and_submodule_should_use_git_scm - generator.expects(:run).with("git submodule add #{@git_plugin_uri} vendor/plugins/rest_auth", :verbose => false) - action :plugin, 'rest_auth', :git => @git_plugin_uri, :submodule => true - end - - def test_plugin_with_git_option_and_submodule_should_use_git_scm - generator.expects(:run).with("git submodule add -b stable #{@git_plugin_uri} vendor/plugins/rest_auth", :verbose => false) - action :plugin, 'rest_auth', :git => @git_plugin_uri, :submodule => true, :branch => 'stable' - end - - def test_plugin_with_no_options_should_skip_method - generator.expects(:run).never - action :plugin, 'rest_auth', {} - end - def test_add_source_adds_source_to_gemfile run_generator action :add_source, 'http://gems.github.com' @@ -95,11 +58,13 @@ class ActionsTest < Rails::Generators::TestCase def test_gem_should_insert_on_separate_lines run_generator + File.open('Gemfile', 'a') {|f| f.write('# Some content...') } + action :gem, 'rspec' action :gem, 'rspec-rails' - assert_file 'Gemfile', /gem "rspec"$/ - assert_file 'Gemfile', /gem "rspec-rails"$/ + assert_file 'Gemfile', /^gem "rspec"$/ + assert_file 'Gemfile', /^gem "rspec-rails"$/ end def test_gem_group_should_wrap_gems_in_a_group @@ -179,9 +144,12 @@ class ActionsTest < Rails::Generators::TestCase action :generate, 'model', 'MyModel' end - def test_rake_should_run_rake_command_with_development_env - generator.expects(:run).once.with('rake log:clear RAILS_ENV=development', :verbose => false) + def test_rake_should_run_rake_command_with_default_env + generator.expects(:run).once.with("rake log:clear RAILS_ENV=development", :verbose => false) + old_env, ENV['RAILS_ENV'] = ENV["RAILS_ENV"], nil action :rake, 'log:clear' + ensure + ENV["RAILS_ENV"] = old_env end def test_rake_with_env_option_should_run_rake_command_in_env @@ -189,9 +157,28 @@ class ActionsTest < Rails::Generators::TestCase action :rake, 'log:clear', :env => 'production' end + def test_rake_with_rails_env_variable_should_run_rake_command_in_env + generator.expects(:run).once.with('rake log:clear RAILS_ENV=production', :verbose => false) + old_env, ENV["RAILS_ENV"] = ENV["RAILS_ENV"], "production" + action :rake, 'log:clear' + ensure + ENV["RAILS_ENV"] = old_env + end + + def test_env_option_should_win_over_rails_env_variable_when_running_rake + generator.expects(:run).once.with('rake log:clear RAILS_ENV=production', :verbose => false) + old_env, ENV["RAILS_ENV"] = ENV["RAILS_ENV"], "staging" + action :rake, 'log:clear', :env => 'production' + ensure + ENV["RAILS_ENV"] = old_env + end + def test_rake_with_sudo_option_should_run_rake_command_with_sudo - generator.expects(:run).once.with('sudo rake log:clear RAILS_ENV=development', :verbose => false) + generator.expects(:run).once.with("sudo rake log:clear RAILS_ENV=development", :verbose => false) + old_env, ENV['RAILS_ENV'] = ENV["RAILS_ENV"], nil action :rake, 'log:clear', :sudo => true + ensure + ENV["RAILS_ENV"] = old_env end def test_capify_should_run_the_capify_command @@ -209,14 +196,14 @@ class ActionsTest < Rails::Generators::TestCase def test_readme run_generator Rails::Generators::AppGenerator.expects(:source_root).times(2).returns(destination_root) - assert_match(/Welcome to Rails/, action(:readme, "README")) + assert_match(/Welcome to Rails/, action(:readme, "README.rdoc")) end def test_readme_with_quiet generator(default_arguments, :quiet => true) run_generator Rails::Generators::AppGenerator.expects(:source_root).times(2).returns(destination_root) - assert_no_match(/Welcome to Rails/, action(:readme, "README")) + assert_no_match(/Welcome to Rails/, action(:readme, "README.rdoc")) end def test_log diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 1b48c80042..128854e4ad 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -1,4 +1,3 @@ -require 'abstract_unit' require 'generators/generators_test_helper' require 'rails/generators/rails/app/app_generator' require 'generators/shared_generator_tests.rb' @@ -33,7 +32,6 @@ DEFAULT_APP_FILES = %w( test/unit vendor vendor/assets - vendor/plugins tmp/cache tmp/cache/assets ) @@ -55,6 +53,7 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "app/views/layouts/application.html.erb", /javascript_include_tag\s+"application"/ assert_file "app/assets/stylesheets/application.css" assert_file "config/application.rb", /config\.assets\.enabled = true/ + assert_file "public/index.html", /url\("assets\/rails.png"\);/ end def test_invalid_application_name_raises_an_error @@ -123,6 +122,16 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "hats/config/environment.rb", /Hats::Application\.initialize!/ end + def test_gemfile_has_no_whitespace_errors + run_generator + absolute = File.expand_path("Gemfile", destination_root) + File.open(absolute, 'r') do |f| + f.each_line do |line| + assert_no_match %r{/^[ \t]+$/}, line + end + end + end + def test_config_database_is_added_by_default run_generator assert_file "config/database.yml", /sqlite3/ @@ -143,6 +152,16 @@ class AppGeneratorTest < Rails::Generators::TestCase end end + def test_config_postgresql_database + run_generator([destination_root, "-d", "postgresql"]) + assert_file "config/database.yml", /postgresql/ + unless defined?(JRUBY_VERSION) + assert_file "Gemfile", /^gem\s+["']pg["']$/ + else + assert_file "Gemfile", /^gem\s+["']activerecord-jdbcpostgresql-adapter["']$/ + end + end + def test_config_jdbcmysql_database run_generator([destination_root, "-d", "jdbcmysql"]) assert_file "config/database.yml", /mysql/ @@ -183,6 +202,8 @@ class AppGeneratorTest < Rails::Generators::TestCase run_generator [destination_root, "--skip-active-record"] assert_no_file "config/database.yml" assert_file "config/application.rb", /#\s+require\s+["']active_record\/railtie["']/ + assert_file "config/application.rb", /#\s+config\.active_record\.whitelist_attributes = true/ + assert_file "config/application.rb", /#\s+config\.active_record\.dependent_restrict_raises = false/ assert_file "test/test_helper.rb" do |helper_content| assert_no_match(/fixtures :all/, helper_content) end @@ -192,17 +213,48 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_generator_if_skip_sprockets_is_given run_generator [destination_root, "--skip-sprockets"] assert_file "config/application.rb" do |content| - assert_match(/#\s+require\s+["']sprockets\/railtie["']/, content) + assert_match(/#\s+require\s+["']sprockets\/rails\/railtie["']/, content) assert_no_match(/config\.assets\.enabled = true/, content) end + assert_file "Gemfile" do |content| + assert_no_match(/sass-rails/, content) + assert_no_match(/coffee-rails/, content) + assert_no_match(/uglifier/, content) + end + assert_file "config/environments/development.rb" do |content| + assert_no_match(/config\.assets\.debug = true/, content) + end + assert_file "config/environments/production.rb" do |content| + assert_no_match(/config\.assets\.digest = true/, content) + assert_no_match(/config\.assets\.compress = true/, content) + end assert_file "test/performance/browsing_test.rb" end + def test_inclusion_of_javascript_runtime + run_generator([destination_root]) + if defined?(JRUBY_VERSION) + assert_file "Gemfile", /gem\s+["']therubyrhino["']$/ + else + assert_file "Gemfile", /# gem\s+["']therubyracer["']+, :platform => :ruby$/ + end + end + def test_creation_of_a_test_directory run_generator assert_file 'test' end + def test_creation_of_vendor_assets_javascripts_directory + run_generator + assert_file "vendor/assets/javascripts" + end + + def test_creation_of_vendor_assets_stylesheets_directory + run_generator + assert_file "vendor/assets/stylesheets" + end + def test_jquery_is_the_default_javascript_library run_generator assert_file "app/assets/javascripts/application.js" do |contents| @@ -232,32 +284,10 @@ class AppGeneratorTest < Rails::Generators::TestCase end end - def test_inclusion_of_turn_gem_in_gemfile + def test_inclusion_of_ruby_debug19 run_generator assert_file "Gemfile" do |contents| - assert_match(/gem 'turn'/, contents) unless RUBY_VERSION < '1.9.2' - assert_no_match(/gem 'turn'/, contents) if RUBY_VERSION < '1.9.2' - end - end - - def test_turn_gem_is_not_included_in_gemfile_if_skipping_test_unit - run_generator [destination_root, "--skip-test-unit"] - assert_file "Gemfile" do |contents| - assert_no_match(/gem 'turn'/, contents) unless RUBY_VERSION < '1.9.2' - end - end - - def test_inclusion_of_ruby_debug - run_generator - assert_file "Gemfile" do |contents| - assert_match(/gem 'ruby-debug'/, contents) if RUBY_VERSION < '1.9' - end - end - - def test_inclusion_of_ruby_debug19_if_ruby19 - run_generator - assert_file "Gemfile" do |contents| - assert_match(/gem 'ruby-debug19', :require => 'ruby-debug'/, contents) unless RUBY_VERSION < '1.9' + assert_match(/gem 'ruby-debug19', :require => 'ruby-debug'/, contents) end end @@ -272,7 +302,7 @@ class AppGeneratorTest < Rails::Generators::TestCase end def test_default_usage - File.expects(:exist?).returns(false) + Rails::Generators::AppGenerator.expects(:usage_path).returns(nil) assert_match(/Create rails files for app generator/, Rails::Generators::AppGenerator.desc) end @@ -299,36 +329,48 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_new_hash_style run_generator [destination_root] assert_file "config/initializers/session_store.rb" do |file| - if RUBY_VERSION < "1.9" - assert_match(/config.session_store :cookie_store, :key => '_.+_session'/, file) - else - assert_match(/config.session_store :cookie_store, key: '_.+_session'/, file) - end + assert_match(/config.session_store :cookie_store, key: '_.+_session'/, file) end end - def test_force_old_style_hash - run_generator [destination_root, "--old-style-hash"] - assert_file "config/initializers/session_store.rb" do |file| - assert_match(/config.session_store :cookie_store, :key => '_.+_session'/, file) + def test_generated_environments_file_for_sanitizer + run_generator [destination_root, "--skip-active-record"] + %w(development test).each do |env| + assert_file "config/environments/#{env}.rb" do |file| + assert_no_match(/config.active_record.mass_assignment_sanitizer = :strict/, file) + end end end - def test_generated_environments_file_for_sanitizer + def test_generated_environments_file_for_auto_explain run_generator [destination_root, "--skip-active-record"] - ["config/environments/development.rb", "config/environments/test.rb"].each do |env_file| - assert_file env_file do |file| - assert_no_match(/config.active_record.mass_assignment_sanitizer = :strict/, file) + %w(development production).each do |env| + assert_file "config/environments/#{env}.rb" do |file| + assert_no_match %r(auto_explain_threshold_in_seconds), file end end end + def test_active_record_whitelist_attributes_is_present_application_config + run_generator + assert_file "config/application.rb", /config\.active_record\.whitelist_attributes = true/ + end + + def test_active_record_dependent_restrict_raises_is_present_application_config + run_generator + assert_file "config/application.rb", /config\.active_record\.dependent_restrict_raises = false/ + end + + def test_pretend_option + output = run_generator [File.join(destination_root, "myapp"), "--pretend"] + assert_no_match(/run bundle install/, output) + end + protected def action(*args, &block) silence(:stdout) { generator.send(*args, &block) } end - end class CustomAppGeneratorTest < Rails::Generators::TestCase diff --git a/railties/test/generators/assets_generator_test.rb b/railties/test/generators/assets_generator_test.rb index 044e0b6bc6..d6338bd3da 100644 --- a/railties/test/generators/assets_generator_test.rb +++ b/railties/test/generators/assets_generator_test.rb @@ -13,7 +13,7 @@ class AssetsGeneratorTest < Rails::Generators::TestCase end def test_skipping_assets - content = run_generator ["posts", "--no-stylesheets", "--no-javascripts"] + run_generator ["posts", "--no-stylesheets", "--no-javascripts"] assert_no_file "app/assets/javascripts/posts.js" assert_no_file "app/assets/stylesheets/posts.css" end diff --git a/railties/test/generators/generated_attribute_test.rb b/railties/test/generators/generated_attribute_test.rb index a85829085c..6e3fc84781 100644 --- a/railties/test/generators/generated_attribute_test.rb +++ b/railties/test/generators/generated_attribute_test.rb @@ -69,7 +69,7 @@ class GeneratedAttributeTest < Rails::Generators::TestCase end def test_default_value_for_type - att = Rails::Generators::GeneratedAttribute.new("type", "string") + att = Rails::Generators::GeneratedAttribute.parse("type:string") assert_equal("", att.default) end @@ -122,4 +122,9 @@ class GeneratedAttributeTest < Rails::Generators::TestCase assert_equal :string, create_generated_attribute(nil, 'title').type assert_equal :string, create_generated_attribute("", 'title').type end + + def test_handles_index_names_for_references + assert_equal "post", create_generated_attribute('string', 'post').index_name + assert_equal "post_id", create_generated_attribute('references', 'post').index_name + end end diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb index 139d6b1421..c501780e7f 100644 --- a/railties/test/generators/mailer_generator_test.rb +++ b/railties/test/generators/mailer_generator_test.rb @@ -10,11 +10,7 @@ class MailerGeneratorTest < Rails::Generators::TestCase run_generator assert_file "app/mailers/notifier.rb" do |mailer| assert_match(/class Notifier < ActionMailer::Base/, mailer) - if RUBY_VERSION < "1.9" - assert_match(/default :from => "from@example.com"/, mailer) - else - assert_match(/default from: "from@example.com"/, mailer) - end + assert_match(/default from: "from@example.com"/, mailer) end end @@ -77,33 +73,14 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_file "app/mailers/notifier.rb" do |mailer| assert_instance_method :foo, mailer do |foo| - if RUBY_VERSION < "1.9" - assert_match(/mail :to => "to@example.org"/, foo) - else - assert_match(/mail to: "to@example.org"/, foo) - end + assert_match(/mail to: "to@example.org"/, foo) assert_match(/@greeting = "Hi"/, foo) end assert_instance_method :bar, mailer do |bar| - if RUBY_VERSION < "1.9" - assert_match(/mail :to => "to@example.org"/, bar) - else - assert_match(/mail to: "to@example.org"/, bar) - end + assert_match(/mail to: "to@example.org"/, bar) assert_match(/@greeting = "Hi"/, bar) end end end - - def test_force_old_style_hash - run_generator ["notifier", "foo", "--old-style-hash"] - assert_file "app/mailers/notifier.rb" do |mailer| - assert_match(/default :from => "from@example.com"/, mailer) - - assert_instance_method :foo, mailer do |foo| - assert_match(/mail :to => "to@example.org"/, foo) - end - end - end end diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb index 337257df7d..b320e40654 100644 --- a/railties/test/generators/migration_generator_test.rb +++ b/railties/test/generators/migration_generator_test.rb @@ -41,6 +41,24 @@ class MigrationGeneratorTest < Rails::Generators::TestCase end end + def test_remove_migration_with_indexed_attribute + migration = "remove_title_body_from_posts" + run_generator [migration, "title:string:index", "body:text"] + + assert_migration "db/migrate/#{migration}.rb" do |content| + assert_method :up, content do |up| + assert_match(/remove_column :posts, :title/, up) + assert_match(/remove_column :posts, :body/, up) + end + + assert_method :down, content do |down| + assert_match(/add_column :posts, :title, :string/, down) + assert_match(/add_column :posts, :body, :text/, down) + assert_match(/add_index :posts, :title/, down) + end + end + end + def test_remove_migration_with_attributes migration = "remove_title_body_from_posts" run_generator [migration, "title:string", "body:text"] @@ -58,6 +76,68 @@ class MigrationGeneratorTest < Rails::Generators::TestCase end end + def test_add_migration_with_attributes_and_indices + migration = "add_title_with_index_and_body_to_posts" + run_generator [migration, "title:string:index", "body:text", "user_id:integer:uniq"] + + assert_migration "db/migrate/#{migration}.rb" do |content| + assert_method :change, content do |up| + assert_match(/add_column :posts, :title, :string/, up) + assert_match(/add_column :posts, :body, :text/, up) + assert_match(/add_column :posts, :user_id, :integer/, up) + end + assert_match(/add_index :posts, :title/, content) + assert_match(/add_index :posts, :user_id, unique: true/, content) + end + end + + def test_add_migration_with_attributes_and_wrong_index_declaration + migration = "add_title_and_content_to_books" + run_generator [migration, "title:string:inex", "content:text", "user_id:integer:unik"] + + assert_migration "db/migrate/#{migration}.rb" do |content| + assert_method :change, content do |up| + assert_match(/add_column :books, :title, :string/, up) + assert_match(/add_column :books, :content, :text/, up) + assert_match(/add_column :books, :user_id, :integer/, up) + end + assert_no_match(/add_index :books, :title/, content) + assert_no_match(/add_index :books, :user_id/, content) + end + end + + def test_add_migration_with_attributes_without_type_and_index + migration = "add_title_with_index_and_body_to_posts" + run_generator [migration, "title:index", "body:text", "user_uuid:uniq"] + + assert_migration "db/migrate/#{migration}.rb" do |content| + assert_method :change, content do |up| + assert_match(/add_column :posts, :title, :string/, up) + assert_match(/add_column :posts, :body, :text/, up) + assert_match(/add_column :posts, :user_uuid, :string/, up) + end + assert_match(/add_index :posts, :title/, content) + assert_match(/add_index :posts, :user_uuid, unique: true/, content) + end + end + + def test_add_migration_with_attributes_index_declaration_and_attribute_options + migration = "add_title_and_content_to_books" + run_generator [migration, "title:string{40}:index", "content:string{255}", "price:decimal{1,2}:index", "discount:decimal{3.4}:uniq"] + + assert_migration "db/migrate/#{migration}.rb" do |content| + assert_method :change, content do |up| + assert_match(/add_column :books, :title, :string, limit: 40/, up) + assert_match(/add_column :books, :content, :string, limit: 255/, up) + assert_match(/add_column :books, :price, :decimal, precision: 1, scale: 2/, up) + assert_match(/add_column :books, :discount, :decimal, precision: 3, scale: 4/, up) + end + assert_match(/add_index :books, :title/, content) + assert_match(/add_index :books, :price/, content) + assert_match(/add_index :books, :discount, unique: true/, content) + end + end + def test_should_create_empty_migrations_if_name_not_start_with_add_or_remove migration = "create_books" run_generator [migration, "title:string", "content:text"] @@ -72,4 +152,8 @@ class MigrationGeneratorTest < Rails::Generators::TestCase end end end + + def test_properly_identifies_usage_file + assert generator_class.send(:usage_path) + end end diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb index 1b0cb425c6..e8d933935d 100644 --- a/railties/test/generators/model_generator_test.rb +++ b/railties/test/generators/model_generator_test.rb @@ -113,6 +113,74 @@ class ModelGeneratorTest < Rails::Generators::TestCase end end + def test_migration_with_attributes_and_with_index + run_generator ["product", "name:string:index", "supplier_id:integer:index", "user_id:integer:uniq", "order_id:uniq"] + + assert_migration "db/migrate/create_products.rb" do |m| + assert_method :change, m do |up| + assert_match(/create_table :products/, up) + assert_match(/t\.string :name/, up) + assert_match(/t\.integer :supplier_id/, up) + assert_match(/t\.integer :user_id/, up) + assert_match(/t\.string :order_id/, up) + + assert_match(/add_index :products, :name/, up) + assert_match(/add_index :products, :supplier_id/, up) + assert_match(/add_index :products, :user_id, unique: true/, up) + assert_match(/add_index :products, :order_id, unique: true/, up) + end + end + end + + def test_migration_with_attributes_and_with_wrong_index_declaration + run_generator ["product", "name:string", "supplier_id:integer:inex", "user_id:integer:unqu"] + + assert_migration "db/migrate/create_products.rb" do |m| + assert_method :change, m do |up| + assert_match(/create_table :products/, up) + assert_match(/t\.string :name/, up) + assert_match(/t\.integer :supplier_id/, up) + assert_match(/t\.integer :user_id/, up) + + assert_no_match(/add_index :products, :name/, up) + assert_no_match(/add_index :products, :supplier_id/, up) + assert_no_match(/add_index :products, :user_id/, up) + end + end + end + + def test_migration_with_missing_attribute_type_and_with_index + run_generator ["product", "name:index", "supplier_id:integer:index", "year:integer"] + + assert_migration "db/migrate/create_products.rb" do |m| + assert_method :change, m do |up| + assert_match(/create_table :products/, up) + assert_match(/t\.string :name/, up) + assert_match(/t\.integer :supplier_id/, up) + + assert_match(/add_index :products, :name/, up) + assert_match(/add_index :products, :supplier_id/, up) + assert_no_match(/add_index :products, :year/, up) + end + end + end + + def test_add_migration_with_attributes_index_declaration_and_attribute_options + run_generator ["product", "title:string{40}:index", "content:string{255}", "price:decimal{5,2}:index", "discount:decimal{5,2}:uniq"] + + assert_migration "db/migrate/create_products.rb" do |content| + assert_method :change, content do |up| + assert_match(/create_table :products/, up) + assert_match(/t.string :title, limit: 40/, up) + assert_match(/t.string :content, limit: 255/, up) + assert_match(/t.decimal :price, precision: 5, scale: 2/, up) + end + assert_match(/add_index :products, :title/, content) + assert_match(/add_index :products, :price/, content) + assert_match(/add_index :products, :discount, unique: true/, content) + end + end + def test_migration_without_timestamps ActiveRecord::Base.timestamped_migrations = false run_generator ["account"] @@ -249,4 +317,14 @@ class ModelGeneratorTest < Rails::Generators::TestCase end end end + + def test_attr_accessible_added_with_non_reference_attributes + run_generator + assert_file 'app/models/account.rb', /attr_accessible :age, :name/ + end + + def test_attr_accessible_added_with_comments_when_no_attributes_present + run_generator ["Account"] + assert_file 'app/models/account.rb', /# attr_accessible :title, :body/ + end end diff --git a/railties/test/generators/named_base_test.rb b/railties/test/generators/named_base_test.rb index f23701e99e..2bc2c33a72 100644 --- a/railties/test/generators/named_base_test.rb +++ b/railties/test/generators/named_base_test.rb @@ -108,6 +108,15 @@ class NamedBaseTest < Rails::Generators::TestCase assert_name g, 'sheep_index', :index_helper end + def test_hide_namespace + g = generator ['Hidden'] + g.class.stubs(:namespace).returns('hidden') + + assert !Rails::Generators.hidden_namespaces.include?('hidden') + g.class.hide! + assert Rails::Generators.hidden_namespaces.include?('hidden') + 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 dd1e4bdac1..5c63b13dce 100644 --- a/railties/test/generators/namespaced_generators_test.rb +++ b/railties/test/generators/namespaced_generators_test.rb @@ -155,11 +155,7 @@ class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase assert_file "app/mailers/test_app/notifier.rb" do |mailer| assert_match(/module TestApp/, mailer) assert_match(/class Notifier < ActionMailer::Base/, mailer) - if RUBY_VERSION < "1.9" - assert_match(/default :from => "from@example.com"/, mailer) - else - assert_match(/default from: "from@example.com"/, mailer) - end + assert_match(/default from: "from@example.com"/, mailer) end end diff --git a/railties/test/generators/orm_test.rb b/railties/test/generators/orm_test.rb new file mode 100644 index 0000000000..9dd3d3e0ec --- /dev/null +++ b/railties/test/generators/orm_test.rb @@ -0,0 +1,38 @@ +require "generators/generators_test_helper" +require "rails/generators/rails/scaffold_controller/scaffold_controller_generator" + +# Mock out two ORMs +module ORMWithGenerators + module Generators + class ActiveModel + def initialize(name) + end + end + end +end + +module ORMWithoutGenerators + # No generators +end + +class OrmTest < Rails::Generators::TestCase + include GeneratorsTestHelper + tests Rails::Generators::ScaffoldControllerGenerator + + def test_orm_class_returns_custom_generator_if_supported_custom_orm_set + g = generator ["Foo"], :orm => "ORMWithGenerators" + assert_equal ORMWithGenerators::Generators::ActiveModel, g.send(:orm_class) + end + + def test_orm_class_returns_rails_generator_if_unsupported_custom_orm_set + g = generator ["Foo"], :orm => "ORMWithoutGenerators" + assert_equal Rails::Generators::ActiveModel, g.send(:orm_class) + end + + def test_orm_instance_returns_orm_class_instance_with_name + g = generator ["Foo"] + orm_instance = g.send(:orm_instance) + assert g.send(:orm_class) === orm_instance + assert_equal "foo", orm_instance.name + end +end diff --git a/railties/test/generators/plugin_new_generator_test.rb b/railties/test/generators/plugin_new_generator_test.rb index 9183945619..4bb5f04a79 100644 --- a/railties/test/generators/plugin_new_generator_test.rb +++ b/railties/test/generators/plugin_new_generator_test.rb @@ -1,4 +1,3 @@ -require 'abstract_unit' require 'generators/generators_test_helper' require 'rails/generators/rails/plugin_new/plugin_new_generator' require 'generators/shared_generator_tests.rb' @@ -28,13 +27,20 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase include SharedGeneratorTests def test_invalid_plugin_name_raises_an_error - content = capture(:stderr){ run_generator [File.join(destination_root, "43-things")] } - assert_equal "Invalid plugin name 43-things. Please give a name which does not start with numbers.\n", content + content = capture(:stderr){ run_generator [File.join(destination_root, "things-43")] } + assert_equal "Invalid plugin name things-43. Please give a name which use only alphabetic or numeric or \"_\" characters.\n", content + + content = capture(:stderr){ run_generator [File.join(destination_root, "things4.3")] } + assert_equal "Invalid plugin name things4.3. Please give a name which use only alphabetic or numeric or \"_\" characters.\n", content + + content = capture(:stderr){ run_generator [File.join(destination_root, "43things")] } + assert_equal "Invalid plugin name 43things. Please give a name which does not start with numbers.\n", content end - def test_invalid_plugin_name_is_fixed - run_generator [File.join(destination_root, "things-43")] - assert_file "things-43/lib/things-43.rb", /module Things43/ + def test_camelcase_plugin_name_underscores_filenames + run_generator [File.join(destination_root, "CamelCasedName")] + assert_no_file "CamelCasedName/lib/CamelCasedName.rb" + assert_file "CamelCasedName/lib/camel_cased_name.rb", /module CamelCasedName/ end def test_generating_without_options @@ -237,6 +243,14 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase assert_no_file "test" end + def test_ensure_that_gitignore_can_be_generated_from_a_template_for_dummy_path + FileUtils.cd(Rails.root) + run_generator([destination_root, "--dummy_path", "spec/dummy" "--skip-test-unit"]) + assert_file ".gitignore" do |contents| + assert_match(/spec\/dummy/, contents) + end + end + def test_skipping_test_unit run_generator [destination_root, "--skip-test-unit"] assert_no_file "test" @@ -250,6 +264,37 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase assert_no_file "bukkits.gemspec" end + def test_creating_plugin_in_app_directory_adds_gemfile_entry + # simulate application existance + gemfile_path = "#{Rails.root}/Gemfile" + Object.const_set('APP_PATH', Rails.root) + FileUtils.touch gemfile_path + + run_generator [destination_root] + + assert_file gemfile_path, /gem 'bukkits', :path => 'tmp\/bukkits'/ + ensure + Object.send(:remove_const, 'APP_PATH') + FileUtils.rm gemfile_path + end + + def test_skipping_gemfile_entry + # simulate application existance + gemfile_path = "#{Rails.root}/Gemfile" + Object.const_set('APP_PATH', Rails.root) + FileUtils.touch gemfile_path + + run_generator [destination_root, "--skip-gemfile-entry"] + + assert_file gemfile_path do |contents| + assert_no_match(/gem 'bukkits', :path => 'tmp\/bukkits'/, contents) + end + ensure + Object.send(:remove_const, 'APP_PATH') + FileUtils.rm gemfile_path + end + + protected def action(*args, &block) diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb index 65b30b9fbd..1eea50b0d9 100644 --- a/railties/test/generators/scaffold_controller_generator_test.rb +++ b/railties/test/generators/scaffold_controller_generator_test.rb @@ -75,6 +75,19 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase assert_file "test/functional/users_controller_test.rb" do |content| assert_match(/class UsersControllerTest < ActionController::TestCase/, content) assert_match(/test "should get index"/, content) + assert_match(/post :create, user: \{ age: @user.age, name: @user.name \}/, content) + assert_match(/put :update, id: @user, user: \{ age: @user.age, name: @user.name \}/, content) + end + end + + def test_functional_tests_without_attributes + run_generator ["User"] + + assert_file "test/functional/users_controller_test.rb" do |content| + assert_match(/class UsersControllerTest < ActionController::TestCase/, content) + assert_match(/test "should get index"/, content) + assert_match(/post :create, user: \{ \}/, content) + assert_match(/put :update, id: @user, user: \{ \}/, content) end end @@ -126,18 +139,7 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase def test_new_hash_style run_generator assert_file "app/controllers/users_controller.rb" do |content| - if RUBY_VERSION < "1.9" - assert_match(/\{ render :action => "new" \}/, content) - else - assert_match(/\{ render action: "new" \}/, content) - end - end - end - - def test_force_old_style_hash - run_generator ["User", "--old-style-hash"] - assert_file "app/controllers/users_controller.rb" do |content| - assert_match(/\{ render :action => "new" \}/, content) + assert_match(/\{ render action: "new" \}/, content) end end end diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb index 2db8090621..7123950add 100644 --- a/railties/test/generators/scaffold_generator_test.rb +++ b/railties/test/generators/scaffold_generator_test.rb @@ -62,8 +62,11 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase end end - assert_file "test/functional/product_lines_controller_test.rb", - /class ProductLinesControllerTest < ActionController::TestCase/ + assert_file "test/functional/product_lines_controller_test.rb" do |test| + assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, test) + assert_match(/post :create, product_line: \{ title: @product_line.title \}/, test) + assert_match(/put :update, id: @product_line, product_line: \{ title: @product_line.title \}/, test) + end # Views %w( @@ -85,6 +88,17 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase assert_file "app/assets/stylesheets/product_lines.css" end + def test_functional_tests_without_attributes + run_generator ["product_line"] + + assert_file "test/functional/product_lines_controller_test.rb" do |content| + assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, content) + assert_match(/test "should get index"/, content) + assert_match(/post :create, product_line: \{ \}/, content) + assert_match(/put :update, id: @product_line, product_line: \{ \}/, content) + end + end + def test_scaffold_on_revoke run_generator run_generator ["product_line"], :behavior => :revoke diff --git a/railties/test/generators/shared_generator_tests.rb b/railties/test/generators/shared_generator_tests.rb index 1534f0d828..92117855b7 100644 --- a/railties/test/generators/shared_generator_tests.rb +++ b/railties/test/generators/shared_generator_tests.rb @@ -91,21 +91,6 @@ module SharedGeneratorTests assert_match(/It works!/, capture(:stdout) { generator.invoke_all }) end - def test_template_raises_an_error_with_invalid_path - content = capture(:stderr){ run_generator([destination_root, "-m", "non/existant/path"]) } - assert_match(/The template \[.*\] could not be loaded/, content) - assert_match(/non\/existant\/path/, content) - end - - def test_template_is_executed_when_supplied - path = "http://gist.github.com/103208.txt" - template = %{ say "It works!" } - template.instance_eval "def read; self; end" # Make the string respond to read - - generator([destination_root], :template => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) - assert_match(/It works!/, capture(:stdout) { generator.invoke_all }) - end - def test_template_is_executed_when_supplied_an_https_path path = "https://gist.github.com/103208.txt" template = %{ say "It works!" } @@ -125,7 +110,7 @@ module SharedGeneratorTests def test_edge_option generator([destination_root], :edge => true).expects(:bundle_command).with('install').once quietly { generator.invoke_all } - assert_file 'Gemfile', %r{^gem\s+["']rails["'],\s+:git\s+=>\s+["']#{Regexp.escape("git://github.com/rails/rails.git")}["']$} + assert_file 'Gemfile', %r{^gem\s+["']rails["'],\s+:git\s+=>\s+["']#{Regexp.escape("https://github.com/rails/rails.git")}["']$} end def test_skip_gemfile diff --git a/railties/test/generators/task_generator_test.rb b/railties/test/generators/task_generator_test.rb new file mode 100644 index 0000000000..f810a21d1e --- /dev/null +++ b/railties/test/generators/task_generator_test.rb @@ -0,0 +1,12 @@ +require 'generators/generators_test_helper' +require 'rails/generators/rails/task/task_generator' + +class TaskGeneratorTest < Rails::Generators::TestCase + include GeneratorsTestHelper + arguments %w(feeds foo bar) + + def test_controller_skeleton_is_created + run_generator + assert_file "lib/tasks/feeds.rake", /namespace :feeds/ + end +end diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index 56329f3183..60e7e57a91 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -201,4 +201,16 @@ class GeneratorsTest < Rails::Generators::TestCase mspec = Rails::Generators.find_by_namespace :fixjour assert mspec.source_paths.include?(File.join(Rails.root, "lib", "templates", "fixjour")) end + + def test_usage_with_embedded_ruby + require File.expand_path("fixtures/lib/generators/usage_template/usage_template_generator", File.dirname(__FILE__)) + output = capture(:stdout) { Rails::Generators.invoke :usage_template, ['--help'] } + assert_match /:: 2 ::/, output + end + + def test_hide_namespace + assert !Rails::Generators.hidden_namespaces.include?("special:namespace") + Rails::Generators.hide_namespace("special:namespace") + assert Rails::Generators.hidden_namespaces.include?("special:namespace") + end end diff --git a/railties/test/initializable_test.rb b/railties/test/initializable_test.rb index 72c35879c5..c84c7f204c 100644 --- a/railties/test/initializable_test.rb +++ b/railties/test/initializable_test.rb @@ -61,7 +61,7 @@ module InitializableTests class Instance include Rails::Initializable - initializer :one do + initializer :one, :group => :assets do $arr << 1 end @@ -69,7 +69,7 @@ module InitializableTests $arr << 2 end - initializer :three do + initializer :three, :group => :all do $arr << 3 end @@ -209,14 +209,21 @@ module InitializableTests $arr = [] instance = Instance.new instance.run_initializers - assert_equal [1, 2, 3, 4], $arr + assert_equal [2, 3, 4], $arr + end + + test "running locals with groups" do + $arr = [] + instance = Instance.new + instance.run_initializers(:assets) + assert_equal [1, 3], $arr end end class WithArgsTest < ActiveSupport::TestCase test "running initializers with args" do $with_arg = nil - WithArgs.new.run_initializers('foo') + WithArgs.new.run_initializers(:default, 'foo') assert_equal 'foo', $with_arg end end diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index 4a6bdb0320..ac4c2abfc8 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -8,8 +8,9 @@ # Rails booted up. require 'fileutils' -require 'test/unit' require 'rubygems' +require 'minitest/autorun' +require 'active_support/test_case' # TODO: Remove setting this magic constant RAILS_FRAMEWORK_ROOT = File.expand_path("#{File.dirname(__FILE__)}/../../..") @@ -115,7 +116,12 @@ module TestHelpers end end - add_to_config 'config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"; config.session_store :cookie_store, :key => "_myapp_session"; config.active_support.deprecation = :log' + add_to_config <<-RUBY + config.secret_token = "3b7cd727ee24e8444053437c36cc66c4" + config.session_store :cookie_store, :key => "_myapp_session" + config.active_support.deprecation = :log + config.action_controller.allow_forgery_protection = false + RUBY end def teardown_app @@ -178,20 +184,6 @@ module TestHelpers end end - def plugin(name, string = "") - dir = "#{app_path}/vendor/plugins/#{name}" - FileUtils.mkdir_p(dir) - - File.open("#{dir}/init.rb", 'w') do |f| - f.puts "::#{name.upcase} = 'loaded'" - f.puts string - end - - Bukkit.new(dir).tap do |bukkit| - yield bukkit if block_given? - end - end - def engine(name) dir = "#{app_path}/random/#{name}" FileUtils.mkdir_p(dir) @@ -224,6 +216,15 @@ module TestHelpers end end + def add_to_env_config(env, str) + environment = File.read("#{app_path}/config/environments/#{env}.rb") + if environment =~ /(\n\s*end\s*)\Z/ + File.open("#{app_path}/config/environments/#{env}.rb", 'w') do |f| + f.puts $` + "\n#{str}\n" + $1 + end + end + end + def remove_from_config(str) file = "#{app_path}/config/application.rb" contents = File.read(file) @@ -249,9 +250,11 @@ module TestHelpers def use_frameworks(arr) to_remove = [:actionmailer, :activemodel, - :activerecord, - :activeresource] - arr - remove_from_config "config.active_record.identity_map = true" if to_remove.include? :activerecord + :activerecord] - arr + if to_remove.include? :activerecord + remove_from_config "config.active_record.whitelist_attributes = true" + remove_from_config "config.active_record.dependent_restrict_raises = false" + end $:.reject! {|path| path =~ %r'/(#{to_remove.join('|')})/' } end @@ -261,7 +264,7 @@ module TestHelpers end end -class Test::Unit::TestCase +class ActiveSupport::TestCase include TestHelpers::Paths include TestHelpers::Rack include TestHelpers::Generation diff --git a/railties/test/paths_test.rb b/railties/test/paths_test.rb index c0f3887263..d334034e7d 100644 --- a/railties/test/paths_test.rb +++ b/railties/test/paths_test.rb @@ -22,7 +22,7 @@ class PathsTest < ActiveSupport::TestCase root = Rails::Paths::Root.new(nil) root.add "app" root.path = "/root" - assert_equal ["app"], root["app"] + assert_equal ["app"], root["app"].to_ary assert_equal ["/root/app"], root["app"].to_a end @@ -91,10 +91,6 @@ class PathsTest < ActiveSupport::TestCase assert_equal ["/foo/bar/app2", "/foo/bar/app"], @root["app"].to_a end - test "the root can only have one physical path" do - assert_raise(RuntimeError) { Rails::Paths::Root.new(["/fiz", "/biz"]) } - end - test "it is possible to add a path that should be autoloaded only once" do @root.add "app", :with => "/app" @root["app"].autoload_once! diff --git a/railties/test/rails_info_test.rb b/railties/test/rails_info_test.rb index 1da66062aa..b9fb071d23 100644 --- a/railties/test/rails_info_test.rb +++ b/railties/test/rails_info_test.rb @@ -43,7 +43,7 @@ class InfoTest < ActiveSupport::TestCase def test_frameworks_exist Rails::Info.frameworks.each do |framework| - dir = File.dirname(__FILE__) + "/../../" + framework.gsub('_', '') + dir = File.dirname(__FILE__) + "/../../" + framework.delete('_') assert File.directory?(dir), "#{framework.classify} does not exist" end end diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb index 06a60cd858..5e93a8e783 100644 --- a/railties/test/railties/engine_test.rb +++ b/railties/test/railties/engine_test.rb @@ -1,13 +1,11 @@ require "isolation/abstract_unit" -require "railties/shared_tests" require "stringio" require "rack/test" module RailtiesTest - class EngineTest < Test::Unit::TestCase + class EngineTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation - include SharedTests include Rack::Test::Methods def setup @@ -29,6 +27,365 @@ module RailtiesTest teardown_app end + def boot_rails + super + require "#{app_path}/config/environment" + end + + test "serving sprocket's assets" do + @plugin.write "app/assets/javascripts/engine.js.erb", "<%= :alert %>();" + + boot_rails + require 'rack/test' + extend Rack::Test::Methods + + get "/assets/engine.js" + assert_match "alert()", last_response.body + end + + test "rake environment can be called in the engine" do + boot_rails + + @plugin.write "Rakefile", <<-RUBY + APP_RAKEFILE = '#{app_path}/Rakefile' + load 'rails/tasks/engine.rake' + task :foo => :environment do + puts "Task ran" + end + RUBY + + Dir.chdir(@plugin.path) do + output = `bundle exec rake foo` + assert_match "Task ran", output + end + end + + test "copying migrations" do + @plugin.write "db/migrate/1_create_users.rb", <<-RUBY + class CreateUsers < ActiveRecord::Migration + end + RUBY + + @plugin.write "db/migrate/2_add_last_name_to_users.rb", <<-RUBY + class AddLastNameToUsers < ActiveRecord::Migration + end + RUBY + + @plugin.write "db/migrate/3_create_sessions.rb", <<-RUBY + class CreateSessions < ActiveRecord::Migration + end + RUBY + + app_file "db/migrate/1_create_sessions.rb", <<-RUBY + class CreateSessions < ActiveRecord::Migration + def up + end + end + RUBY + + add_to_config "ActiveRecord::Base.timestamped_migrations = false" + + boot_rails + railties = Rails.application.railties.all.map(&:railtie_name) + + 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_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) + assert_equal 3, Dir["#{app_path}/db/migrate/*.rb"].length + + output = `bundle exec rake railties:install:migrations`.split("\n") + + assert_no_match(/2_create_users/, output.join("\n")) + + bukkits_migration_order = output.index(output.detect{|o| /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/ =~ o }) + 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` + + assert_equal migrations_count, Dir["#{app_path}/db/migrate/*.rb"].length + end + end + + test "no rake task without migrations" do + boot_rails + require 'rake' + require 'rdoc/task' + require 'rake/testtask' + Rails.application.load_tasks + assert !Rake::Task.task_defined?('bukkits:install:migrations') + end + + test "puts its lib directory on load path" do + boot_rails + require "another" + assert_equal "Another", Another.name + end + + test "puts its models directory on autoload path" do + @plugin.write "app/models/my_bukkit.rb", "class MyBukkit ; end" + boot_rails + assert_nothing_raised { MyBukkit } + end + + test "puts its controllers directory on autoload path" do + @plugin.write "app/controllers/bukkit_controller.rb", "class BukkitController ; end" + boot_rails + assert_nothing_raised { BukkitController } + end + + test "adds its views to view paths" do + @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY + class BukkitController < ActionController::Base + def index + end + end + RUBY + + @plugin.write "app/views/bukkit/index.html.erb", "Hello bukkits" + + boot_rails + + require "action_controller" + require "rack/mock" + response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/")) + assert_equal "Hello bukkits\n", response[2].body + end + + test "adds its views to view paths with lower proriority than app ones" do + @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY + class BukkitController < ActionController::Base + def index + end + end + RUBY + + @plugin.write "app/views/bukkit/index.html.erb", "Hello bukkits" + app_file "app/views/bukkit/index.html.erb", "Hi bukkits" + + boot_rails + + require "action_controller" + require "rack/mock" + response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/")) + assert_equal "Hi bukkits\n", response[2].body + end + + test "adds helpers to controller views" do + @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY + class BukkitController < ActionController::Base + def index + end + end + RUBY + + @plugin.write "app/helpers/bukkit_helper.rb", <<-RUBY + module BukkitHelper + def bukkits + "bukkits" + end + end + RUBY + + @plugin.write "app/views/bukkit/index.html.erb", "Hello <%= bukkits %>" + + boot_rails + + require "rack/mock" + response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/")) + assert_equal "Hello bukkits\n", response[2].body + end + + test "autoload any path under app" do + @plugin.write "app/anything/foo.rb", <<-RUBY + module Foo; end + RUBY + boot_rails + assert Foo + end + + test "routes are added to router" do + @plugin.write "config/routes.rb", <<-RUBY + class Sprokkit + def self.call(env) + [200, {'Content-Type' => 'text/html'}, ["I am a Sprokkit"]] + end + end + + Rails.application.routes.draw do + match "/sprokkit", :to => Sprokkit + end + RUBY + + boot_rails + require 'rack/test' + extend Rack::Test::Methods + + get "/sprokkit" + assert_equal "I am a Sprokkit", last_response.body + end + + test "routes in engines have lower priority than application ones" do + controller "foo", <<-RUBY + class FooController < ActionController::Base + def index + render :text => "foo" + end + end + RUBY + + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do + match 'foo', :to => 'foo#index' + end + RUBY + + @plugin.write "app/controllers/bar_controller.rb", <<-RUBY + class BarController < ActionController::Base + def index + render :text => "bar" + end + end + RUBY + + @plugin.write "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + match 'foo', :to => 'bar#index' + match 'bar', :to => 'bar#index' + end + RUBY + + boot_rails + require 'rack/test' + extend Rack::Test::Methods + + get '/foo' + assert_equal 'foo', last_response.body + + get '/bar' + assert_equal 'bar', last_response.body + end + + test "rake tasks lib tasks are loaded" do + $executed = false + @plugin.write "lib/tasks/foo.rake", <<-RUBY + task :foo do + $executed = true + end + RUBY + + boot_rails + require 'rake' + require 'rdoc/task' + require 'rake/testtask' + Rails.application.load_tasks + Rake::Task[:foo].invoke + assert $executed + end + + test "i18n files have lower priority than application ones" do + add_to_config <<-RUBY + config.i18n.load_path << "#{app_path}/app/locales/en.yml" + RUBY + + app_file 'app/locales/en.yml', <<-YAML +en: + bar: "1" +YAML + + app_file 'config/locales/en.yml', <<-YAML +en: + foo: "2" + bar: "2" +YAML + + @plugin.write 'config/locales/en.yml', <<-YAML +en: + foo: "3" +YAML + + boot_rails + + expected_locales = %W( + #{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 + #{@plugin.path}/config/locales/en.yml + #{app_path}/config/locales/en.yml + #{app_path}/app/locales/en.yml + ).map { |path| File.expand_path(path) } + + actual_locales = I18n.load_path.map { |path| + File.expand_path(path) + } & expected_locales # remove locales external to Rails + + assert_equal expected_locales, actual_locales + + assert_equal "2", I18n.t(:foo) + assert_equal "1", I18n.t(:bar) + end + + test "namespaced controllers with namespaced routes" do + @plugin.write "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + namespace :admin do + namespace :foo do + match "bar", :to => "bar#index" + end + end + end + RUBY + + @plugin.write "app/controllers/admin/foo/bar_controller.rb", <<-RUBY + class Admin::Foo::BarController < ApplicationController + def index + render :text => "Rendered from namespace" + end + end + RUBY + + boot_rails + require 'rack/test' + extend Rack::Test::Methods + + get "/admin/foo/bar" + assert_equal 200, last_response.status + assert_equal "Rendered from namespace", last_response.body + end + + test "initializers" do + $plugin_initializer = false + @plugin.write "config/initializers/foo.rb", <<-RUBY + $plugin_initializer = true + RUBY + + boot_rails + assert $plugin_initializer + end + + test "midleware referenced in configuration" do + @plugin.write "lib/bukkits.rb", <<-RUBY + class Bukkits + def initialize(app) + @app = app + end + + def call(env) + @app.call(env) + end + end + RUBY + + add_to_config "config.middleware.use \"Bukkits\"" + boot_rails + end + test "Rails::Engine itself does not respond to config" do boot_rails assert !Rails::Engine.respond_to?(:config) @@ -60,7 +417,6 @@ module RailtiesTest assert index < initializers.index { |i| i.name == :build_middleware_stack } end - class Upcaser def initialize(app) @app = app @@ -151,46 +507,6 @@ module RailtiesTest assert_equal "foo", last_response.body end - test "engine can load its own plugins" do - @plugin.write "lib/bukkits.rb", <<-RUBY - module Bukkits - class Engine < ::Rails::Engine - end - end - RUBY - - @plugin.write "vendor/plugins/yaffle/init.rb", <<-RUBY - config.yaffle_loaded = true - RUBY - - boot_rails - - assert Bukkits::Engine.config.yaffle_loaded - end - - test "engine does not load plugins that already exists in application" do - @plugin.write "lib/bukkits.rb", <<-RUBY - module Bukkits - class Engine < ::Rails::Engine - end - end - RUBY - - @plugin.write "vendor/plugins/yaffle/init.rb", <<-RUBY - config.engine_yaffle_loaded = true - RUBY - - app_file "vendor/plugins/yaffle/init.rb", <<-RUBY - config.app_yaffle_loaded = true - RUBY - - warnings = capture(:stderr) { boot_rails } - - assert !warnings.empty? - assert !Bukkits::Engine.config.respond_to?(:engine_yaffle_loaded) - assert Rails.application.config.app_yaffle_loaded - end - test "it loads its environment file" do @plugin.write "lib/bukkits.rb", <<-RUBY module Bukkits @@ -323,7 +639,7 @@ module RailtiesTest assert_equal "bukkits_", Bukkits.table_name_prefix assert_equal "bukkits", Bukkits::Engine.engine_name - assert_equal Bukkits._railtie, Bukkits::Engine + assert_equal Bukkits.railtie_namespace, Bukkits::Engine assert ::Bukkits::MyMailer.method_defined?(:foo_path) assert !::Bukkits::MyMailer.method_defined?(:bar_path) @@ -455,13 +771,19 @@ module RailtiesTest Rails.application.load_seed assert Rails.application.config.app_seeds_loaded - assert_raise(NoMethodError) do Bukkits::Engine.config.bukkits_seeds_loaded end + assert_raise(NoMethodError) { Bukkits::Engine.config.bukkits_seeds_loaded } Bukkits::Engine.load_seed assert Bukkits::Engine.config.bukkits_seeds_loaded end - test "using namespace more than once on one module should not overwrite _railtie method" do + test "skips nonexistent seed data" do + FileUtils.rm "#{app_path}/db/seeds.rb" + boot_rails + assert_nil Rails.application.load_seed + end + + test "using namespace more than once on one module should not overwrite railtie_namespace method" do @plugin.write "lib/bukkits.rb", <<-RUBY module AppTemplate class Engine < ::Rails::Engine @@ -478,7 +800,7 @@ module RailtiesTest boot_rails - assert_equal AppTemplate._railtie, AppTemplate::Engine + assert_equal AppTemplate.railtie_namespace, AppTemplate::Engine end test "properly reload routes" do @@ -510,8 +832,6 @@ module RailtiesTest boot_rails - require "#{rails_root}/config/environment" - get("/foo") assert_equal "foo", last_response.body @@ -545,7 +865,6 @@ module RailtiesTest RUBY boot_rails - require "#{rails_root}/config/environment" app_generators = Rails.application.config.generators.options[:rails] assert_equal :mongoid , app_generators[:orm] @@ -568,7 +887,6 @@ module RailtiesTest RUBY boot_rails - require "#{rails_root}/config/environment" generators = Bukkits::Engine.config.generators.options[:rails] assert_equal :active_record, generators[:orm] @@ -592,7 +910,6 @@ module RailtiesTest RUBY boot_rails - require "#{rails_root}/config/environment" assert_equal "foo", Bukkits.table_name_prefix end @@ -606,7 +923,6 @@ module RailtiesTest RUBY boot_rails - require "#{rails_root}/config/environment" assert_equal Bukkits::Engine.instance, Rails::Engine.find(@plugin.path) @@ -654,13 +970,189 @@ module RailtiesTest add_to_config("config.action_dispatch.show_exceptions = false") boot_rails - require "#{rails_root}/config/environment" methods = Bukkits::Engine.helpers.public_instance_methods.collect(&:to_s).sort expected = ["bar", "baz"] assert_equal expected, methods end + test "setting priority for engines with config.railties_order" do + @blog = engine "blog" do |plugin| + plugin.write "lib/blog.rb", <<-RUBY + module Blog + class Engine < ::Rails::Engine + end + end + RUBY + end + + @plugin.write "lib/bukkits.rb", <<-RUBY + module Bukkits + class Engine < ::Rails::Engine + isolate_namespace Bukkits + end + end + RUBY + + controller "main", <<-RUBY + class MainController < ActionController::Base + def foo + render :inline => '<%= render :partial => "shared/foo" %>' + end + + def bar + render :inline => '<%= render :partial => "shared/bar" %>' + end + end + RUBY + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + match "/foo" => "main#foo" + match "/bar" => "main#bar" + end + RUBY + + @plugin.write "app/views/shared/_foo.html.erb", <<-RUBY + Bukkit's foo partial + RUBY + + app_file "app/views/shared/_foo.html.erb", <<-RUBY + App's foo partial + RUBY + + @blog.write "app/views/shared/_bar.html.erb", <<-RUBY + Blog's bar partial + RUBY + + app_file "app/views/shared/_bar.html.erb", <<-RUBY + App's bar partial + RUBY + + @plugin.write "app/assets/javascripts/foo.js", <<-RUBY + // Bukkit's foo js + RUBY + + app_file "app/assets/javascripts/foo.js", <<-RUBY + // App's foo js + RUBY + + @blog.write "app/assets/javascripts/bar.js", <<-RUBY + // Blog's bar js + RUBY + + app_file "app/assets/javascripts/bar.js", <<-RUBY + // App's bar js + RUBY + + add_to_config("config.railties_order = [:all, :main_app, Blog::Engine]") + + boot_rails + + get("/foo") + assert_equal "Bukkit's foo partial", last_response.body.strip + + get("/bar") + assert_equal "App's bar partial", last_response.body.strip + + get("/assets/foo.js") + assert_equal "// Bukkit's foo js\n;", last_response.body.strip + + get("/assets/bar.js") + assert_equal "// App's bar js\n;", last_response.body.strip + end + + test "railties_order adds :all with lowest priority if not given" do + @plugin.write "lib/bukkits.rb", <<-RUBY + module Bukkits + class Engine < ::Rails::Engine + end + end + RUBY + + controller "main", <<-RUBY + class MainController < ActionController::Base + def foo + render :inline => '<%= render :partial => "shared/foo" %>' + end + end + RUBY + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + match "/foo" => "main#foo" + end + RUBY + + @plugin.write "app/views/shared/_foo.html.erb", <<-RUBY + Bukkit's foo partial + RUBY + + app_file "app/views/shared/_foo.html.erb", <<-RUBY + App's foo partial + RUBY + + add_to_config("config.railties_order = [Bukkits::Engine]") + + boot_rails + + get("/foo") + assert_equal "Bukkit's foo partial", last_response.body.strip + end + + test "engine can be properly mounted at root" do + add_to_config("config.action_dispatch.show_exceptions = false") + add_to_config("config.serve_static_assets = false") + + @plugin.write "lib/bukkits.rb", <<-RUBY + module Bukkits + class Engine < ::Rails::Engine + isolate_namespace ::Bukkits + end + end + RUBY + + @plugin.write "config/routes.rb", <<-RUBY + Bukkits::Engine.routes.draw do + root "foo#index" + end + RUBY + + @plugin.write "app/controllers/bukkits/foo_controller.rb", <<-RUBY + module Bukkits + class FooController < ActionController::Base + def index + text = <<-TEXT + script_name: \#{request.script_name} + fullpath: \#{request.fullpath} + path: \#{request.path} + TEXT + render :text => text + end + end + end + RUBY + + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + mount Bukkits::Engine => "/" + end + RUBY + + boot_rails + + expected = <<-TEXT + script_name: + fullpath: / + path: / + TEXT + + get("/") + assert_equal expected.split("\n").map(&:strip), + last_response.body.split("\n").map(&:strip) + end + private def app Rails.application diff --git a/railties/test/railties/generators_test.rb b/railties/test/railties/generators_test.rb index f8540d69d9..6ebbabc0ff 100644 --- a/railties/test/railties/generators_test.rb +++ b/railties/test/railties/generators_test.rb @@ -46,10 +46,6 @@ module RailtiesTests gem 'rails', :path => '#{RAILS_FRAMEWORK_ROOT}' gem 'sqlite3' - - if RUBY_VERSION < '1.9' - gem "ruby-debug", ">= 0.10.3" - end GEMFILE end end diff --git a/railties/test/railties/mounted_engine_test.rb b/railties/test/railties/mounted_engine_test.rb index 0491fc2174..2bb9df6b64 100644 --- a/railties/test/railties/mounted_engine_test.rb +++ b/railties/test/railties/mounted_engine_test.rb @@ -1,7 +1,7 @@ require 'isolation/abstract_unit' module ApplicationTests - class ApplicationRoutingTest < Test::Unit::TestCase + class ApplicationRoutingTest < ActiveSupport::TestCase require 'rack/test' include Rack::Test::Methods include ActiveSupport::Testing::Isolation diff --git a/railties/test/railties/plugin_ordering_test.rb b/railties/test/railties/plugin_ordering_test.rb deleted file mode 100644 index 1cfaf557e9..0000000000 --- a/railties/test/railties/plugin_ordering_test.rb +++ /dev/null @@ -1,76 +0,0 @@ -require "isolation/abstract_unit" - -module RailtiesTest - class PluginOrderingTest < Test::Unit::TestCase - include ActiveSupport::Testing::Isolation - - def setup - build_app - $arr = [] - plugin "a_plugin", "$arr << :a" - plugin "b_plugin", "$arr << :b" - plugin "c_plugin", "$arr << :c" - end - - def teardown - teardown_app - end - - def boot_rails - super - require "#{app_path}/config/environment" - end - - test "plugins are loaded alphabetically by default" do - boot_rails - assert_equal [:a, :b, :c], $arr - end - - test "if specified, only those plugins are loaded" do - add_to_config "config.plugins = [:b_plugin]" - boot_rails - assert_equal [:b], $arr - end - - test "the plugins are initialized in the order they are specified" do - add_to_config "config.plugins = [:b_plugin, :a_plugin]" - boot_rails - assert_equal [:b, :a], $arr - end - - test "if :all is specified, the remaining plugins are loaded in alphabetical order" do - add_to_config "config.plugins = [:c_plugin, :all]" - boot_rails - assert_equal [:c, :a, :b], $arr - end - - test "if :all is at the beginning, it represents the plugins not otherwise specified" do - add_to_config "config.plugins = [:all, :b_plugin]" - boot_rails - assert_equal [:a, :c, :b], $arr - end - - test "plugin order array is strings" do - add_to_config "config.plugins = %w( c_plugin all )" - boot_rails - assert_equal [:c, :a, :b], $arr - end - - test "can require lib file from a different plugin" do - plugin "foo", "require 'bar'" do |plugin| - plugin.write "lib/foo.rb", "$foo = true" - end - - plugin "bar", "require 'foo'" do |plugin| - plugin.write "lib/bar.rb", "$bar = true" - end - - add_to_config "config.plugins = [:foo, :bar]" - - boot_rails - - assert $foo - assert $bar - end - end -end diff --git a/railties/test/railties/plugin_test.rb b/railties/test/railties/plugin_test.rb deleted file mode 100644 index f307d53cf7..0000000000 --- a/railties/test/railties/plugin_test.rb +++ /dev/null @@ -1,123 +0,0 @@ -require "isolation/abstract_unit" -require "railties/shared_tests" - -module RailtiesTest - class PluginTest < Test::Unit::TestCase - include ActiveSupport::Testing::Isolation - include SharedTests - - def setup - build_app - - @plugin = plugin "bukkits", "::LEVEL = config.log_level" do |plugin| - plugin.write "lib/bukkits.rb", "class Bukkits; end" - plugin.write "lib/another.rb", "class Another; end" - end - end - - def teardown - teardown_app - end - - test "Rails::Plugin itself does not respond to config" do - boot_rails - assert !Rails::Plugin.respond_to?(:config) - end - - test "cannot inherit from Rails::Plugin" do - boot_rails - assert_raise RuntimeError do - class Foo < Rails::Plugin; end - end - end - - test "plugin can load the file with the same name in lib" do - boot_rails - require "bukkits" - assert_equal "Bukkits", Bukkits.name - end - - test "plugin gets added to dependency list" do - boot_rails - assert_equal "Another", Another.name - end - - test "plugin constants get reloaded if config.reload_plugins is set to true" do - add_to_config <<-RUBY - config.reload_plugins = true - RUBY - - boot_rails - - assert_equal "Another", Another.name - ActiveSupport::Dependencies.clear - @plugin.delete("lib/another.rb") - assert_raises(NameError) { Another } - end - - test "plugin constants are not reloaded by default" do - boot_rails - assert_equal "Another", Another.name - ActiveSupport::Dependencies.clear - @plugin.delete("lib/another.rb") - assert_nothing_raised { Another } - end - - test "it loads the plugin's init.rb file" do - boot_rails - assert_equal "loaded", BUKKITS - end - - test "the init.rb file has access to the config object" do - boot_rails - assert_equal :debug, LEVEL - end - - test "plugin_init_is_run_before_application_ones" do - plugin "foo", "$foo = true" do |plugin| - plugin.write "lib/foo.rb", "module Foo; end" - end - - app_file 'config/initializers/foo.rb', <<-RUBY - raise "no $foo" unless $foo - raise "no Foo" unless Foo - RUBY - - boot_rails - assert $foo - end - - test "plugin should work without init.rb" do - @plugin.delete("init.rb") - - boot_rails - - require "bukkits" - assert_nothing_raised { Bukkits } - end - - test "plugin cannot declare an engine for it" do - @plugin.write "lib/bukkits.rb", <<-RUBY - class Bukkits - class Engine < Rails::Engine - end - end - RUBY - - @plugin.write "init.rb", <<-RUBY - require "bukkits" - RUBY - - rescued = false - - begin - boot_rails - rescue Exception => e - rescued = true - assert_equal '"bukkits" is a Railtie/Engine and cannot be installed as a plugin', e.message - end - - assert rescued, "Expected boot rails to fail" - end - end -end diff --git a/railties/test/railties/railtie_test.rb b/railties/test/railties/railtie_test.rb index 55f85c7202..cd495320b5 100644 --- a/railties/test/railties/railtie_test.rb +++ b/railties/test/railties/railtie_test.rb @@ -1,7 +1,7 @@ require "isolation/abstract_unit" module RailtiesTest - class RailtieTest < Test::Unit::TestCase + class RailtieTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation def setup diff --git a/railties/test/railties/shared_tests.rb b/railties/test/railties/shared_tests.rb deleted file mode 100644 index 21fde49ff7..0000000000 --- a/railties/test/railties/shared_tests.rb +++ /dev/null @@ -1,361 +0,0 @@ -module RailtiesTest - # Holds tests shared between plugin and engines - module SharedTests - def boot_rails - super - require "#{app_path}/config/environment" - end - - def app - @app ||= Rails.application - end - - def test_serving_sprockets_assets - @plugin.write "app/assets/javascripts/engine.js.erb", "<%= :alert %>();" - - boot_rails - require 'rack/test' - extend Rack::Test::Methods - - get "/assets/engine.js" - assert_match "alert()", last_response.body - end - - def test_copying_migrations - @plugin.write "db/migrate/1_create_users.rb", <<-RUBY - class CreateUsers < ActiveRecord::Migration - end - RUBY - - @plugin.write "db/migrate/2_add_last_name_to_users.rb", <<-RUBY - class AddLastNameToUsers < ActiveRecord::Migration - end - RUBY - - @plugin.write "db/migrate/3_create_sessions.rb", <<-RUBY - class CreateSessions < ActiveRecord::Migration - end - RUBY - - app_file "db/migrate/1_create_sessions.rb", <<-RUBY - class CreateSessions < ActiveRecord::Migration - end - RUBY - - yaffle = plugin "acts_as_yaffle", "::LEVEL = config.log_level" do |plugin| - plugin.write "lib/acts_as_yaffle.rb", "class ActsAsYaffle; end" - end - - yaffle.write "db/migrate/1_create_yaffles.rb", <<-RUBY - class CreateYaffles < ActiveRecord::Migration - end - RUBY - - add_to_config "ActiveRecord::Base.timestamped_migrations = false" - - boot_rails - railties = Rails.application.railties.all.map(&:railtie_name) - - Dir.chdir(app_path) do - output = `bundle exec rake bukkits:install:migrations` - - assert File.exists?("#{app_path}/db/migrate/2_create_users.rb") - assert File.exists?("#{app_path}/db/migrate/3_add_last_name_to_users.rb") - assert_match(/Copied migration 2_create_users.rb from bukkits/, output) - assert_match(/Copied migration 3_add_last_name_to_users.rb from bukkits/, output) - assert_match(/NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/, output) - assert_equal 3, Dir["#{app_path}/db/migrate/*.rb"].length - - output = `bundle exec rake railties:install:migrations`.split("\n") - - assert File.exists?("#{app_path}/db/migrate/4_create_yaffles.rb") - assert_no_match(/2_create_users/, output.join("\n")) - - yaffle_migration_order = output.index(output.detect{|o| /Copied migration 4_create_yaffles.rb from acts_as_yaffle/ =~ o }) - bukkits_migration_order = output.index(output.detect{|o| /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/ =~ o }) - assert_not_nil yaffle_migration_order, "Expected migration to be copied" - assert_not_nil bukkits_migration_order, "Expected migration to be skipped" - assert_equal(railties.index('acts_as_yaffle') > railties.index('bukkits'), yaffle_migration_order > bukkits_migration_order) - - migrations_count = Dir["#{app_path}/db/migrate/*.rb"].length - output = `bundle exec rake railties:install:migrations` - - assert_equal migrations_count, Dir["#{app_path}/db/migrate/*.rb"].length - end - end - - def test_no_rake_task_without_migrations - boot_rails - require 'rake' - require 'rdoc/task' - require 'rake/testtask' - Rails.application.load_tasks - assert !Rake::Task.task_defined?('bukkits:install:migrations') - end - - def test_puts_its_lib_directory_on_load_path - boot_rails - require "another" - assert_equal "Another", Another.name - end - - def test_puts_its_models_directory_on_autoload_path - @plugin.write "app/models/my_bukkit.rb", "class MyBukkit ; end" - boot_rails - assert_nothing_raised { MyBukkit } - end - - def test_puts_its_controllers_directory_on_autoload_path - @plugin.write "app/controllers/bukkit_controller.rb", "class BukkitController ; end" - boot_rails - assert_nothing_raised { BukkitController } - end - - def test_adds_its_views_to_view_paths - @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY - class BukkitController < ActionController::Base - def index - end - end - RUBY - - @plugin.write "app/views/bukkit/index.html.erb", "Hello bukkits" - - boot_rails - - require "action_controller" - require "rack/mock" - response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/")) - assert_equal "Hello bukkits\n", response[2].body - end - - def test_adds_its_views_to_view_paths_with_lower_proriority_than_app_ones - @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY - class BukkitController < ActionController::Base - def index - end - end - RUBY - - @plugin.write "app/views/bukkit/index.html.erb", "Hello bukkits" - app_file "app/views/bukkit/index.html.erb", "Hi bukkits" - - boot_rails - - require "action_controller" - require "rack/mock" - response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/")) - assert_equal "Hi bukkits\n", response[2].body - end - - def test_adds_helpers_to_controller_views - @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY - class BukkitController < ActionController::Base - def index - end - end - RUBY - - @plugin.write "app/helpers/bukkit_helper.rb", <<-RUBY - module BukkitHelper - def bukkits - "bukkits" - end - end - RUBY - - @plugin.write "app/views/bukkit/index.html.erb", "Hello <%= bukkits %>" - - boot_rails - - require "rack/mock" - response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/")) - assert_equal "Hello bukkits\n", response[2].body - end - - def test_autoload_any_path_under_app - @plugin.write "app/anything/foo.rb", <<-RUBY - module Foo; end - RUBY - boot_rails - assert Foo - end - - def test_routes_are_added_to_router - @plugin.write "config/routes.rb", <<-RUBY - class Sprokkit - def self.call(env) - [200, {'Content-Type' => 'text/html'}, ["I am a Sprokkit"]] - end - end - - Rails.application.routes.draw do - match "/sprokkit", :to => Sprokkit - end - RUBY - - boot_rails - require 'rack/test' - extend Rack::Test::Methods - - get "/sprokkit" - assert_equal "I am a Sprokkit", last_response.body - end - - def test_routes_in_plugins_have_lower_priority_than_application_ones - controller "foo", <<-RUBY - class FooController < ActionController::Base - def index - render :text => "foo" - end - end - RUBY - - app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do - match 'foo', :to => 'foo#index' - end - RUBY - - @plugin.write "app/controllers/bar_controller.rb", <<-RUBY - class BarController < ActionController::Base - def index - render :text => "bar" - end - end - RUBY - - @plugin.write "config/routes.rb", <<-RUBY - Rails.application.routes.draw do - match 'foo', :to => 'bar#index' - match 'bar', :to => 'bar#index' - end - RUBY - - boot_rails - require 'rack/test' - extend Rack::Test::Methods - - get '/foo' - assert_equal 'foo', last_response.body - - get '/bar' - assert_equal 'bar', last_response.body - end - - def test_rake_tasks_lib_tasks_are_loaded - $executed = false - @plugin.write "lib/tasks/foo.rake", <<-RUBY - task :foo do - $executed = true - end - RUBY - - boot_rails - require 'rake' - require 'rdoc/task' - require 'rake/testtask' - Rails.application.load_tasks - Rake::Task[:foo].invoke - assert $executed - end - - def test_i18n_files_have_lower_priority_than_application_ones - add_to_config <<-RUBY - config.i18n.load_path << "#{app_path}/app/locales/en.yml" - RUBY - - app_file 'app/locales/en.yml', <<-YAML -en: - bar: "1" -YAML - - app_file 'config/locales/en.yml', <<-YAML -en: - foo: "2" - bar: "2" -YAML - - @plugin.write 'config/locales/en.yml', <<-YAML -en: - foo: "3" -YAML - - boot_rails - - expected_locales = %W( - #{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 - #{@plugin.path}/config/locales/en.yml - #{app_path}/config/locales/en.yml - #{app_path}/app/locales/en.yml - ).map { |path| File.expand_path(path) } - - actual_locales = I18n.load_path.map { |path| - File.expand_path(path) - } & expected_locales # remove locales external to Rails - - assert_equal expected_locales, actual_locales - - assert_equal "2", I18n.t(:foo) - assert_equal "1", I18n.t(:bar) - end - - def test_namespaced_controllers_with_namespaced_routes - @plugin.write "config/routes.rb", <<-RUBY - Rails.application.routes.draw do - namespace :admin do - namespace :foo do - match "bar", :to => "bar#index" - end - end - end - RUBY - - @plugin.write "app/controllers/admin/foo/bar_controller.rb", <<-RUBY - class Admin::Foo::BarController < ApplicationController - def index - render :text => "Rendered from namespace" - end - end - RUBY - - boot_rails - require 'rack/test' - extend Rack::Test::Methods - - get "/admin/foo/bar" - assert_equal 200, last_response.status - assert_equal "Rendered from namespace", last_response.body - end - - def test_initializers - $plugin_initializer = false - @plugin.write "config/initializers/foo.rb", <<-RUBY - $plugin_initializer = true - RUBY - - boot_rails - assert $plugin_initializer - end - - def test_midleware_referenced_in_configuration - @plugin.write "lib/bukkits.rb", <<-RUBY - class Bukkits - def initialize(app) - @app = app - end - - def call(env) - @app.call(env) - end - end - RUBY - - add_to_config "config.middleware.use \"Bukkits\"" - boot_rails - end - end -end |