diff options
Diffstat (limited to 'railties/test')
30 files changed, 1162 insertions, 198 deletions
diff --git a/railties/test/application/asset_debugging_test.rb b/railties/test/application/asset_debugging_test.rb new file mode 100644 index 0000000000..1b99af22a4 --- /dev/null +++ b/railties/test/application/asset_debugging_test.rb @@ -0,0 +1,65 @@ +require 'isolation/abstract_unit' +require 'rack/test' + +module ApplicationTests + class AssetDebuggingTest < Test::Unit::TestCase + include ActiveSupport::Testing::Isolation + include Rack::Test::Methods + + def setup + build_app(:initializers => true) + + 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 + + app_file "app/controllers/posts_controller.rb", <<-RUBY + class PostsController < ActionController::Base + end + RUBY + + ENV["RAILS_ENV"] = "production" + + boot_rails + end + + def teardown + teardown_app + end + + test "assets are concatenated when debug is off and compile is off either if debug_assets param is provided" do + # config.assets.debug and config.assets.compile are false for production environment + ENV["RAILS_ENV"] = "production" + capture(:stdout) do + Dir.chdir(app_path){ `bundle exec rake assets:precompile` } + end + 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_file "config/initializers/compile.rb", "Rails.application.config.assets.compile = 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 + end +end diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index 7fb930bd99..a22013f81c 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- require 'isolation/abstract_unit' require 'active_support/core_ext/kernel/reporting' require 'rack/test' @@ -20,8 +21,14 @@ module ApplicationTests @app ||= Rails.application end + 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 @@ -32,11 +39,13 @@ 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 %>();" + add_to_env_config "production", "config.assets.compile = true" + ENV["RAILS_ENV"] = "production" require "#{app_path}/config/environment" @@ -46,29 +55,250 @@ module ApplicationTests assert defined?(Uglifier) end - test "precompile creates the file and gives it the original asset's content" do + test "precompile creates the file, gives it the original asset's content and run in production as default" do app_file "app/assets/javascripts/application.js", "alert();" app_file "app/assets/javascripts/foo/application.js", "alert();" - capture(:stdout) do - Dir.chdir(app_path){ `bundle exec rake assets:precompile` } - end + ENV["RAILS_ENV"] = nil + 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();\n", File.read(file) + assert_equal "alert()", File.read(file) end end - test "precompile appends the md5 hash to files referenced with asset_path" do + test "precompile application.js and application.css and all other files not ending with .js or .css by default" 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{}" + + 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.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 + + 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") + end + + test "asset pipeline should use a Sprockets::Index when config.assets.digest is true" do + add_to_config "config.assets.digest = true" + add_to_config "config.action_controller.perform_caching = false" + + ENV["RAILS_ENV"] = "production" + require "#{app_path}/config/environment" + + assert_equal Sprockets::Index, Rails.application.assets.class + end + + test "precompile creates a manifest file with all the assets listed" do app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>" + 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" - capture(:stdout) do - Dir.chdir(app_path){ `bundle exec rake assets:precompile` } + precompile! + manifest = "#{app_path}/public/assets/manifest.yml" + + assets = YAML.load_file(manifest) + assert_match(/application-([0-z]+)\.js/, assets["application.js"]) + assert_match(/application-([0-z]+)\.css/, assets["application.css"]) + end + + test "precompile creates a manifest file in a custom path with all the assets listed" do + app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>" + 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.manifest = '#{app_path}/shared'" + + precompile! + manifest = "#{app_path}/shared/manifest.yml" + + assets = YAML.load_file(manifest) + assert_match(/application-([0-z]+)\.js/, assets["application.js"]) + 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'" + + precompile! + + manifest = "#{app_path}/public/x/manifest.yml" + assets = YAML.load_file(manifest) + assert_match(/application-([0-z]+)\.js/, assets["application.js"]) + end + + test "precompile does not append asset digests when config.assets.digest is false" do + app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>" + app_file "app/assets/javascripts/application.js", "alert();" + add_to_config "config.assets.digest = false" + + precompile! + + assert File.exists?("#{app_path}/public/assets/application.js") + assert File.exists?("#{app_path}/public/assets/application.css") + + manifest = "#{app_path}/public/assets/manifest.yml" + + assets = YAML.load_file(manifest) + assert_equal "application.js", assets["application.js"] + assert_equal "application.css", assets["application.css"] + end + + test "assets do not require any assets group gem when manifest file is present" do + app_file "app/assets/javascripts/application.js", "alert();" + add_to_env_config "production", "config.serve_static_assets = true" + + ENV["RAILS_ENV"] = "production" + precompile! + + manifest = "#{app_path}/public/assets/manifest.yml" + assets = YAML.load_file(manifest) + asset_path = assets["application.js"] + + require "#{app_path}/config/environment" + + # Checking if Uglifier is defined we can know if Sprockets was reached or not + assert !defined?(Uglifier) + get "/assets/#{asset_path}" + assert_match "alert()", last_response.body + assert !defined?(Uglifier) + end + + test "assets raise AssetNotPrecompiledError when manifest file is present and requested file isn't precompiled" do + app_file "app/views/posts/index.html.erb", "<%= javascript_include_tag 'app' %>" + + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do + match '/posts', :to => "posts#index" + end + RUBY + + ENV["RAILS_ENV"] = "production" + precompile! + + # Create file after of precompile + app_file "app/assets/javascripts/app.js", "alert();" + + require "#{app_path}/config/environment" + class ::PostsController < ActionController::Base ; end + + get '/posts' + assert_match(/AssetNotPrecompiledError/, last_response.body) + assert_match(/app.js isn't precompiled/, last_response.body) + end + + test "assets raise AssetNotPrecompiledError when manifest file is present and requested file isn't precompiled if digest is disabled" do + app_file "app/views/posts/index.html.erb", "<%= javascript_include_tag 'app' %>" + add_to_config "config.assets.compile = false" + + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do + match '/posts', :to => "posts#index" + end + RUBY + + ENV["RAILS_ENV"] = "development" + precompile! + + # Create file after of precompile + app_file "app/assets/javascripts/app.js", "alert();" + + require "#{app_path}/config/environment" + class ::PostsController < ActionController::Base ; end + + get '/posts' + assert_match(/AssetNotPrecompiledError/, last_response.body) + assert_match(/app.js isn't precompiled/, last_response.body) + end + + 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_env_config "test", "config.assets.digest = true" + + quietly do + Dir.chdir(app_path){ `bundle exec rake assets:precompile RAILS_ENV=test` } 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) + 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 + quietly do + Dir.chdir(app_path){ `bundle exec rake assets:precompile RAILS_GROUPS=assets` } + end + file = Dir["#{app_path}/public/assets/application-*.css"].first + assert_match(/\/assets\/rails-([0-z]+)\.png/, File.read(file)) + end + + test "precompile should handle utf8 filenames" do + filename = "レイルズ.png" + app_file "app/assets/images/#{filename}", "not a image really" + add_to_config "config.assets.precompile = [ /\.png$/, /application.(css|js)$/ ]" + + precompile! + require "#{app_path}/config/environment" + + 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 @@ -76,14 +306,25 @@ 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/**/*"] + files = Dir["#{app_path}/public/assets/**/*", "#{app_path}/tmp/cache/*"] assert_equal 0, files.length, "Expected no assets, but found #{files.join(', ')}" end + test "assets routes are not drawn when compilation is disabled" do + app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();" + add_to_config "config.assets.compile = false" + + ENV["RAILS_ENV"] = "production" + require "#{app_path}/config/environment" + + get "/assets/demo.js" + assert_equal 404, last_response.status + end + test "does not stream session cookies back" do app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();" @@ -109,5 +350,141 @@ module ApplicationTests assert_match "alert()", last_response.body assert_equal nil, last_response.headers["Set-Cookie"] end + + test "files in any assets/ directories are not added to Sprockets" do + %w[app lib vendor].each do |dir| + app_file "#{dir}/assets/#{dir}_test.erb", "testing" + end + + app_file "app/assets/javascripts/demo.js", "alert();" + + require "#{app_path}/config/environment" + + get "/assets/demo.js" + 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 "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 + + + 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/configuration_test.rb b/railties/test/application/configuration_test.rb index 448982f9de..28ffff58ca 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -306,7 +306,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 +319,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 +332,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 +345,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 @@ -476,7 +476,7 @@ module ApplicationTests app_file 'app/controllers/posts_controller.rb', <<-RUBY class PostsController < ApplicationController - def index + def create render :text => params[:post].inspect end end @@ -521,9 +521,11 @@ 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 end end diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb index 1528d5dd87..2073c780bf 100644 --- a/railties/test/application/console_test.rb +++ b/railties/test/application/console_test.rb @@ -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 @@ -66,12 +70,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/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb index e656ada3c0..050a2161ae 100644 --- a/railties/test/application/middleware/cache_test.rb +++ b/railties/test/application/middleware/cache_test.rb @@ -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..13556cbed2 --- /dev/null +++ b/railties/test/application/middleware/cookies_test.rb @@ -0,0 +1,47 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class CookiesTest < Test::Unit::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/sendfile_test.rb b/railties/test/application/middleware/sendfile_test.rb index c7a1c573f9..d2ad2668bb 100644 --- a/railties/test/application/middleware/sendfile_test.rb +++ b/railties/test/application/middleware/sendfile_test.rb @@ -27,11 +27,12 @@ module ApplicationTests end # x_sendfile_header middleware - test "config.action_dispatch.x_sendfile_header defaults to ''" do + test "config.action_dispatch.x_sendfile_header defaults to nil" do make_basic_app simple_controller get "/" + assert !last_response.headers["X-Sendfile"] assert_equal File.read(__FILE__), last_response.body end diff --git a/railties/test/application/middleware/show_exceptions_test.rb b/railties/test/application/middleware/show_exceptions_test.rb index e3f27f63c3..7dbadc6ce3 100644 --- a/railties/test/application/middleware/show_exceptions_test.rb +++ b/railties/test/application/middleware/show_exceptions_test.rb @@ -1,27 +1,23 @@ +# encoding: utf-8 require 'isolation/abstract_unit' +require 'rack/test' module ApplicationTests class ShowExceptionsTest < Test::Unit::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 "unspecified route when set action_dispatch.show_exceptions to false" do - make_basic_app do |app| - app.config.action_dispatch.show_exceptions = false - end + app.config.action_dispatch.show_exceptions = false assert_raise(ActionController::RoutingError) do get '/foo' @@ -29,13 +25,36 @@ module ApplicationTests 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 + app.config.action_dispatch.show_exceptions = true assert_nothing_raised(ActionController::RoutingError) do get '/foo' end end + + test "displays diagnostics message when exception raised in template that contains UTF-8" do + app.config.action_dispatch.show_exceptions = 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) + end end end diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb index bed5ba503f..4703a59326 100644 --- a/railties/test/application/middleware_test.rb +++ b/railties/test/application/middleware_test.rb @@ -30,6 +30,7 @@ module ApplicationTests "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::RemoteIp", @@ -69,6 +70,14 @@ module ApplicationTests assert middleware.include?("Rack::SSL") end + test "Rack::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 use_frameworks [] boot! diff --git a/railties/test/application/rack/logger_test.rb b/railties/test/application/rack/logger_test.rb index 8b2b2f1802..387eb25525 100644 --- a/railties/test/application/rack/logger_test.rb +++ b/railties/test/application/rack/logger_test.rb @@ -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..86e1995def 100644 --- a/railties/test/application/rackup_test.rb +++ b/railties/test/application/rackup_test.rb @@ -6,7 +6,7 @@ module ApplicationTests 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_test.rb b/railties/test/application/rake_test.rb index cc65a674c9..c76bc3d526 100644 --- a/railties/test/application/rake_test.rb +++ b/railties/test/application/rake_test.rb @@ -1,3 +1,4 @@ +# coding:utf-8 require "isolation/abstract_unit" module ApplicationTests @@ -79,13 +80,13 @@ module ApplicationTests 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 + 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) end end - def test_rake_routes_output_strips_anchors_from_http_verbs + def test_rake_routes_calls_the_route_inspector app_file "config/routes.rb", <<-RUBY AppTemplate::Application.routes.draw do get '/cart', :to => 'cart#show' @@ -94,99 +95,6 @@ module ApplicationTests assert_equal "cart GET /cart(.:format) cart#show\n", Dir.chdir(app_path){ `rake routes` } end - def test_rake_routes_shows_custom_assets - app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do - get '/custom/assets', :to => 'custom_assets#show' - end - RUBY - assert_equal "custom_assets GET /custom/assets(.:format) custom_assets#show\n", - Dir.chdir(app_path){ `rake routes` } - end - - def test_rake_routes_shows_resources_route - app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do - resources :articles - end - RUBY - expected = - " articles GET /articles(.:format) articles#index\n" << - " POST /articles(.:format) articles#create\n" << - " new_article GET /articles/new(.:format) articles#new\n" << - "edit_article GET /articles/:id/edit(.:format) articles#edit\n" << - " article GET /articles/:id(.:format) articles#show\n" << - " PUT /articles/:id(.:format) articles#update\n" << - " DELETE /articles/:id(.:format) articles#destroy\n" - assert_equal expected, Dir.chdir(app_path){ `rake routes` } - end - - def test_rake_routes_shows_root_route - app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do - root :to => 'pages#main' - end - RUBY - assert_equal "root / pages#main\n", Dir.chdir(app_path){ `rake routes` } - end - - def test_rake_routes_shows_controller_and_action_only_route - app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do - match ':controller/:action' - end - RUBY - assert_equal " /:controller/:action(.:format) \n", Dir.chdir(app_path){ `rake routes` } - end - - def test_rake_routes_shows_controller_and_action_route_with_constraints - app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do - match ':controller(/:action(/:id))', :id => /\\d+/ - end - RUBY - assert_equal " /:controller(/:action(/:id))(.:format) {:id=>/\\d+/}\n", Dir.chdir(app_path){ `rake routes` } - end - - def test_rake_routes_shows_route_with_defaults - app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do - match 'photos/:id' => 'photos#show', :defaults => {:format => 'jpg'} - end - RUBY - assert_equal %Q[ /photos/:id(.:format) photos#show {:format=>"jpg"}\n], Dir.chdir(app_path){ `rake routes` } - end - - def test_rake_routes_shows_route_with_constraints - app_file "config/routes.rb", <<-RUBY - AppTemplate::Application.routes.draw do - match 'photos/:id' => 'photos#show', :id => /[A-Z]\\d{5}/ - end - RUBY - assert_equal " /photos/:id(.:format) photos#show {:id=>/[A-Z]\\d{5}/}\n", Dir.chdir(app_path){ `rake routes` } - end - - def test_rake_routes_shows_route_with_rack_app - app_file "lib/rack_app.rb", <<-RUBY - class RackApp - class << self - def call(env) - end - end - end - RUBY - - app_file "config/routes.rb", <<-RUBY - require 'rack_app' - - AppTemplate::Application.routes.draw do - match 'foo/:id' => RackApp, :id => /[A-Z]\\d{5}/ - end - RUBY - - assert_equal " /foo/:id(.:format) RackApp {:id=>/[A-Z]\\d{5}/}\n", Dir.chdir(app_path){ `rake routes` } - end - def test_logger_is_flushed_when_exiting_production_rake_tasks add_to_config <<-RUBY rake_tasks do @@ -219,6 +127,55 @@ module ApplicationTests assert_match(/AddEmailToUsers: reverted/, output) end + 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 + 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` + 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) + end + + def test_migration_status_after_rollback_and_redo + Dir.chdir(app_path) do + `rails generate model user username:string password:string` + `rails generate migration add_email_to_users email:string` + 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) + + Dir.chdir(app_path) { `rake db:migrate:redo` } + 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) + end + def test_loading_specific_fixtures Dir.chdir(app_path) do `rails generate model user username:string password:string` @@ -245,4 +202,4 @@ module ApplicationTests assert_match(/7 tests, 10 assertions, 0 failures, 0 errors/, content) end end -end
\ No newline at end of file +end diff --git a/railties/test/application/route_inspect_test.rb b/railties/test/application/route_inspect_test.rb new file mode 100644 index 0000000000..2ad5ee6c4c --- /dev/null +++ b/railties/test/application/route_inspect_test.rb @@ -0,0 +1,131 @@ +require 'test/unit' +require 'rails/application/route_inspector' +require 'action_controller' +require 'rails/engine' + +module ApplicationTests + class RouteInspectTest < Test::Unit::TestCase + def setup + @set = ActionDispatch::Routing::RouteSet.new + @inspector = Rails::Application::RouteInspector.new + 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 + @set.draw do + get '/cart', :to => 'cart#show' + end + output = @inspector.format @set.routes + assert_equal ["cart GET /cart(.:format) cart#show"], output + end + + def test_inspect_shows_custom_assets + @set.draw do + get '/custom/assets', :to => 'custom_assets#show' + end + output = @inspector.format @set.routes + assert_equal ["custom_assets GET /custom/assets(.:format) custom_assets#show"], output + end + + def test_inspect_routes_shows_resources_route + @set.draw do + resources :articles + end + output = @inspector.format @set.routes + expected = [ + " articles GET /articles(.:format) articles#index", + " POST /articles(.:format) articles#create", + " new_article GET /articles/new(.:format) articles#new", + "edit_article GET /articles/:id/edit(.:format) articles#edit", + " article GET /articles/:id(.:format) articles#show", + " PUT /articles/:id(.:format) articles#update", + " DELETE /articles/:id(.:format) articles#destroy" ] + assert_equal expected, output + end + + def test_inspect_routes_shows_root_route + @set.draw do + root :to => 'pages#main' + end + output = @inspector.format @set.routes + 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) :controller#:action"], output + end + + def test_inspect_routes_shows_controller_and_action_route_with_constraints + @set.draw do + match ':controller(/:action(/:id))', :id => /\d+/ + end + output = @inspector.format @set.routes + assert_equal [" /:controller(/:action(/:id))(.:format) :controller#:action {:id=>/\\d+/}"], output + end + + def test_rake_routes_shows_route_with_defaults + @set.draw do + match 'photos/:id' => 'photos#show', :defaults => {:format => 'jpg'} + end + output = @inspector.format @set.routes + assert_equal [%Q[ /photos/:id(.:format) photos#show {:format=>"jpg"}]], output + end + + def test_rake_routes_shows_route_with_constraints + @set.draw do + match 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/ + end + output = @inspector.format @set.routes + assert_equal [" /photos/:id(.:format) photos#show {:id=>/[A-Z]\\d{5}/}"], output + end + + class RackApp + def self.call(env) + end + end + + def test_rake_routes_shows_route_with_rack_app + @set.draw do + match 'foo/:id' => RackApp, :id => /[A-Z]\d{5}/ + end + output = @inspector.format @set.routes + assert_equal [" /foo/:id(.:format) #{RackApp.name} {:id=>/[A-Z]\\d{5}/}"], output + end + end +end diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb index 3adf0ccd3e..a05e39658d 100644 --- a/railties/test/application/routing_test.rb +++ b/railties/test/application/routing_test.rb @@ -141,7 +141,7 @@ module ApplicationTests test "routes appending blocks" do app_file 'config/routes.rb', <<-RUBY AppTemplate::Application.routes.draw do - match ':controller#:action' + match ':controller/:action' end RUBY diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb index 27a7959e84..a06facc04b 100644 --- a/railties/test/application/test_test.rb +++ b/railties/test/application/test_test.rb @@ -24,7 +24,7 @@ module ApplicationTests end RUBY - run_test 'unit/foo_test.rb' + run_test_file 'unit/foo_test.rb' end # Run just in Ruby < 1.9 @@ -40,7 +40,7 @@ module ApplicationTests end RUBY - run_test 'unit/backtrace_test.rb' + run_test_file 'unit/backtrace_test.rb' end end @@ -66,7 +66,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 +91,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/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 e4a8000425..c1fd6a38f1 100644 --- a/railties/test/generators/actions_test.rb +++ b/railties/test/generators/actions_test.rb @@ -95,18 +95,34 @@ 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 + run_generator + + action :gem_group, :development, :test do + gem 'rspec-rails' + end + + action :gem_group, :test do + gem 'fakeweb' + end + + assert_file 'Gemfile', /\ngroup :development, :test do\n gem "rspec-rails"\nend\n\ngroup :test do\n gem "fakeweb"\nend/ end def test_environment_should_include_data_in_environment_initializer_block run_generator autoload_paths = 'config.autoload_paths += %w["#{Rails.root}/app/extras"]' action :environment, autoload_paths - assert_file 'config/application.rb', /#{Regexp.escape(autoload_paths)}/ + assert_file 'config/application.rb', / class Application < Rails::Application\n #{Regexp.escape(autoload_paths)}/ end def test_environment_should_include_data_in_environment_initializer_block_with_env_option @@ -165,9 +181,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 @@ -175,9 +194,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 diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index fb7ebaa1fa..235c08e38e 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -55,6 +55,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 @@ -143,6 +144,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/ @@ -189,7 +200,7 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "test/performance/browsing_test.rb" end - def test_generator_if_skip_active_record_is_given + 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) @@ -198,11 +209,28 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "test/performance/browsing_test.rb" end + def test_inclusion_of_therubyrhino_under_jruby + if defined?(JRUBY_VERSION) + run_generator([destination_root]) + assert_file "Gemfile", /gem\s+["']therubyrhino["']$/ + 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,21 +260,6 @@ class AppGeneratorTest < Rails::Generators::TestCase end end - def test_inclusion_of_turn_gem_in_gemfile - 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| @@ -314,6 +327,15 @@ class AppGeneratorTest < Rails::Generators::TestCase end end + def test_generated_environments_file_for_sanitizer + 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) + end + end + end + protected def action(*args, &block) 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/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 0ccb2ae9da..826eac904e 100644 --- a/railties/test/generators/plugin_new_generator_test.rb +++ b/railties/test/generators/plugin_new_generator_test.rb @@ -7,11 +7,13 @@ DEFAULT_PLUGIN_FILES = %w( .gitignore Gemfile Rakefile + README.rdoc bukkits.gemspec MIT-LICENSE lib lib/bukkits.rb lib/tasks/bukkits_tasks.rake + lib/bukkits/version.rb test/bukkits_test.rb test/test_helper.rb test/dummy @@ -25,10 +27,6 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase # brings setup, teardown, and some tests include SharedGeneratorTests - def default_files - ::DEFAULT_PLUGIN_FILES - end - 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 @@ -39,6 +37,12 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase assert_file "things-43/lib/things-43.rb", /module Things43/ end + 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 run_generator assert_file "README.rdoc", /Bukkits/ @@ -69,13 +73,13 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase def test_database_entry_is_generated_for_sqlite3_by_default_in_full_mode run_generator([destination_root, "--full"]) assert_file "test/dummy/config/database.yml", /sqlite/ - assert_file "Gemfile", /^gem\s+["']sqlite3["']$/ + assert_file "bukkits.gemspec", /sqlite3/ end def test_config_another_database run_generator([destination_root, "-d", "mysql", "--full"]) assert_file "test/dummy/config/database.yml", /mysql/ - assert_file "Gemfile", /^gem\s+["']mysql2["']$/ + assert_file "bukkits.gemspec", /mysql/ end def test_active_record_is_removed_from_frameworks_if_skip_active_record_is_given @@ -117,8 +121,8 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase assert_match %r{^//= require jquery}, contents assert_match %r{^//= require jquery_ujs}, contents end - assert_file 'Gemfile' do |contents| - assert_match(/^gem 'jquery-rails'/, contents) + assert_file 'bukkits.gemspec' do |contents| + assert_match(/jquery-rails/, contents) end end @@ -128,8 +132,8 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase assert_match %r{^//= require prototype}, contents assert_match %r{^//= require prototype_ujs}, contents end - assert_file 'Gemfile' do |contents| - assert_match(/^gem 'prototype-rails'/, contents) + assert_file 'bukkits.gemspec' do |contents| + assert_match(/prototype-rails/, contents) end end @@ -176,6 +180,7 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase assert_file "app/controllers" assert_file "app/views" assert_file "app/helpers" + assert_file "app/mailers" assert_file "config/routes.rb", /Rails.application.routes.draw do/ assert_file "lib/bukkits/engine.rb", /module Bukkits\n class Engine < ::Rails::Engine\n end\nend/ assert_file "lib/bukkits.rb", /require "bukkits\/engine"/ @@ -198,17 +203,17 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase assert_file "app/helpers/bukkits/application_helper.rb", /module Bukkits\n module ApplicationHelper/ assert_file "app/views/layouts/bukkits/application.html.erb" do |contents| assert_match "<title>Bukkits</title>", contents - assert_match /stylesheet_link_tag\s+['"]bukkits\/application['"]/, contents - assert_match /javascript_include_tag\s+['"]bukkits\/application['"]/, contents + assert_match(/stylesheet_link_tag\s+['"]bukkits\/application['"]/, contents) + assert_match(/javascript_include_tag\s+['"]bukkits\/application['"]/, contents) end end def test_creating_gemspec run_generator - assert_file "bukkits.gemspec", /s.name = "bukkits"/ + assert_file "bukkits.gemspec", /s.name\s+= "bukkits"/ assert_file "bukkits.gemspec", /s.files = Dir\["\{app,config,db,lib\}\/\*\*\/\*"\]/ assert_file "bukkits.gemspec", /s.test_files = Dir\["test\/\*\*\/\*"\]/ - assert_file "bukkits.gemspec", /s.version = "0.0.1"/ + assert_file "bukkits.gemspec", /s.version\s+ = Bukkits::VERSION/ end def test_usage_of_engine_commands @@ -237,12 +242,20 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase assert_file "spec/dummy/config/application.rb" 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" assert_file "bukkits.gemspec" do |contents| - assert_no_match /s.test_files = Dir\["test\/\*\*\/\*"\]/, contents + assert_no_match(/s.test_files = Dir\["test\/\*\*\/\*"\]/, contents) end end @@ -257,6 +270,10 @@ protected silence(:stdout){ generator.send(*args, &block) } end +protected + def default_files + ::DEFAULT_PLUGIN_FILES + end end class CustomPluginGeneratorTest < Rails::Generators::TestCase diff --git a/railties/test/generators/shared_generator_tests.rb b/railties/test/generators/shared_generator_tests.rb index d3074afd91..1534f0d828 100644 --- a/railties/test/generators/shared_generator_tests.rb +++ b/railties/test/generators/shared_generator_tests.rb @@ -191,11 +191,11 @@ module SharedCustomGeneratorTests end def test_builder_option_with_http - path = "http://gist.github.com/103208.txt" + url = "http://gist.github.com/103208.txt" template = "class #{builder_class}; end" template.instance_eval "def read; self; end" # Make the string respond to read - generator([destination_root], :builder => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) + generator([destination_root], :builder => url).expects(:open).with(url, 'Accept' => 'application/x-thor-template').returns(template) quietly { generator.invoke_all } default_files.each{ |path| assert_no_file(path) } diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index 56329f3183..5f9ee220dc 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -201,4 +201,10 @@ 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 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 685d1b154b..06b658e7bd 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -224,6 +224,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) @@ -282,7 +291,7 @@ Module.new do require_environment = "-r #{environment}" end - `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/bin/rails new #{tmp_path('app_template')}` + `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails new #{tmp_path('app_template')}` File.open("#{tmp_path}/app_template/config/boot.rb", 'w') do |f| if require_environment f.puts "Dir.chdir('#{File.dirname(environment)}') do" diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb index 0ff1e0f180..400cae98b2 100644 --- a/railties/test/railties/engine_test.rb +++ b/railties/test/railties/engine_test.rb @@ -323,7 +323,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) @@ -400,7 +400,7 @@ module RailtiesTest boot_rails get("/bukkits/posts/new") - assert_match /name="post\[title\]"/, last_response.body + assert_match(/name="post\[title\]"/, last_response.body) end test "isolated engine should set correct route module prefix for nested namespace" do @@ -455,13 +455,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 +484,7 @@ module RailtiesTest boot_rails - assert_equal AppTemplate._railtie, AppTemplate::Engine + assert_equal AppTemplate.railtie_namespace, AppTemplate::Engine end test "properly reload routes" do @@ -661,6 +667,132 @@ module RailtiesTest 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 + require "#{rails_root}/config/environment" + + 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 + require "#{rails_root}/config/environment" + + get("/foo") + assert_equal "Bukkit's foo partial", last_response.body.strip + end + private def app Rails.application diff --git a/railties/test/railties/generators_test.rb b/railties/test/railties/generators_test.rb index 1d4ba0e5b6..f8540d69d9 100644 --- a/railties/test/railties/generators_test.rb +++ b/railties/test/railties/generators_test.rb @@ -28,7 +28,7 @@ module RailtiesTests if File.exist?("#{environment}.rb") require_environment = "-r #{environment}" end - `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/bin/rails #{cmd}` + `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails #{cmd}` end def build_engine(is_mountable=false) diff --git a/railties/test/railties/mounted_engine_test.rb b/railties/test/railties/mounted_engine_test.rb index 94dec405a7..0491fc2174 100644 --- a/railties/test/railties/mounted_engine_test.rb +++ b/railties/test/railties/mounted_engine_test.rb @@ -11,13 +11,17 @@ module ApplicationTests add_to_config("config.action_dispatch.show_exceptions = false") + @simple_plugin = engine "weblog" @plugin = engine "blog" app_file 'config/routes.rb', <<-RUBY AppTemplate::Application.routes.draw do + mount Weblog::Engine, :at => '/', :as => 'weblog' resources :posts match "/engine_route" => "application_generating#engine_route" match "/engine_route_in_view" => "application_generating#engine_route_in_view" + match "/weblog_engine_route" => "application_generating#weblog_engine_route" + match "/weblog_engine_route_in_view" => "application_generating#weblog_engine_route_in_view" match "/url_for_engine_route" => "application_generating#url_for_engine_route" match "/polymorphic_route" => "application_generating#polymorphic_route" match "/application_polymorphic_path" => "application_generating#application_polymorphic_path" @@ -28,6 +32,29 @@ module ApplicationTests end RUBY + + @simple_plugin.write "lib/weblog.rb", <<-RUBY + module Weblog + class Engine < ::Rails::Engine + end + end + RUBY + + @simple_plugin.write "config/routes.rb", <<-RUBY + Weblog::Engine.routes.draw do + match '/weblog' => "weblogs#index", :as => 'weblogs' + end + RUBY + + @simple_plugin.write "app/controllers/weblogs_controller.rb", <<-RUBY + class WeblogsController < ActionController::Base + def index + render :text => request.url + end + end + RUBY + + @plugin.write "app/models/blog/post.rb", <<-RUBY module Blog class Post @@ -100,6 +127,14 @@ module ApplicationTests render :inline => "<%= blog.posts_path %>" end + def weblog_engine_route + render :text => weblog.weblogs_path + end + + def weblog_engine_route_in_view + render :inline => "<%= weblog.weblogs_path %>" + end + def url_for_engine_route render :text => blog.url_for(:controller => "blog/posts", :action => "index", :user => "john", :only_path => true) end @@ -192,5 +227,13 @@ module ApplicationTests get "/application_polymorphic_path" assert_equal "/posts/44", last_response.body end + + test "route path for controller action when engine is mounted at root" do + get "/weblog_engine_route" + assert_equal "/weblog", last_response.body + + get "/weblog_engine_route_in_view" + assert_equal "/weblog", last_response.body + end end end diff --git a/railties/test/railties/shared_tests.rb b/railties/test/railties/shared_tests.rb index 9a64b7c64e..7653e52d26 100644 --- a/railties/test/railties/shared_tests.rb +++ b/railties/test/railties/shared_tests.rb @@ -21,6 +21,23 @@ module RailtiesTest assert_match "alert()", last_response.body end + def test_rake_environment_can_be_called_in_the_engine_or_plugin + 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 + def test_copying_migrations @plugin.write "db/migrate/1_create_users.rb", <<-RUBY class CreateUsers < ActiveRecord::Migration @@ -61,21 +78,21 @@ module RailtiesTest 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_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") + 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) + 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` |