diff options
Diffstat (limited to 'railties/test')
46 files changed, 1446 insertions, 271 deletions
diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb index b6533a5fb2..0749615d03 100644 --- a/railties/test/abstract_unit.rb +++ b/railties/test/abstract_unit.rb @@ -28,24 +28,26 @@ def jruby_skip(message = '') end class ActiveSupport::TestCase + # FIXME: we have tests that depend on run order, we should fix that and + # remove this method call. + self.test_order = :sorted + private - unless defined?(:capture) - def capture(stream) - stream = stream.to_s - captured_stream = Tempfile.new(stream) - stream_io = eval("$#{stream}") - origin_stream = stream_io.dup - stream_io.reopen(captured_stream) - - yield - - stream_io.rewind - return captured_stream.read - ensure - captured_stream.close - captured_stream.unlink - stream_io.reopen(origin_stream) - end + def capture(stream) + stream = stream.to_s + captured_stream = Tempfile.new(stream) + stream_io = eval("$#{stream}") + origin_stream = stream_io.dup + stream_io.reopen(captured_stream) + + yield + + stream_io.rewind + return captured_stream.read + ensure + captured_stream.close + captured_stream.unlink + stream_io.reopen(origin_stream) end end diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index 8f091cfdbf..d58a27403e 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -225,7 +225,7 @@ module ApplicationTests test "assets do not require any assets group gem when manifest file is present" do app_file "app/assets/javascripts/application.js", "alert();" - add_to_env_config "production", "config.serve_static_assets = true" + add_to_env_config "production", "config.serve_static_files = true" ENV["RAILS_ENV"] = "production" precompile! diff --git a/railties/test/application/configuration/base_test.rb b/railties/test/application/configuration/base_test.rb new file mode 100644 index 0000000000..d6a82b139d --- /dev/null +++ b/railties/test/application/configuration/base_test.rb @@ -0,0 +1,37 @@ +require 'isolation/abstract_unit' +require 'rack/test' +require 'env_helpers' + +module ApplicationTests + module ConfigurationTests + class BaseTest < ActiveSupport::TestCase + def setup + build_app + boot_rails + FileUtils.rm_rf("#{app_path}/config/environments") + end + + def teardown + teardown_app + FileUtils.rm_rf(new_app) if File.directory?(new_app) + end + + private + def new_app + File.expand_path("#{app_path}/../new_app") + end + + def copy_app + FileUtils.cp_r(app_path, new_app) + end + + def app + @app ||= Rails.application + end + + def require_environment + require "#{app_path}/config/environment" + end + end + end +end
\ No newline at end of file diff --git a/railties/test/application/configuration/custom_test.rb b/railties/test/application/configuration/custom_test.rb new file mode 100644 index 0000000000..f8d22f6d97 --- /dev/null +++ b/railties/test/application/configuration/custom_test.rb @@ -0,0 +1,22 @@ +require 'application/configuration/base_test' + +class ApplicationTests::ConfigurationTests::CustomTest < ApplicationTests::ConfigurationTests::BaseTest + test 'access custom configuration point' do + add_to_config <<-RUBY + config.x.payment_processing.schedule = :daily + config.x.payment_processing.retries = 3 + config.x.super_debugger = true + config.x.hyper_debugger = false + config.x.nil_debugger = nil + RUBY + require_environment + + x = Rails.configuration.x + assert_equal :daily, x.payment_processing.schedule + assert_equal 3, x.payment_processing.retries + assert_equal true, x.super_debugger + assert_equal false, x.hyper_debugger + assert_equal nil, x.nil_debugger + assert_nil x.i_do_not_exist.zomg + end +end diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 21244188dd..ad15e30b6a 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -41,7 +41,7 @@ module ApplicationTests def setup build_app boot_rails - FileUtils.rm_rf("#{app_path}/config/environments") + supress_default_config end def teardown @@ -49,6 +49,15 @@ module ApplicationTests FileUtils.rm_rf(new_app) if File.directory?(new_app) end + def supress_default_config + FileUtils.mv("#{app_path}/config/environments", "#{app_path}/config/__environments__") + end + + def restore_default_config + FileUtils.rm_rf("#{app_path}/config/environments") + FileUtils.mv("#{app_path}/config/__environments__", "#{app_path}/config/environments") + end + test "Rails.env does not set the RAILS_ENV environment variable which would leak out into rake tasks" do require "rails" @@ -59,6 +68,20 @@ module ApplicationTests end end + test "lib dir is on LOAD_PATH during config" do + app_file 'lib/my_logger.rb', <<-RUBY + require "logger" + class MyLogger < ::Logger + end + RUBY + add_to_top_of_config <<-RUBY + require 'my_logger' + config.logger = MyLogger.new STDOUT + RUBY + require "#{app_path}/config/environment" + assert_equal 'MyLogger', Rails.application.config.logger.class.name + end + test "a renders exception on pending migration" do add_to_config <<-RUBY config.active_record.migration_error = :page_load @@ -118,7 +141,7 @@ module ApplicationTests test "Rails::Application responds to paths" do require "#{app_path}/config/environment" assert_respond_to AppTemplate::Application, :paths - assert_equal AppTemplate::Application.paths["app/views"].expanded, ["#{app_path}/app/views"] + assert_equal ["#{app_path}/app/views"], AppTemplate::Application.paths["app/views"].expanded end test "the application root is set correctly" do @@ -182,7 +205,7 @@ module ApplicationTests test "application is always added to eager_load namespaces" do require "#{app_path}/config/application" - assert Rails.application, Rails.application.config.eager_load_namespaces + assert_includes Rails.application.config.eager_load_namespaces, AppTemplate::Application end test "the application can be eager loaded even when there are no frameworks" do @@ -266,10 +289,57 @@ module ApplicationTests assert_equal Pathname.new(app_path).join("somewhere"), Rails.public_path end + test "In production mode, config.serve_static_files is off by default" do + restore_default_config + + with_rails_env "production" do + require "#{app_path}/config/environment" + assert_not app.config.serve_static_files + end + end + + test "In production mode, config.serve_static_files is enabled when RAILS_SERVE_STATIC_FILES is set" do + restore_default_config + + with_rails_env "production" do + switch_env "RAILS_SERVE_STATIC_FILES", "1" do + require "#{app_path}/config/environment" + assert app.config.serve_static_files + end + end + end + + test "In production mode, config.serve_static_files is disabled when RAILS_SERVE_STATIC_FILES is blank" do + restore_default_config + + with_rails_env "production" do + switch_env "RAILS_SERVE_STATIC_FILES", " " do + require "#{app_path}/config/environment" + assert_not app.config.serve_static_files + end + end + end + + test "config.serve_static_assets is deprecated" do + require "#{app_path}/config/application" + + assert_deprecated(/serve_static_assets/) do + app.config.serve_static_assets = false + end + + assert_not app.config.serve_static_files + assert_deprecated(/serve_static_assets/) { assert_not app.config.serve_static_assets } + + app.config.serve_static_files = true + + assert app.config.serve_static_files + assert_deprecated(/serve_static_assets/) { assert app.config.serve_static_assets } + end + test "Use key_generator when secret_key_base is set" do - make_basic_app do |app| - app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' - app.config.session_store :disabled + make_basic_app do |application| + application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' + application.config.session_store :disabled end class ::OmgController < ActionController::Base @@ -287,9 +357,9 @@ module ApplicationTests end test "application verifier can be used in the entire application" do - make_basic_app do |app| - app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' - app.config.session_store :disabled + make_basic_app do |application| + application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' + application.config.session_store :disabled end message = app.message_verifier(:sensitive_value).generate("some_value") @@ -301,10 +371,55 @@ module ApplicationTests assert_equal 'some_value', verifier.verify(message) end + test "application message verifier can be used when the key_generator is ActiveSupport::LegacyKeyGenerator" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + require "#{app_path}/config/environment" + + + assert_equal app.env_config['action_dispatch.key_generator'], Rails.application.key_generator + assert_equal app.env_config['action_dispatch.key_generator'].class, ActiveSupport::LegacyKeyGenerator + message = app.message_verifier(:sensitive_value).generate("some_value") + assert_equal 'some_value', Rails.application.message_verifier(:sensitive_value).verify(message) + end + + test "warns when secrets.secret_key_base is blank and config.secret_token is set" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + require "#{app_path}/config/environment" + + assert_deprecated(/You didn't set `secret_key_base`./) do + app.env_config + end + end + + test "prefer secrets.secret_token over config.secret_token" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_token: 3b7cd727ee24e8444053437c36cc66c3 + YAML + require "#{app_path}/config/environment" + + assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token + end + test "application verifier can build different verifiers" do - make_basic_app do |app| - app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' - app.config.session_store :disabled + make_basic_app do |application| + application.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' + application.config.session_store :disabled end default_verifier = app.message_verifier(:sensitive_value) @@ -341,6 +456,21 @@ module ApplicationTests assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_key_base end + test "config.secret_token over-writes a blank secrets.secret_token" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + secret_token: + YAML + require "#{app_path}/config/environment" + + assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.secrets.secret_token + assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token + end + test "custom secrets saved in config/secrets.yml are loaded in app secrets" do app_file 'config/secrets.yml', <<-YAML development: @@ -362,6 +492,51 @@ module ApplicationTests assert_nil app.secrets.not_defined end + test "config.secret_key_base over-writes a blank secrets.secret_key_base" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_key_base = "iaminallyoursecretkeybase" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + require "#{app_path}/config/environment" + + assert_equal "iaminallyoursecretkeybase", app.secrets.secret_key_base + end + + test "uses ActiveSupport::LegacyKeyGenerator as app.key_generator when secrets.secret_key_base is blank" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + require "#{app_path}/config/environment" + + assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token + assert_equal nil, app.secrets.secret_key_base + assert_equal app.key_generator.class, ActiveSupport::LegacyKeyGenerator + end + + test "uses ActiveSupport::LegacyKeyGenerator with config.secret_token as app.key_generator when secrets.secret_key_base is blank" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + require "#{app_path}/config/environment" + + assert_equal '', app.config.secret_token + assert_equal nil, app.secrets.secret_key_base + assert_raise ArgumentError, /\AA secret is required/ do + app.key_generator + end + end + test "protect from forgery is the default in a new app" do make_basic_app @@ -375,6 +550,45 @@ module ApplicationTests assert last_response.body =~ /csrf\-param/ end + test "default form builder specified as a string" do + + app_file 'config/initializers/form_builder.rb', <<-RUBY + class CustomFormBuilder < ActionView::Helpers::FormBuilder + def text_field(attribute, *args) + label(attribute) + super(attribute, *args) + end + end + Rails.configuration.action_view.default_form_builder = "CustomFormBuilder" + RUBY + + app_file 'app/models/post.rb', <<-RUBY + class Post + include ActiveModel::Model + attr_accessor :name + end + RUBY + + + app_file 'app/controllers/posts_controller.rb', <<-RUBY + class PostsController < ApplicationController + def index + render inline: "<%= begin; form_for(Post.new) {|f| f.text_field(:name)}; rescue => e; e.to_s; end %>" + end + end + RUBY + + add_to_config <<-RUBY + routes.prepend do + resources :posts + end + RUBY + + require "#{app_path}/config/environment" + + get "/posts" + assert_match(/label/, last_response.body) + end + test "default method for update can be changed" do app_file 'app/models/post.rb', <<-RUBY class Post @@ -429,8 +643,8 @@ module ApplicationTests end test "request forgery token param can be changed" do - make_basic_app do - app.config.action_controller.request_forgery_protection_token = '_xsrf_token_here' + make_basic_app do |application| + application.config.action_controller.request_forgery_protection_token = '_xsrf_token_here' end class ::OmgController < ActionController::Base @@ -440,7 +654,7 @@ module ApplicationTests end get "/" - assert last_response.body =~ /_xsrf_token_here/ + assert_match "_xsrf_token_here", last_response.body end test "sets ActionDispatch.test_app" do @@ -449,8 +663,8 @@ module ApplicationTests end test "sets ActionDispatch::Response.default_charset" do - make_basic_app do |app| - app.config.action_dispatch.default_charset = "utf-16" + make_basic_app do |application| + application.config.action_dispatch.default_charset = "utf-16" end assert_equal "utf-16", ActionDispatch::Response.default_charset @@ -631,8 +845,8 @@ module ApplicationTests end test "config.action_dispatch.show_exceptions is sent in env" do - make_basic_app do |app| - app.config.action_dispatch.show_exceptions = true + make_basic_app do |application| + application.config.action_dispatch.show_exceptions = true end class ::OmgController < ActionController::Base @@ -793,8 +1007,8 @@ module ApplicationTests end test "config.action_dispatch.ignore_accept_header" do - make_basic_app do |app| - app.config.action_dispatch.ignore_accept_header = true + make_basic_app do |application| + application.config.action_dispatch.ignore_accept_header = true end class ::OmgController < ActionController::Base @@ -831,9 +1045,9 @@ module ApplicationTests test "config.session_store with :active_record_store with activerecord-session_store gem" do begin - make_basic_app do |app| + make_basic_app do |application| ActionDispatch::Session::ActiveRecordStore = Class.new(ActionDispatch::Session::CookieStore) - app.config.session_store :active_record_store + application.config.session_store :active_record_store end ensure ActionDispatch::Session.send :remove_const, :ActiveRecordStore @@ -842,16 +1056,46 @@ module ApplicationTests test "config.session_store with :active_record_store without activerecord-session_store gem" do assert_raise RuntimeError, /activerecord-session_store/ do - make_basic_app do |app| - app.config.session_store :active_record_store + make_basic_app do |application| + application.config.session_store :active_record_store + end + end + end + + test "Blank config.log_level is not deprecated for non-production environment" do + with_rails_env "development" do + assert_not_deprecated do + make_basic_app do |application| + application.config.log_level = nil + end + end + end + end + + test "Blank config.log_level is deprecated for the production environment" do + with_rails_env "production" do + assert_deprecated(/log_level/) do + make_basic_app do |application| + application.config.log_level = nil + end + end + end + end + + test "Not blank config.log_level is not deprecated for the production environment" do + with_rails_env "production" do + assert_not_deprecated do + make_basic_app do |application| + application.config.log_level = :info + end end end end test "config.log_level with custom logger" do - make_basic_app do |app| - app.config.logger = Logger.new(STDOUT) - app.config.log_level = :info + make_basic_app do |application| + application.config.logger = Logger.new(STDOUT) + application.config.log_level = :info end assert_equal Logger::INFO, Rails.logger.level end @@ -881,8 +1125,8 @@ module ApplicationTests end test "config.annotations wrapping SourceAnnotationExtractor::Annotation class" do - make_basic_app do |app| - app.config.annotations.register_extensions("coffee") do |tag| + make_basic_app do |application| + application.config.annotations.register_extensions("coffee") do |tag| /#\s*(#{tag}):?\s*(.*)$/ end end @@ -891,95 +1135,102 @@ module ApplicationTests end test "rake_tasks block works at instance level" do - $ran_block = false - app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do + config.ran_block = false + rake_tasks do - $ran_block = true + config.ran_block = true end end RUBY require "#{app_path}/config/environment" + assert_not Rails.configuration.ran_block - assert !$ran_block require 'rake' require 'rake/testtask' require 'rdoc/task' Rails.application.load_tasks - assert $ran_block + assert Rails.configuration.ran_block end test "generators block works at instance level" do - $ran_block = false - app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do + config.ran_block = false + generators do - $ran_block = true + config.ran_block = true end end RUBY require "#{app_path}/config/environment" + assert_not Rails.configuration.ran_block - assert !$ran_block Rails.application.load_generators - assert $ran_block + assert Rails.configuration.ran_block end test "console block works at instance level" do - $ran_block = false - app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do + config.ran_block = false + console do - $ran_block = true + config.ran_block = true end end RUBY require "#{app_path}/config/environment" + assert_not Rails.configuration.ran_block - assert !$ran_block Rails.application.load_console - assert $ran_block + assert Rails.configuration.ran_block end test "runner block works at instance level" do - $ran_block = false - app_file "config/environments/development.rb", <<-RUBY Rails.application.configure do + config.ran_block = false + runner do - $ran_block = true + config.ran_block = true end end RUBY require "#{app_path}/config/environment" + assert_not Rails.configuration.ran_block - assert !$ran_block Rails.application.load_runner - assert $ran_block + assert Rails.configuration.ran_block end test "loading the first existing database configuration available" do app_file 'config/environments/development.rb', <<-RUBY Rails.application.configure do - config.paths.add 'config/database', with: 'config/nonexistant.yml' + config.paths.add 'config/database', with: 'config/nonexistent.yml' config.paths['config/database'] << 'config/database.yml' end RUBY require "#{app_path}/config/environment" - db_config = Rails.application.config.database_configuration + assert_kind_of Hash, Rails.application.config.database_configuration + end - assert db_config.is_a?(Hash) + test 'raises with proper error message if no database configuration found' do + FileUtils.rm("#{app_path}/config/database.yml") + require "#{app_path}/config/environment" + err = assert_raises RuntimeError do + Rails.application.config.database_configuration + end + assert_match 'config/database', err.message end test 'config.action_mailer.show_previews defaults to true in development' do @@ -993,7 +1244,7 @@ module ApplicationTests Rails.env = "production" require "#{app_path}/config/environment" - assert_equal Rails.application.config.action_mailer.show_previews, false + assert_equal false, Rails.application.config.action_mailer.show_previews end test 'config.action_mailer.show_previews can be set in the configuration file' do @@ -1003,7 +1254,7 @@ module ApplicationTests RUBY require "#{app_path}/config/environment" - assert_equal Rails.application.config.action_mailer.show_previews, true + assert_equal true, Rails.application.config.action_mailer.show_previews end test "config_for loads custom configuration from yaml files" do diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index 8e76bf27f3..2d45c9b53f 100644 --- a/railties/test/application/initializers/frameworks_test.rb +++ b/railties/test/application/initializers/frameworks_test.rb @@ -35,8 +35,8 @@ module ApplicationTests require "#{app_path}/config/environment" expanded_path = File.expand_path("app/views", app_path) - assert_equal ActionController::Base.view_paths[0].to_s, expanded_path - assert_equal ActionMailer::Base.view_paths[0].to_s, expanded_path + assert_equal expanded_path, ActionController::Base.view_paths[0].to_s + assert_equal expanded_path, ActionMailer::Base.view_paths[0].to_s end test "allows me to configure default url options for ActionMailer" do @@ -50,7 +50,7 @@ module ApplicationTests assert_equal "test.rails", ActionMailer::Base.default_url_options[:host] end - test "does not include url helpers as action methods" do + test "includes url helpers as action methods" do app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get "/foo", :to => lambda { |env| [200, {}, []] }, :as => :foo @@ -66,8 +66,8 @@ module ApplicationTests require "#{app_path}/config/environment" assert Foo.method_defined?(:foo_path) + assert Foo.method_defined?(:foo_url) assert Foo.method_defined?(:main_app) - assert_equal Set.new(["notify"]), Foo.action_methods end test "allows to not load all helpers for controllers" do diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb index 4f30f30f95..85066210f3 100644 --- a/railties/test/application/loading_test.rb +++ b/railties/test/application/loading_test.rb @@ -33,6 +33,35 @@ class LoadingTest < ActiveSupport::TestCase assert_equal 'omg', p.title end + test "concerns in app are autoloaded" do + app_file "app/controllers/concerns/trackable.rb", <<-CONCERN + module Trackable + end + CONCERN + + app_file "app/mailers/concerns/email_loggable.rb", <<-CONCERN + module EmailLoggable + end + CONCERN + + app_file "app/models/concerns/orderable.rb", <<-CONCERN + module Orderable + end + CONCERN + + app_file "app/validators/concerns/matchable.rb", <<-CONCERN + module Matchable + end + CONCERN + + require "#{rails_root}/config/environment" + + assert_nothing_raised(NameError) { Trackable } + assert_nothing_raised(NameError) { EmailLoggable } + assert_nothing_raised(NameError) { Orderable } + assert_nothing_raised(NameError) { Matchable } + end + test "models without table do not panic on scope definitions when loaded" do app_file "app/models/user.rb", <<-MODEL class User < ActiveRecord::Base diff --git a/railties/test/application/mailer_previews_test.rb b/railties/test/application/mailer_previews_test.rb index 8b91a1171f..9e4f858539 100644 --- a/railties/test/application/mailer_previews_test.rb +++ b/railties/test/application/mailer_previews_test.rb @@ -40,6 +40,17 @@ module ApplicationTests assert_equal 404, last_response.status end + test "/rails/mailers is accessible with globbing route present" do + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + get '*foo', to: 'foo#index' + end + RUBY + app("development") + get "/rails/mailers" + assert_equal 200, last_response.status + end + test "mailer previews are loaded from the default preview_path" do mailer 'notifier', <<-RUBY class Notifier < ActionMailer::Base @@ -417,6 +428,58 @@ module ApplicationTests assert_match '<option selected value="?part=text%2Fplain">View as plain-text email</option>', last_response.body end + test "*_path helpers emit a deprecation" do + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + get 'foo', to: 'foo#index' + end + RUBY + + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def path_in_view + mail to: "to@example.org" + end + + def path_in_mailer + @url = foo_path + mail to: "to@example.org" + end + end + RUBY + + html_template 'notifier/path_in_view', "<%= link_to 'foo', foo_path %>" + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def path_in_view + Notifier.path_in_view + end + + def path_in_mailer + Notifier.path_in_mailer + end + end + RUBY + + app('development') + + assert_deprecated do + get "/rails/mailers/notifier/path_in_view.html" + assert_equal 200, last_response.status + end + + html_template 'notifier/path_in_mailer', "No ERB in here" + + assert_deprecated do + get "/rails/mailers/notifier/path_in_mailer.html" + assert_equal 200, last_response.status + end + end + private def build_app super diff --git a/railties/test/application/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb index b4db840e68..c951dabd6c 100644 --- a/railties/test/application/middleware/cache_test.rb +++ b/railties/test/application/middleware/cache_test.rb @@ -81,8 +81,8 @@ module ApplicationTests add_to_config "config.action_dispatch.rack_cache = true" get "/expires/expires_header" - assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"] - assert_equal "max-age=10, public", last_response.headers["Cache-Control"] + assert_equal "miss, store", last_response.headers["X-Rack-Cache"] + assert_equal "max-age=10, public", last_response.headers["Cache-Control"] body = last_response.body @@ -115,8 +115,8 @@ module ApplicationTests add_to_config "config.action_dispatch.rack_cache = true" get "/expires/expires_etag" - assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"] - assert_equal "public", last_response.headers["Cache-Control"] + assert_equal "miss, store", last_response.headers["X-Rack-Cache"] + assert_equal "public", last_response.headers["Cache-Control"] body = last_response.body etag = last_response.headers["ETag"] @@ -149,8 +149,8 @@ module ApplicationTests add_to_config "config.action_dispatch.rack_cache = true" get "/expires/expires_last_modified" - assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"] - assert_equal "public", last_response.headers["Cache-Control"] + assert_equal "miss, store", last_response.headers["X-Rack-Cache"] + assert_equal "public", last_response.headers["Cache-Control"] body = last_response.body last = last_response.headers["Last-Modified"] diff --git a/railties/test/application/middleware/exceptions_test.rb b/railties/test/application/middleware/exceptions_test.rb index 42096cfec4..a7472b37f1 100644 --- a/railties/test/application/middleware/exceptions_test.rb +++ b/railties/test/application/middleware/exceptions_test.rb @@ -60,6 +60,21 @@ module ApplicationTests assert_equal "YOU FAILED BRO", last_response.body end + test "url generation error when action_dispatch.show_exceptions is set raises an exception" do + controller :foo, <<-RUBY + class FooController < ActionController::Base + def index + raise ActionController::UrlGenerationError + end + end + RUBY + + app.config.action_dispatch.show_exceptions = true + + get '/foo' + assert_equal 500, last_response.status + end + test "unspecified route when action_dispatch.show_exceptions is not set raises an exception" do app.config.action_dispatch.show_exceptions = false diff --git a/railties/test/application/middleware/remote_ip_test.rb b/railties/test/application/middleware/remote_ip_test.rb index 946b82eeb3..97d5b5c698 100644 --- a/railties/test/application/middleware/remote_ip_test.rb +++ b/railties/test/application/middleware/remote_ip_test.rb @@ -1,3 +1,4 @@ +require 'ipaddr' require 'isolation/abstract_unit' require 'active_support/key_generator' @@ -53,12 +54,25 @@ module ApplicationTests end end + test "remote_ip works with HTTP_X_FORWARDED_FOR" do + make_basic_app + assert_equal "4.2.42.42", remote_ip("REMOTE_ADDR" => "1.1.1.1", "HTTP_X_FORWARDED_FOR" => "4.2.42.42") + end + test "the user can set trusted proxies" do make_basic_app do |app| app.config.action_dispatch.trusted_proxies = /^4\.2\.42\.42$/ end - assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "4.2.42.42,1.1.1.1") + assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "1.1.1.1", "HTTP_X_FORWARDED_FOR" => "4.2.42.42") + end + + test "the user can set trusted proxies with an IPAddr argument" do + make_basic_app do |app| + app.config.action_dispatch.trusted_proxies = IPAddr.new('4.2.42.0/24') + end + + assert_equal "1.1.1.1", remote_ip("REMOTE_ADDR" => "1.1.1.1", "HTTP_X_FORWARDED_FOR" => "10.0.0.0,4.2.42.42") end end end diff --git a/railties/test/application/middleware/sendfile_test.rb b/railties/test/application/middleware/sendfile_test.rb index eb791f5687..dc96480d6d 100644 --- a/railties/test/application/middleware/sendfile_test.rb +++ b/railties/test/application/middleware/sendfile_test.rb @@ -61,7 +61,7 @@ module ApplicationTests test "files handled by ActionDispatch::Static are handled by Rack::Sendfile" do make_basic_app do |app| app.config.action_dispatch.x_sendfile_header = 'X-Sendfile' - app.config.serve_static_assets = true + app.config.serve_static_files = true app.paths["public"] = File.join(rails_root, "public") end diff --git a/railties/test/application/middleware/session_test.rb b/railties/test/application/middleware/session_test.rb index 31a64c2f5a..eb7885e5b1 100644 --- a/railties/test/application/middleware/session_test.rb +++ b/railties/test/application/middleware/session_test.rb @@ -203,7 +203,7 @@ module ApplicationTests RUBY add_to_config <<-RUBY - config.secret_token = "3b7cd727ee24e8444053437c36cc66c4" + secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4" RUBY require "#{app_path}/config/environment" @@ -258,7 +258,7 @@ module ApplicationTests RUBY add_to_config <<-RUBY - config.secret_token = "3b7cd727ee24e8444053437c36cc66c4" + secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4" RUBY require "#{app_path}/config/environment" @@ -317,7 +317,7 @@ module ApplicationTests RUBY add_to_config <<-RUBY - config.secret_token = "3b7cd727ee24e8444053437c36cc66c4" + secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4" secrets.secret_key_base = nil RUBY @@ -334,7 +334,7 @@ module ApplicationTests get '/foo/read_signed_cookie' assert_equal '2', last_response.body - verifier = ActiveSupport::MessageVerifier.new(app.config.secret_token) + verifier = ActiveSupport::MessageVerifier.new(app.secrets.secret_token) get '/foo/read_raw_cookie' assert_equal 2, verifier.verify(last_response.body)['foo'] diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb index 1557b90d27..c64fe082f3 100644 --- a/railties/test/application/middleware_test.rb +++ b/railties/test/application/middleware_test.rb @@ -83,7 +83,7 @@ module ApplicationTests add_to_config "config.ssl_options = { host: 'example.com' }" boot! - assert_equal Rails.application.middleware.first.args, [{host: 'example.com'}] + assert_equal [{host: 'example.com'}], Rails.application.middleware.first.args end test "removing Active Record omits its middleware" do @@ -94,20 +94,27 @@ module ApplicationTests assert !middleware.include?("ActiveRecord::Migration::CheckPending") end - test "removes lock if cache classes is set" do + test "includes lock if cache_classes is set but eager_load is not" do add_to_config "config.cache_classes = true" boot! + assert middleware.include?("Rack::Lock") + end + + test "does not include lock if cache_classes is set and so is eager_load" do + add_to_config "config.cache_classes = true" + add_to_config "config.eager_load = true" + boot! assert !middleware.include?("Rack::Lock") end - test "removes lock if allow concurrency is set" do + test "does not include lock if allow_concurrency is set" do add_to_config "config.allow_concurrency = true" boot! assert !middleware.include?("Rack::Lock") end - test "removes static asset server if serve_static_assets is disabled" do - add_to_config "config.serve_static_assets = false" + test "removes static asset server if serve_static_files is disabled" do + add_to_config "config.serve_static_files = false" boot! assert !middleware.include?("ActionDispatch::Static") end @@ -188,7 +195,7 @@ module ApplicationTests end end - etag = "5af83e3196bf99f440f31f2e1a6c9afe".inspect + etag = "W/" + "5af83e3196bf99f440f31f2e1a6c9afe".inspect get "/" assert_equal 200, last_response.status diff --git a/railties/test/application/multiple_applications_test.rb b/railties/test/application/multiple_applications_test.rb index f8d8a673ae..cddc79cc85 100644 --- a/railties/test/application/multiple_applications_test.rb +++ b/railties/test/application/multiple_applications_test.rb @@ -8,6 +8,7 @@ module ApplicationTests build_app(initializers: true) boot_rails require "#{rails_root}/config/environment" + Rails.application.config.some_setting = 'something_or_other' end def teardown @@ -18,7 +19,7 @@ module ApplicationTests clone = Rails.application.clone assert_equal Rails.application.config, clone.config, "The cloned application should get a copy of the config" - assert_equal Rails.application.config.secret_key_base, clone.config.secret_key_base, "The base secret key on the config should be the same" + assert_equal Rails.application.config.some_setting, clone.config.some_setting, "The some_setting on the config should be the same" end def test_inheriting_multiple_times_from_application @@ -36,23 +37,23 @@ module ApplicationTests end def test_initialization_of_application_with_previous_config - application1 = AppTemplate::Application.new(config: Rails.application.config) - application2 = AppTemplate::Application.new + application1 = AppTemplate::Application.create(config: Rails.application.config) + application2 = AppTemplate::Application.create assert_equal Rails.application.config, application1.config, "Creating a new application while setting an initial config should result in the same config" assert_not_equal Rails.application.config, application2.config, "New applications without setting an initial config should not have the same config" end def test_initialization_of_application_with_previous_railties - application1 = AppTemplate::Application.new(railties: Rails.application.railties) - application2 = AppTemplate::Application.new + application1 = AppTemplate::Application.create(railties: Rails.application.railties) + application2 = AppTemplate::Application.create assert_equal Rails.application.railties, application1.railties assert_not_equal Rails.application.railties, application2.railties end def test_initialize_new_application_with_all_previous_initialization_variables - application1 = AppTemplate::Application.new( + application1 = AppTemplate::Application.create( config: Rails.application.config, railties: Rails.application.railties, routes_reloader: Rails.application.routes_reloader, @@ -72,26 +73,26 @@ module ApplicationTests end def test_rake_tasks_defined_on_different_applications_go_to_the_same_class - $run_count = 0 + run_count = 0 application1 = AppTemplate::Application.new application1.rake_tasks do - $run_count += 1 + run_count += 1 end application2 = AppTemplate::Application.new application2.rake_tasks do - $run_count += 1 + run_count += 1 end require "#{app_path}/config/environment" - assert_equal 0, $run_count, "The count should stay at zero without any calls to the rake tasks" + assert_equal 0, run_count, "The count should stay at zero without any calls to the rake tasks" require 'rake' require 'rake/testtask' require 'rdoc/task' Rails.application.load_tasks - assert_equal 2, $run_count, "Calling a rake task should result in two increments to the count" + assert_equal 2, run_count, "Calling a rake task should result in two increments to the count" end def test_multiple_applications_can_be_initialized @@ -100,56 +101,56 @@ module ApplicationTests def test_initializers_run_on_different_applications_go_to_the_same_class application1 = AppTemplate::Application.new - $run_count = 0 + run_count = 0 AppTemplate::Application.initializer :init0 do - $run_count += 1 + run_count += 1 end application1.initializer :init1 do - $run_count += 1 + run_count += 1 end AppTemplate::Application.new.initializer :init2 do - $run_count += 1 + run_count += 1 end - assert_equal 0, $run_count, "Without loading the initializers, the count should be 0" + assert_equal 0, run_count, "Without loading the initializers, the count should be 0" # Set config.eager_load to false so that an eager_load warning doesn't pop up AppTemplate::Application.new { config.eager_load = false }.initialize! - assert_equal 3, $run_count, "There should have been three initializers that incremented the count" + assert_equal 3, run_count, "There should have been three initializers that incremented the count" end def test_consoles_run_on_different_applications_go_to_the_same_class - $run_count = 0 - AppTemplate::Application.console { $run_count += 1 } - AppTemplate::Application.new.console { $run_count += 1 } + run_count = 0 + AppTemplate::Application.console { run_count += 1 } + AppTemplate::Application.new.console { run_count += 1 } - assert_equal 0, $run_count, "Without loading the consoles, the count should be 0" + assert_equal 0, run_count, "Without loading the consoles, the count should be 0" Rails.application.load_console - assert_equal 2, $run_count, "There should have been two consoles that increment the count" + assert_equal 2, run_count, "There should have been two consoles that increment the count" end def test_generators_run_on_different_applications_go_to_the_same_class - $run_count = 0 - AppTemplate::Application.generators { $run_count += 1 } - AppTemplate::Application.new.generators { $run_count += 1 } + run_count = 0 + AppTemplate::Application.generators { run_count += 1 } + AppTemplate::Application.new.generators { run_count += 1 } - assert_equal 0, $run_count, "Without loading the generators, the count should be 0" + assert_equal 0, run_count, "Without loading the generators, the count should be 0" Rails.application.load_generators - assert_equal 2, $run_count, "There should have been two generators that increment the count" + assert_equal 2, run_count, "There should have been two generators that increment the count" end def test_runners_run_on_different_applications_go_to_the_same_class - $run_count = 0 - AppTemplate::Application.runner { $run_count += 1 } - AppTemplate::Application.new.runner { $run_count += 1 } + run_count = 0 + AppTemplate::Application.runner { run_count += 1 } + AppTemplate::Application.new.runner { run_count += 1 } - assert_equal 0, $run_count, "Without loading the runners, the count should be 0" + assert_equal 0, run_count, "Without loading the runners, the count should be 0" Rails.application.load_runner - assert_equal 2, $run_count, "There should have been two runners that increment the count" + assert_equal 2, run_count, "There should have been two runners that increment the count" end def test_isolate_namespace_on_an_application @@ -160,13 +161,14 @@ module ApplicationTests def test_inserting_configuration_into_application app = AppTemplate::Application.new(config: Rails.application.config) - new_config = Rails::Application::Configuration.new("root_of_application") - new_config.secret_key_base = "some_secret_key_dude" - app.config.secret_key_base = "a_different_secret_key" + app.config.some_setting = "a_different_setting" + assert_equal "a_different_setting", app.config.some_setting, "The configuration's some_setting should be set." - assert_equal "a_different_secret_key", app.config.secret_key_base, "The configuration's secret key should be set." + new_config = Rails::Application::Configuration.new("root_of_application") + new_config.some_setting = "some_setting_dude" app.config = new_config - assert_equal "some_secret_key_dude", app.config.secret_key_base, "The configuration's secret key should have changed." + + assert_equal "some_setting_dude", app.config.some_setting, "The configuration's some_setting should have changed." assert_equal "root_of_application", app.config.root, "The root should have changed to the new config's root." assert_equal new_config, app.config, "The application's config should have changed to the new config." end diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb index 15414db00f..c414732f92 100644 --- a/railties/test/application/rake/dbs_test.rb +++ b/railties/test/application/rake/dbs_test.rb @@ -109,6 +109,16 @@ module ApplicationTests db_fixtures_load database_url_db_name end + test 'db:fixtures:load with namespaced fixture' do + require "#{app_path}/config/environment" + Dir.chdir(app_path) do + `rails generate model admin::book title:string; + bundle exec rake db:migrate db:fixtures:load` + require "#{app_path}/app/models/admin/book" + assert_equal 2, Admin::Book.count + end + end + def db_structure_dump_and_load(expected_database) Dir.chdir(app_path) do `rails generate model book title:string; @@ -146,6 +156,31 @@ module ApplicationTests end end + test 'db:schema:load and db:structure:load do not purge the existing database' do + Dir.chdir(app_path) do + `bin/rails runner 'ActiveRecord::Base.connection.create_table(:posts) {|t| t.string :title }'` + + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: 20140423102712) do + create_table(:comments) {} + end + RUBY + + list_tables = lambda { `bin/rails runner 'p ActiveRecord::Base.connection.tables'`.strip } + + assert_equal '["posts"]', list_tables[] + `bin/rake db:schema:load` + assert_equal '["posts", "comments", "schema_migrations"]', list_tables[] + + app_file 'db/structure.sql', <<-SQL + CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255)); + SQL + + `bin/rake db:structure:load` + assert_equal '["posts", "comments", "schema_migrations", "users"]', list_tables[] + end + end + def db_test_load_structure Dir.chdir(app_path) do `rails generate model book title:string; @@ -165,12 +200,32 @@ module ApplicationTests db_test_load_structure end - test 'db:test deprecation' do - require "#{app_path}/config/environment" - Dir.chdir(app_path) do - output = `bundle exec rake db:migrate db:test:prepare 2>&1` - assert_equal "WARNING: db:test:prepare is deprecated. The Rails test helper now maintains " \ - "your test schema automatically, see the release notes for details.\n", output + test 'db:setup loads schema and seeds database' do + begin + @old_rails_env = ENV["RAILS_ENV"] + @old_rack_env = ENV["RACK_ENV"] + ENV.delete "RAILS_ENV" + ENV.delete "RACK_ENV" + + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: "1") do + create_table :users do |t| + t.string :name + end + end + RUBY + + app_file 'db/seeds.rb', <<-RUBY + puts ActiveRecord::Base.connection_config[:database] + RUBY + + Dir.chdir(app_path) do + database_path = `bundle exec rake db:setup` + assert_equal "development.sqlite3", File.basename(database_path.strip) + end + ensure + ENV["RAILS_ENV"] = @old_rails_env + ENV["RACK_ENV"] = @old_rack_env end end end diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb index 8576a2b738..cbada6be97 100644 --- a/railties/test/application/routing_test.rb +++ b/railties/test/application/routing_test.rb @@ -123,6 +123,26 @@ module ApplicationTests assert_equal '/archives', last_response.body end + test "mount named rack app" do + controller :foo, <<-RUBY + class FooController < ApplicationController + def index + render text: my_blog_path + end + end + RUBY + + app_file 'config/routes.rb', <<-RUBY + Rails.application.routes.draw do + mount lambda { |env| [200, {}, [env["PATH_INFO"]]] }, at: "/blog", as: "my_blog" + get '/foo' => 'foo#index' + end + RUBY + + get '/foo' + assert_equal '/blog', last_response.body + end + test "multiple controllers" do controller :foo, <<-RUBY class FooController < ApplicationController diff --git a/railties/test/application/test_runner_test.rb b/railties/test/application/test_runner_test.rb index 118f22995e..032b11a95f 100644 --- a/railties/test/application/test_runner_test.rb +++ b/railties/test/application/test_runner_test.rb @@ -109,6 +109,17 @@ module ApplicationTests end end + def test_run_jobs + create_test_file :jobs, 'foo_job' + create_test_file :jobs, 'bar_job' + create_test_file :models, 'foo' + run_test_jobs_command.tap do |output| + assert_match "FooJobTest", output + assert_match "BarJobTest", output + assert_match "2 runs, 2 assertions, 0 failures", output + end + end + def test_run_functionals create_test_file :mailers, 'foo_mailer' create_test_file :controllers, 'bar_controller' @@ -132,11 +143,11 @@ module ApplicationTests end def test_run_all_suites - suites = [:models, :helpers, :unit, :controllers, :mailers, :functional, :integration] + suites = [:models, :helpers, :unit, :controllers, :mailers, :functional, :integration, :jobs] suites.each { |suite| create_test_file suite, "foo_#{suite}" } run_test_command('') .tap do |output| suites.each { |suite| assert_match "Foo#{suite.to_s.camelize}Test", output } - assert_match "7 runs, 7 assertions, 0 failures", output + assert_match "8 runs, 8 assertions, 0 failures", output end end @@ -245,7 +256,7 @@ module ApplicationTests def run_test_command(arguments = 'test/unit/test_test.rb') run_task ['test', arguments] end - %w{ mailers models helpers units controllers functionals integration }.each do |type| + %w{ mailers models helpers units controllers functionals integration jobs }.each do |type| define_method("run_test_#{type}_command") do run_task ["test:#{type}"] end diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb index a223180169..c7132837b1 100644 --- a/railties/test/application/test_test.rb +++ b/railties/test/application/test_test.rb @@ -67,7 +67,7 @@ module ApplicationTests assert_match %r{/app/test/unit/failing_test\.rb}, output end - test "migrations" do + test "ruby schema migrations" do output = script('generate model user name:string') version = output.match(/(\d+)_create_users\.rb/)[1] @@ -104,6 +104,187 @@ module ApplicationTests assert !result.include?("create_table(:users)") end + test "sql structure migrations" do + output = script('generate model user name:string') + version = output.match(/(\d+)_create_users\.rb/)[1] + + app_file 'test/models/user_test.rb', <<-RUBY + require 'test_helper' + + class UserTest < ActiveSupport::TestCase + test "user" do + User.create! name: "Jon" + end + end + RUBY + + app_file 'db/structure.sql', '' + app_file 'config/initializers/enable_sql_schema_format.rb', <<-RUBY + Rails.application.config.active_record.schema_format = :sql + RUBY + + assert_unsuccessful_run "models/user_test.rb", "Migrations are pending" + + app_file 'db/structure.sql', <<-SQL + CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL); + CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version"); + CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255)); + INSERT INTO schema_migrations (version) VALUES ('#{version}'); + SQL + + app_file 'config/initializers/disable_maintain_test_schema.rb', <<-RUBY + Rails.application.config.active_record.maintain_test_schema = false + RUBY + + assert_unsuccessful_run "models/user_test.rb", "Could not find table 'users'" + + File.delete "#{app_path}/config/initializers/disable_maintain_test_schema.rb" + + assert_successful_test_run('models/user_test.rb') + end + + test "sql structure migrations when adding column to existing table" do + output_1 = script('generate model user name:string') + version_1 = output_1.match(/(\d+)_create_users\.rb/)[1] + + app_file 'test/models/user_test.rb', <<-RUBY + require 'test_helper' + class UserTest < ActiveSupport::TestCase + test "user" do + User.create! name: "Jon" + end + end + RUBY + + app_file 'config/initializers/enable_sql_schema_format.rb', <<-RUBY + Rails.application.config.active_record.schema_format = :sql + RUBY + + app_file 'db/structure.sql', <<-SQL + CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL); + CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version"); + CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255)); + INSERT INTO schema_migrations (version) VALUES ('#{version_1}'); + SQL + + assert_successful_test_run('models/user_test.rb') + + output_2 = script('generate migration add_email_to_users') + version_2 = output_2.match(/(\d+)_add_email_to_users\.rb/)[1] + + app_file 'test/models/user_test.rb', <<-RUBY + require 'test_helper' + + class UserTest < ActiveSupport::TestCase + test "user" do + User.create! name: "Jon", email: "jon@doe.com" + end + end + RUBY + + app_file 'db/structure.sql', <<-SQL + CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL); + CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version"); + CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255), "email" varchar(255)); + INSERT INTO schema_migrations (version) VALUES ('#{version_1}'); + INSERT INTO schema_migrations (version) VALUES ('#{version_2}'); + SQL + + assert_successful_test_run('models/user_test.rb') + end + + # TODO: would be nice if we could detect the schema change automatically. + # For now, the user has to synchronize the schema manually. + # This test-case serves as a reminder for this use-case. + test "manually synchronize test schema after rollback" do + output = script('generate model user name:string') + version = output.match(/(\d+)_create_users\.rb/)[1] + + app_file 'test/models/user_test.rb', <<-RUBY + require 'test_helper' + + class UserTest < ActiveSupport::TestCase + test "user" do + assert_equal ["id", "name"], User.columns_hash.keys + end + end + RUBY + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: #{version}) do + create_table :users do |t| + t.string :name + end + end + RUBY + + assert_successful_test_run "models/user_test.rb" + + # Simulate `db:rollback` + edit of the migration file + `db:migrate` + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: #{version}) do + create_table :users do |t| + t.string :name + t.integer :age + end + end + RUBY + + assert_successful_test_run "models/user_test.rb" + + Dir.chdir(app_path) { `bin/rake db:test:prepare` } + + assert_unsuccessful_run "models/user_test.rb", <<-ASSERTION +Expected: ["id", "name"] + Actual: ["id", "name", "age"] + ASSERTION + end + + test "hooks for plugins" do + output = script('generate model user name:string') + version = output.match(/(\d+)_create_users\.rb/)[1] + + app_file 'lib/tasks/hooks.rake', <<-RUBY + task :before_hook do + has_user_table = ActiveRecord::Base.connection.table_exists?('users') + puts "before: " + has_user_table.to_s + end + + task :after_hook do + has_user_table = ActiveRecord::Base.connection.table_exists?('users') + puts "after: " + has_user_table.to_s + end + + Rake::Task["db:test:prepare"].enhance [:before_hook] do + Rake::Task[:after_hook].invoke + end + RUBY + app_file 'test/models/user_test.rb', <<-RUBY + require 'test_helper' + class UserTest < ActiveSupport::TestCase + test "user" do + User.create! name: "Jon" + end + end + RUBY + + # Simulate `db:migrate` + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: #{version}) do + create_table :users do |t| + t.string :name + end + end + RUBY + + output = assert_successful_test_run "models/user_test.rb" + assert_includes output, "before: false\nafter: true" + + # running tests again won't trigger a schema update + output = assert_successful_test_run "models/user_test.rb" + assert_not_includes output, "before:" + assert_not_includes output, "after:" + end + private def assert_unsuccessful_run(name, message) result = run_test_file(name) @@ -119,7 +300,7 @@ module ApplicationTests end def run_test_file(name, options = {}) - ruby '-Itest', "#{app_path}/test/#{name}", options + ruby '-Itest', "#{app_path}/test/#{name}", options.deep_merge(env: {"RAILS_ENV" => "test"}) end def ruby(*args) diff --git a/railties/test/application/url_generation_test.rb b/railties/test/application/url_generation_test.rb index efbc853d7b..ef16ab56ed 100644 --- a/railties/test/application/url_generation_test.rb +++ b/railties/test/application/url_generation_test.rb @@ -15,7 +15,7 @@ module ApplicationTests require "action_view/railtie" class MyApp < Rails::Application - config.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4" + secrets.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4" config.session_store :cookie_store, key: "_myapp_session" config.active_support.deprecation = :log config.eager_load = false diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb index ede08e7b86..a3cd1eb0ed 100644 --- a/railties/test/commands/dbconsole_test.rb +++ b/railties/test/commands/dbconsole_test.rb @@ -28,7 +28,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase } } app_db_config(config_sample) do - assert_equal Rails::DBConsole.new.config, config_sample["test"] + assert_equal config_sample["test"], Rails::DBConsole.new.config end end @@ -79,22 +79,23 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase end def test_env - assert_equal Rails::DBConsole.new.environment, "test" + assert_equal "test", Rails::DBConsole.new.environment ENV['RAILS_ENV'] = nil ENV['RACK_ENV'] = nil Rails.stub(:respond_to?, false) do - assert_equal Rails::DBConsole.new.environment, "development" + assert_equal "development", Rails::DBConsole.new.environment ENV['RACK_ENV'] = "rack_env" - assert_equal Rails::DBConsole.new.environment, "rack_env" + assert_equal "rack_env", Rails::DBConsole.new.environment ENV['RAILS_ENV'] = "rails_env" - assert_equal Rails::DBConsole.new.environment, "rails_env" + assert_equal "rails_env", Rails::DBConsole.new.environment end ensure ENV['RAILS_ENV'] = "test" + ENV['RACK_ENV'] = nil end def test_rails_env_is_development_when_argument_is_dev diff --git a/railties/test/configuration/middleware_stack_proxy_test.rb b/railties/test/configuration/middleware_stack_proxy_test.rb index 6f3e45f320..d5072614cf 100644 --- a/railties/test/configuration/middleware_stack_proxy_test.rb +++ b/railties/test/configuration/middleware_stack_proxy_test.rb @@ -1,3 +1,4 @@ +require 'active_support' require 'active_support/testing/autorun' require 'rails/configuration' require 'active_support/test_case' diff --git a/railties/test/engine_test.rb b/railties/test/engine_test.rb index 7970913d21..f46fb748f5 100644 --- a/railties/test/engine_test.rb +++ b/railties/test/engine_test.rb @@ -11,4 +11,15 @@ class EngineTest < ActiveSupport::TestCase assert !engine.routes? end + + def test_application_can_be_subclassed + klass = Class.new(Rails::Application) do + attr_reader :hello + def initialize + @hello = "world" + super + end + end + assert_equal "world", klass.instance.hello + end end diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb index a4337926d1..c4b6441397 100644 --- a/railties/test/generators/actions_test.rb +++ b/railties/test/generators/actions_test.rb @@ -79,6 +79,16 @@ class ActionsTest < Rails::Generators::TestCase assert_file 'Gemfile', /gem 'rspec', github: 'dchelimsky\/rspec', tag: '1\.2\.9\.rc1'/ end + def test_gem_with_non_string_options + run_generator + + action :gem, 'rspec', require: false + action :gem, 'rspec-rails', group: [:development, :test] + + assert_file 'Gemfile', /^gem 'rspec', require: false$/ + assert_file 'Gemfile', /^gem 'rspec-rails', group: \[:development, :test\]$/ + end + def test_gem_falls_back_to_inspect_if_string_contains_single_quote run_generator @@ -119,7 +129,7 @@ class ActionsTest < Rails::Generators::TestCase run_generator action :environment do - '# This wont be added' + _ = '# This wont be added'# assignment to silence parse-time warning "unused literal ignored" '# This will be added' end diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index aff484f3eb..e30c9a7b2f 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -160,6 +160,38 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file("#{app_root}/config/initializers/cookies_serializer.rb", /Rails\.application\.config\.action_dispatch\.cookies_serializer = :json/) end + def test_rails_update_does_not_create_callback_terminator_initializer + app_root = File.join(destination_root, 'myapp') + run_generator [app_root] + + FileUtils.rm("#{app_root}/config/initializers/callback_terminator.rb") + + Rails.application.config.root = app_root + Rails.application.class.stubs(:name).returns("Myapp") + Rails.application.stubs(:is_a?).returns(Rails::Application) + + generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, destination_root: app_root, shell: @shell + generator.send(:app_const) + quietly { generator.send(:update_config_files) } + assert_no_file "#{app_root}/config/initializers/callback_terminator.rb" + end + + def test_rails_update_does_not_remove_callback_terminator_initializer_if_already_present + app_root = File.join(destination_root, 'myapp') + run_generator [app_root] + + FileUtils.touch("#{app_root}/config/initializers/callback_terminator.rb") + + Rails.application.config.root = app_root + Rails.application.class.stubs(:name).returns("Myapp") + Rails.application.stubs(:is_a?).returns(Rails::Application) + + generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, destination_root: app_root, shell: @shell + generator.send(:app_const) + quietly { generator.send(:update_config_files) } + assert_file "#{app_root}/config/initializers/callback_terminator.rb" + end + def test_rails_update_set_the_cookie_serializer_to_marchal_if_it_is_not_already_configured app_root = File.join(destination_root, 'myapp') run_generator [app_root] @@ -194,20 +226,20 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_config_database_is_added_by_default run_generator assert_file "config/database.yml", /sqlite3/ - unless defined?(JRUBY_VERSION) - assert_gem "sqlite3" - else + if defined?(JRUBY_VERSION) assert_gem "activerecord-jdbcsqlite3-adapter" + else + assert_gem "sqlite3" end end def test_config_another_database run_generator([destination_root, "-d", "mysql"]) assert_file "config/database.yml", /mysql/ - unless defined?(JRUBY_VERSION) - assert_gem "mysql2" - else + if defined?(JRUBY_VERSION) assert_gem "activerecord-jdbcmysql-adapter" + else + assert_gem "mysql2" end end @@ -219,10 +251,10 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_config_postgresql_database run_generator([destination_root, "-d", "postgresql"]) assert_file "config/database.yml", /postgresql/ - unless defined?(JRUBY_VERSION) - assert_gem "pg" - else + if defined?(JRUBY_VERSION) assert_gem "activerecord-jdbcpostgresql-adapter" + else + assert_gem "pg" end end @@ -251,14 +283,28 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_gem "activerecord-jdbc-adapter" end - def test_config_jdbc_database_when_no_option_given - if defined?(JRUBY_VERSION) - run_generator([destination_root]) + if defined?(JRUBY_VERSION) + def test_config_jdbc_database_when_no_option_given + run_generator assert_file "config/database.yml", /sqlite3/ assert_gem "activerecord-jdbcsqlite3-adapter" end end + def test_generator_without_skips + run_generator + assert_file "config/application.rb", /\s+require\s+["']rails\/all["']/ + assert_file "config/environments/development.rb" do |content| + assert_match(/config\.action_mailer\.raise_delivery_errors = false/, content) + end + assert_file "config/environments/test.rb" do |content| + assert_match(/config\.action_mailer\.delivery_method = :test/, content) + end + assert_file "config/environments/production.rb" do |content| + assert_match(/# config\.action_mailer\.raise_delivery_errors = false/, content) + end + end + def test_generator_if_skip_active_record_is_given run_generator [destination_root, "--skip-active-record"] assert_no_file "config/database.yml" @@ -268,9 +314,18 @@ class AppGeneratorTest < Rails::Generators::TestCase end end - def test_generator_if_skip_action_view_is_given - run_generator [destination_root, "--skip-action-view"] - assert_file "config/application.rb", /#\s+require\s+["']action_view\/railtie["']/ + def test_generator_if_skip_action_mailer_is_given + run_generator [destination_root, "--skip-action-mailer"] + assert_file "config/application.rb", /#\s+require\s+["']action_mailer\/railtie["']/ + assert_file "config/environments/development.rb" do |content| + assert_no_match(/config\.action_mailer/, content) + end + assert_file "config/environments/test.rb" do |content| + assert_no_match(/config\.action_mailer/, content) + end + assert_file "config/environments/production.rb" do |content| + assert_no_match(/config\.action_mailer/, content) + end end def test_generator_if_skip_sprockets_is_given @@ -295,11 +350,11 @@ class AppGeneratorTest < Rails::Generators::TestCase end def test_inclusion_of_javascript_runtime - run_generator([destination_root]) + run_generator if defined?(JRUBY_VERSION) assert_gem "therubyrhino" else - assert_file "Gemfile", /# gem\s+["']therubyracer["']+, \s+platforms: :ruby$/ + assert_file "Gemfile", /# gem 'therubyracer', platforms: :ruby/ end end @@ -340,20 +395,20 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_inclusion_of_jbuilder run_generator - assert_file "Gemfile", /gem 'jbuilder'/ + assert_gem 'jbuilder' end def test_inclusion_of_a_debugger run_generator - if defined?(JRUBY_VERSION) + if defined?(JRUBY_VERSION) || RUBY_ENGINE == "rbx" assert_file "Gemfile" do |content| assert_no_match(/byebug/, content) assert_no_match(/debugger/, content) end elsif RUBY_VERSION < '2.0.0' - assert_file "Gemfile", /# gem 'debugger'/ + assert_gem 'debugger' else - assert_file "Gemfile", /# gem 'byebug'/ + assert_gem 'byebug' end end @@ -395,10 +450,11 @@ class AppGeneratorTest < Rails::Generators::TestCase run_generator [destination_root, "--skip-test-unit", "--skip-active-record"] assert_file "config/application.rb", /#\s+require\s+["']rails\/test_unit\/railtie["']/ assert_file "config/application.rb", /#\s+require\s+["']active_record\/railtie["']/ + assert_file "config/application.rb", /\s+require\s+["']active_job\/railtie["']/ end def test_new_hash_style - run_generator [destination_root] + run_generator assert_file "config/initializers/session_store.rb" do |file| assert_match(/config.session_store :cookie_store, key: '_.+_session'/, file) end @@ -419,9 +475,32 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "foo bar/config/initializers/session_store.rb", /key: '_foo_bar/ end + def test_web_console + run_generator + assert_gem 'web-console' + end + + def test_web_console_with_dev_option + run_generator [destination_root, "--dev"] + + assert_file "Gemfile" do |content| + assert_match(/gem 'web-console',\s+github: "rails\/web-console"/, content) + assert_no_match(/gem 'web-console', '~> 2.0'/, content) + end + end + + def test_web_console_with_edge_option + run_generator [destination_root, "--edge"] + + assert_file "Gemfile" do |content| + assert_match(/gem 'web-console',\s+github: "rails\/web-console"/, content) + assert_no_match(/gem 'web-console', '~> 2.0'/, content) + end + end + def test_spring run_generator - assert_file "Gemfile", /gem 'spring', \s+group: :development/ + assert_gem 'spring' end def test_spring_binstubs @@ -449,12 +528,11 @@ class AppGeneratorTest < Rails::Generators::TestCase end end - def test_generator_if_skip_gems_is_given - run_generator [destination_root, "--skip-gems", "turbolinks", "coffee-rails"] + def test_generator_if_skip_turbolinks_is_given + run_generator [destination_root, "--skip-turbolinks"] assert_file "Gemfile" do |content| assert_no_match(/turbolinks/, content) - assert_no_match(/coffee-rails/, content) end assert_file "app/views/layouts/application.html.erb" do |content| assert_no_match(/data-turbolinks-track/, content) @@ -490,7 +568,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_psych_gem run_generator - gem_regex = /gem 'psych',\s+'~> 2.0', \s+platforms: :rbx/ + gem_regex = /gem 'psych',\s+'~> 2.0',\s+platforms: :rbx/ assert_file "Gemfile" do |content| if defined?(Rubinius) @@ -501,6 +579,21 @@ class AppGeneratorTest < Rails::Generators::TestCase end end + def test_after_bundle_callback + path = 'http://example.org/rails_template' + template = %{ after_bundle { run 'echo ran after_bundle' } } + template.instance_eval "def read; self; end" # Make the string respond to read + + generator([destination_root], template: path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) + + bundler_first = sequence('bundle, binstubs, after_bundle') + generator.expects(:bundle_command).with('install').once.in_sequence(bundler_first) + generator.expects(:bundle_command).with('exec spring binstub --all').in_sequence(bundler_first) + generator.expects(:run).with('echo ran after_bundle').in_sequence(bundler_first) + + quietly { generator.invoke_all } + end + protected def action(*args, &block) @@ -508,6 +601,6 @@ class AppGeneratorTest < Rails::Generators::TestCase end def assert_gem(gem) - assert_file "Gemfile", /^gem\s+["']#{gem}["']$/ + assert_file "Gemfile", /^\s*gem\s+["']#{gem}["']$*/ end end diff --git a/railties/test/generators/argv_scrubber_test.rb b/railties/test/generators/argv_scrubber_test.rb index 31c2d846e2..31e07bc8da 100644 --- a/railties/test/generators/argv_scrubber_test.rb +++ b/railties/test/generators/argv_scrubber_test.rb @@ -1,5 +1,5 @@ -require 'active_support/testing/autorun' require 'active_support/test_case' +require 'active_support/testing/autorun' require 'rails/generators/rails/app/app_generator' require 'tempfile' diff --git a/railties/test/generators/controller_generator_test.rb b/railties/test/generators/controller_generator_test.rb index 28b527cb0e..a7d56dd352 100644 --- a/railties/test/generators/controller_generator_test.rb +++ b/railties/test/generators/controller_generator_test.rb @@ -28,13 +28,11 @@ class ControllerGeneratorTest < Rails::Generators::TestCase def test_invokes_helper run_generator assert_file "app/helpers/account_helper.rb" - assert_file "test/helpers/account_helper_test.rb" end def test_does_not_invoke_helper_if_required run_generator ["account", "--skip-helper"] assert_no_file "app/helpers/account_helper.rb" - assert_no_file "test/helpers/account_helper_test.rb" end def test_invokes_assets diff --git a/railties/test/generators/generated_attribute_test.rb b/railties/test/generators/generated_attribute_test.rb index c48bc20899..ee7c009305 100644 --- a/railties/test/generators/generated_attribute_test.rb +++ b/railties/test/generators/generated_attribute_test.rb @@ -141,4 +141,12 @@ class GeneratedAttributeTest < Rails::Generators::TestCase assert_equal "post_id", create_generated_attribute('references', 'post').column_name assert_equal "post_id", create_generated_attribute('belongs_to', 'post').column_name end + + def test_parse_required_attribute_with_index + att = Rails::Generators::GeneratedAttribute.parse("supplier:references{required}:index") + assert_equal "supplier", att.name + assert_equal :references, att.type + assert att.has_index? + assert att.required? + end end diff --git a/railties/test/generators/generator_test.rb b/railties/test/generators/generator_test.rb index b136239795..7871399dd7 100644 --- a/railties/test/generators/generator_test.rb +++ b/railties/test/generators/generator_test.rb @@ -1,5 +1,5 @@ -require 'active_support/testing/autorun' require 'active_support/test_case' +require 'active_support/testing/autorun' require 'rails/generators/app_base' module Rails diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb index de1e56e7b3..6cc91f166b 100644 --- a/railties/test/generators/generators_test_helper.rb +++ b/railties/test/generators/generators_test_helper.rb @@ -7,7 +7,7 @@ module Rails class << self remove_possible_method :root def root - @root ||= File.expand_path(File.join(File.dirname(__FILE__), '..', 'fixtures')) + @root ||= Pathname.new(File.expand_path('../../fixtures', __FILE__)) end end end diff --git a/railties/test/generators/helper_generator_test.rb b/railties/test/generators/helper_generator_test.rb index 81d4fcb129..add04f21a4 100644 --- a/railties/test/generators/helper_generator_test.rb +++ b/railties/test/generators/helper_generator_test.rb @@ -13,26 +13,11 @@ class HelperGeneratorTest < Rails::Generators::TestCase assert_file "app/helpers/admin_helper.rb", /module AdminHelper/ end - def test_invokes_default_test_framework - run_generator - assert_file "test/helpers/admin_helper_test.rb", /class AdminHelperTest < ActionView::TestCase/ - end - - def test_logs_if_the_test_framework_cannot_be_found - content = run_generator ["admin", "--test-framework=rspec"] - assert_match(/rspec \[not found\]/, content) - end - def test_check_class_collision content = capture(:stderr){ run_generator ["object"] } assert_match(/The name 'ObjectHelper' is either already used in your application or reserved/, content) end - def test_check_class_collision_on_tests - content = capture(:stderr){ run_generator ["another_object"] } - assert_match(/The name 'AnotherObjectHelperTest' is either already used in your application or reserved/, content) - end - def test_namespaced_and_not_namespaced_helpers run_generator ["products"] diff --git a/railties/test/generators/job_generator_test.rb b/railties/test/generators/job_generator_test.rb new file mode 100644 index 0000000000..a9e0cea94f --- /dev/null +++ b/railties/test/generators/job_generator_test.rb @@ -0,0 +1,29 @@ +require 'generators/generators_test_helper' +require 'rails/generators/job/job_generator' + +class JobGeneratorTest < Rails::Generators::TestCase + include GeneratorsTestHelper + + def test_job_skeleton_is_created + run_generator ["refresh_counters"] + assert_file "app/jobs/refresh_counters_job.rb" do |job| + assert_match(/class RefreshCountersJob < ActiveJob::Base/, job) + end + end + + def test_job_queue_param + run_generator ["refresh_counters", "--queue", "important"] + assert_file "app/jobs/refresh_counters_job.rb" do |job| + assert_match(/class RefreshCountersJob < ActiveJob::Base/, job) + assert_match(/queue_as :important/, job) + end + end + + def test_job_namespace + run_generator ["admin/refresh_counters", "--queue", "admin"] + assert_file "app/jobs/admin/refresh_counters_job.rb" do |job| + assert_match(/class Admin::RefreshCountersJob < ActiveJob::Base/, job) + assert_match(/queue_as :admin/, job) + end + end +end diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb index 25649881eb..3d1cf87dae 100644 --- a/railties/test/generators/mailer_generator_test.rb +++ b/railties/test/generators/mailer_generator_test.rb @@ -8,8 +8,18 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_mailer_skeleton_is_created run_generator assert_file "app/mailers/notifier.rb" do |mailer| - assert_match(/class Notifier < ActionMailer::Base/, mailer) + assert_match(/class Notifier < ApplicationMailer/, mailer) + assert_no_match(/default from: "from@example.com"/, mailer) + assert_no_match(/layout :mailer_notifier/, mailer) + end + end + + def test_application_mailer_skeleton_is_created + run_generator + assert_file "app/mailers/application_mailer.rb" do |mailer| + assert_match(/class ApplicationMailer < ActionMailer::Base/, mailer) assert_match(/default from: "from@example.com"/, mailer) + assert_match(/layout 'mailer'/, mailer) end end @@ -77,6 +87,10 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_match(%r(\sapp/views/notifier/bar\.text\.erb), view) assert_match(/<%= @greeting %>/, view) end + + assert_file "app/views/layouts/mailer.text.erb" do |view| + assert_match(/<%= yield %>/, view) + end end def test_invokes_default_html_template_engine @@ -90,11 +104,17 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_match(%r(\sapp/views/notifier/bar\.html\.erb), view) assert_match(/<%= @greeting %>/, view) end + + assert_file "app/views/layouts/mailer.html.erb" do |view| + assert_match(%r{<html>\n <body>\n <%= yield %>\n </body>\n</html>}, view) + end end def test_invokes_default_template_engine_even_with_no_action run_generator ["notifier"] assert_file "app/views/notifier" + assert_file "app/views/layouts/mailer.text.erb" + assert_file "app/views/layouts/mailer.html.erb" end def test_logs_if_the_template_engine_cannot_be_found @@ -105,7 +125,7 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_mailer_with_namedspaced_mailer run_generator ["Farm::Animal", "moos"] assert_file "app/mailers/farm/animal.rb" do |mailer| - assert_match(/class Farm::Animal < ActionMailer::Base/, mailer) + assert_match(/class Farm::Animal < ApplicationMailer/, mailer) assert_match(/en\.farm\.animal\.moos\.subject/, mailer) end assert_file "test/mailers/previews/farm/animal_preview.rb" do |preview| @@ -132,4 +152,19 @@ class MailerGeneratorTest < Rails::Generators::TestCase end end end + + def test_mailer_on_revoke + run_generator + run_generator ["notifier"], behavior: :revoke + + assert_no_file "app/mailers/notifier.rb" + assert_no_file "app/views/notifier/foo.text.erb" + assert_no_file "app/views/notifier/bar.text.erb" + assert_no_file "app/views/notifier/foo.html.erb" + assert_no_file "app/views/notifier/bar.html.erb" + + assert_file "app/mailers/application_mailer.rb" + assert_file "app/views/layouts/mailer.text.erb" + assert_file "app/views/layouts/mailer.html.erb" + end end diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb index 6fac643ed0..413d457d54 100644 --- a/railties/test/generators/migration_generator_test.rb +++ b/railties/test/generators/migration_generator_test.rb @@ -85,6 +85,19 @@ class MigrationGeneratorTest < Rails::Generators::TestCase end end + def test_remove_migration_with_references_removes_foreign_keys + migration = "remove_references_from_books" + run_generator [migration, "author:belongs_to", "distributor:references{polymorphic}"] + + assert_migration "db/migrate/#{migration}.rb" do |content| + assert_method :change, content do |change| + assert_match(/remove_reference :books, :author,.*\sforeign_key: true/, change) + assert_match(/remove_reference :books, :distributor/, change) # sanity check + assert_no_match(/remove_reference :books, :distributor,.*\sforeign_key: true/, change) + end + 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"] @@ -159,6 +172,31 @@ class MigrationGeneratorTest < Rails::Generators::TestCase end end + def test_add_migration_with_required_references + migration = "add_references_to_books" + run_generator [migration, "author:belongs_to{required}", "distributor:references{polymorphic,required}"] + + assert_migration "db/migrate/#{migration}.rb" do |content| + assert_method :change, content do |change| + assert_match(/add_reference :books, :author, index: true, null: false/, change) + assert_match(/add_reference :books, :distributor, polymorphic: true, index: true, null: false/, change) + end + end + end + + def test_add_migration_with_references_adds_foreign_keys + migration = "add_references_to_books" + run_generator [migration, "author:belongs_to", "distributor:references{polymorphic}"] + + assert_migration "db/migrate/#{migration}.rb" do |content| + assert_method :change, content do |change| + assert_match(/add_reference :books, :author,.*\sforeign_key: true/, change) + assert_match(/add_reference :books, :distributor/, change) # sanity check + assert_no_match(/add_reference :books, :distributor,.*\sforeign_key: true/, change) + end + end + end + def test_create_join_table_migration migration = "add_media_join_table" run_generator [migration, "artist_id", "musics:uniq"] @@ -193,7 +231,7 @@ class MigrationGeneratorTest < Rails::Generators::TestCase end end end - + def test_properly_identifies_usage_file assert generator_class.send(:usage_path) end diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb index b67cf02d7b..afee0a655d 100644 --- a/railties/test/generators/model_generator_test.rb +++ b/railties/test/generators/model_generator_test.rb @@ -1,5 +1,6 @@ require 'generators/generators_test_helper' require 'rails/generators/rails/model/model_generator' +require 'active_support/core_ext/string/strip' class ModelGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -222,7 +223,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase def test_migration_with_timestamps run_generator - assert_migration "db/migrate/create_accounts.rb", /t.timestamps/ + assert_migration "db/migrate/create_accounts.rb", /t.timestamps null: false/ end def test_migration_timestamps_are_skipped @@ -286,18 +287,18 @@ class ModelGeneratorTest < Rails::Generators::TestCase def test_fixtures_use_the_references_ids run_generator ["LineItem", "product:references", "cart:belongs_to"] - assert_file "test/fixtures/line_items.yml", /product_id: \n cart_id: / + assert_file "test/fixtures/line_items.yml", /product: \n cart: / assert_generated_fixture("test/fixtures/line_items.yml", - {"one"=>{"product_id"=>nil, "cart_id"=>nil}, "two"=>{"product_id"=>nil, "cart_id"=>nil}}) + {"one"=>{"product"=>nil, "cart"=>nil}, "two"=>{"product"=>nil, "cart"=>nil}}) end def test_fixtures_use_the_references_ids_and_type run_generator ["LineItem", "product:references{polymorphic}", "cart:belongs_to"] - assert_file "test/fixtures/line_items.yml", /product_id: \n product_type: Product\n cart_id: / + assert_file "test/fixtures/line_items.yml", /product: \n product_type: Product\n cart: / assert_generated_fixture("test/fixtures/line_items.yml", - {"one"=>{"product_id"=>nil, "product_type"=>"Product", "cart_id"=>nil}, - "two"=>{"product_id"=>nil, "product_type"=>"Product", "cart_id"=>nil}}) + {"one"=>{"product"=>nil, "product_type"=>"Product", "cart"=>nil}, + "two"=>{"product"=>nil, "product_type"=>"Product", "cart"=>nil}}) end def test_fixtures_respect_reserved_yml_keywords @@ -363,6 +364,80 @@ class ModelGeneratorTest < Rails::Generators::TestCase end end + def test_required_belongs_to_adds_required_association + run_generator ["account", "supplier:references{required}"] + + expected_file = <<-FILE.strip_heredoc + class Account < ActiveRecord::Base + belongs_to :supplier, required: true + end + FILE + assert_file "app/models/account.rb", expected_file + end + + def test_required_polymorphic_belongs_to_generages_correct_model + run_generator ["account", "supplier:references{required,polymorphic}"] + + expected_file = <<-FILE.strip_heredoc + class Account < ActiveRecord::Base + belongs_to :supplier, polymorphic: true, required: true + end + FILE + assert_file "app/models/account.rb", expected_file + end + + def test_required_and_polymorphic_are_order_independent + run_generator ["account", "supplier:references{polymorphic.required}"] + + expected_file = <<-FILE.strip_heredoc + class Account < ActiveRecord::Base + belongs_to :supplier, polymorphic: true, required: true + end + FILE + assert_file "app/models/account.rb", expected_file + end + + def test_required_adds_null_false_to_column + run_generator ["account", "supplier:references{required}"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_match(/t\.references :supplier,.*\snull: false/, up) + end + end + end + + def test_foreign_key_is_not_added_for_non_references + run_generator ["account", "supplier:string"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_no_match(/foreign_key/, up) + end + end + end + + def test_foreign_key_is_added_for_references + run_generator ["account", "supplier:belongs_to", "user:references"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_match(/t\.belongs_to :supplier,.*\sforeign_key: true/, up) + assert_match(/t\.references :user,.*\sforeign_key: true/, up) + end + end + end + + def test_foreign_key_is_skipped_for_polymorphic_references + run_generator ["account", "supplier:belongs_to{polymorphic}"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_no_match(/foreign_key/, up) + end + end + end + private def assert_generated_fixture(path, parsed_contents) fixture_file = File.new File.expand_path(path, destination_root) diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb index d677c21f15..6075805152 100644 --- a/railties/test/generators/namespaced_generators_test.rb +++ b/railties/test/generators/namespaced_generators_test.rb @@ -47,7 +47,6 @@ class NamespacedControllerGeneratorTest < NamespacedGeneratorTestCase def test_helper_is_also_namespaced run_generator assert_file "app/helpers/test_app/account_helper.rb", /module TestApp/, / module AccountHelper/ - assert_file "test/helpers/test_app/account_helper_test.rb", /module TestApp/, / class AccountHelperTest/ end def test_invokes_default_test_framework @@ -149,8 +148,8 @@ class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase run_generator assert_file "app/mailers/test_app/notifier.rb" do |mailer| assert_match(/module TestApp/, mailer) - assert_match(/class Notifier < ActionMailer::Base/, mailer) - assert_match(/default from: "from@example.com"/, mailer) + assert_match(/class Notifier < ApplicationMailer/, mailer) + assert_no_match(/default from: "from@example.com"/, mailer) end end @@ -229,7 +228,6 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase # Helpers assert_file "app/helpers/test_app/product_lines_helper.rb" - assert_file "test/helpers/test_app/product_lines_helper_test.rb" # Stylesheets assert_file "app/assets/stylesheets/scaffold.css" @@ -260,7 +258,6 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase # Helpers assert_no_file "app/helpers/test_app/product_lines_helper.rb" - assert_no_file "test/helpers/test_app/product_lines_helper_test.rb" # Stylesheets (should not be removed) assert_file "app/assets/stylesheets/scaffold.css" @@ -297,7 +294,6 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase # Helpers assert_file "app/helpers/test_app/admin/roles_helper.rb" - assert_file "test/helpers/test_app/admin/roles_helper_test.rb" # Stylesheets assert_file "app/assets/stylesheets/scaffold.css" @@ -329,7 +325,6 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase # Helpers assert_no_file "app/helpers/test_app/admin/roles_helper.rb" - assert_no_file "test/helpers/test_app/admin/roles_helper_test.rb" # Stylesheets (should not be removed) assert_file "app/assets/stylesheets/scaffold.css" @@ -366,7 +361,6 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase # Helpers assert_file "app/helpers/test_app/admin/user/special/roles_helper.rb" - assert_file "test/helpers/test_app/admin/user/special/roles_helper_test.rb" # Stylesheets assert_file "app/assets/stylesheets/scaffold.css" @@ -397,7 +391,6 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase # Helpers assert_no_file "app/helpers/test_app/admin/user/special/roles_helper.rb" - assert_no_file "test/helpers/test_app/admin/user/special/roles_helper_test.rb" # Stylesheets (should not be removed) assert_file "app/assets/stylesheets/scaffold.css" diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb index 0d01931daa..e9f06a1fd7 100644 --- a/railties/test/generators/plugin_generator_test.rb +++ b/railties/test/generators/plugin_generator_test.rb @@ -54,7 +54,11 @@ class PluginGeneratorTest < Rails::Generators::TestCase run_generator assert_file "README.rdoc", /Bukkits/ assert_no_file "config/routes.rb" - assert_file "test/test_helper.rb" + assert_file "test/test_helper.rb" do |content| + assert_match(/require.+test\/dummy\/config\/environment/, content) + assert_match(/ActiveRecord::Migrator\.migrations_paths.+test\/dummy\/db\/migrate/, content) + assert_match(/Minitest\.backtrace_filter = Minitest::BacktraceFilter\.new/, content) + end assert_file "test/bukkits_test.rb", /assert_kind_of Module, Bukkits/ end @@ -67,7 +71,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase def test_inclusion_of_a_debugger run_generator [destination_root, '--full'] - if defined?(JRUBY_VERSION) + if defined?(JRUBY_VERSION) || RUBY_ENGINE == "rbx" assert_file "Gemfile" do |content| assert_no_match(/byebug/, content) assert_no_match(/debugger/, content) @@ -95,7 +99,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase end def test_generating_adds_dummy_app_without_javascript_and_assets_deps - run_generator [destination_root] + run_generator assert_file "test/dummy/app/assets/stylesheets/application.css" @@ -136,6 +140,20 @@ class PluginGeneratorTest < Rails::Generators::TestCase end end + def test_app_generator_without_skips + run_generator + assert_file "test/dummy/config/application.rb", /\s+require\s+["']rails\/all["']/ + assert_file "test/dummy/config/environments/development.rb" do |content| + assert_match(/config\.action_mailer\.raise_delivery_errors = false/, content) + end + assert_file "test/dummy/config/environments/test.rb" do |content| + assert_match(/config\.action_mailer\.delivery_method = :test/, content) + end + assert_file "test/dummy/config/environments/production.rb" do |content| + assert_match(/# config\.action_mailer\.raise_delivery_errors = false/, content) + end + end + def test_active_record_is_removed_from_frameworks_if_skip_active_record_is_given run_generator [destination_root, "--skip-active-record"] assert_file "test/dummy/config/application.rb", /#\s+require\s+["']active_record\/railtie["']/ @@ -149,6 +167,20 @@ class PluginGeneratorTest < Rails::Generators::TestCase end end + def test_action_mailer_is_removed_from_frameworks_if_skip_action_mailer_is_given + run_generator [destination_root, "--skip-action-mailer"] + assert_file "test/dummy/config/application.rb", /#\s+require\s+["']action_mailer\/railtie["']/ + assert_file "test/dummy/config/environments/development.rb" do |content| + assert_no_match(/config\.action_mailer/, content) + end + assert_file "test/dummy/config/environments/test.rb" do |content| + assert_no_match(/config\.action_mailer/, content) + end + assert_file "test/dummy/config/environments/production.rb" do |content| + assert_no_match(/config\.action_mailer/, content) + end + end + def test_ensure_that_database_option_is_passed_to_app_generator run_generator [destination_root, "--database", "postgresql"] assert_file "test/dummy/config/database.yml", /postgres/ @@ -242,6 +274,10 @@ class PluginGeneratorTest < Rails::Generators::TestCase assert_match(/stylesheet_link_tag\s+['"]bukkits\/application['"]/, contents) assert_match(/javascript_include_tag\s+['"]bukkits\/application['"]/, contents) end + assert_file "test/test_helper.rb" do |content| + assert_match(/ActiveRecord::Migrator\.migrations_paths.+\.\.\/test\/dummy\/db\/migrate/, content) + assert_match(/ActiveRecord::Migrator\.migrations_paths.+<<.+\.\.\/db\/migrate/, content) + end end def test_creating_gemspec @@ -270,6 +306,10 @@ class PluginGeneratorTest < Rails::Generators::TestCase assert_file "spec/dummy" assert_file "spec/dummy/config/application.rb" assert_no_file "test/dummy" + assert_file "test/test_helper.rb" do |content| + assert_match(/require.+spec\/dummy\/config\/environment/, content) + assert_match(/ActiveRecord::Migrator\.migrations_paths.+spec\/dummy\/db\/migrate/, content) + end end def test_creating_dummy_application_with_different_name @@ -277,6 +317,10 @@ class PluginGeneratorTest < Rails::Generators::TestCase assert_file "spec/fake" assert_file "spec/fake/config/application.rb" assert_no_file "test/dummy" + assert_file "test/test_helper.rb" do |content| + assert_match(/require.+spec\/fake\/config\/environment/, content) + assert_match(/ActiveRecord::Migrator\.migrations_paths.+spec\/fake\/db\/migrate/, content) + end end def test_creating_dummy_without_tests_but_with_dummy_path @@ -284,6 +328,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase assert_file "spec/dummy" assert_file "spec/dummy/config/application.rb" assert_no_file "test" + assert_no_file "test/test_helper.rb" assert_file '.gitignore' do |contents| assert_match(/spec\/dummy/, contents) end @@ -335,7 +380,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase Object.const_set('APP_PATH', Rails.root) FileUtils.touch gemfile_path - run_generator [destination_root] + run_generator assert_file gemfile_path, /gem 'bukkits', path: 'tmp\/bukkits'/ ensure @@ -376,19 +421,19 @@ class PluginGeneratorTest < Rails::Generators::TestCase name = `git config user.name`.chomp rescue "TODO: Write your name" email = `git config user.email`.chomp rescue "TODO: Write your email address" - run_generator [destination_root] + run_generator assert_file "bukkits.gemspec" do |contents| - assert_match(/#{Regexp.escape(name)}/, contents) - assert_match(/#{Regexp.escape(email)}/, contents) + assert_match name, contents + assert_match email, contents end end def test_git_name_in_license_file name = `git config user.name`.chomp rescue "TODO: Write your name" - run_generator [destination_root] + run_generator assert_file "MIT-LICENSE" do |contents| - assert_match(/#{Regexp.escape(name)}/, contents) + assert_match name, contents end end @@ -398,11 +443,11 @@ class PluginGeneratorTest < Rails::Generators::TestCase run_generator [destination_root, '--skip-git'] assert_file "MIT-LICENSE" do |contents| - assert_match(/#{Regexp.escape(name)}/, contents) + assert_match name, contents end assert_file "bukkits.gemspec" do |contents| - assert_match(/#{Regexp.escape(name)}/, contents) - assert_match(/#{Regexp.escape(email)}/, contents) + assert_match name, contents + assert_match email, contents end end @@ -416,10 +461,10 @@ protected end def assert_match_sqlite3(contents) - unless defined?(JRUBY_VERSION) - assert_match(/group :development do\n gem 'sqlite3'\nend/, contents) - else + if defined?(JRUBY_VERSION) assert_match(/group :development do\n gem 'activerecord-jdbcsqlite3-adapter'\nend/, contents) + else + assert_match(/group :development do\n gem 'sqlite3'\nend/, contents) end end end diff --git a/railties/test/generators/resource_generator_test.rb b/railties/test/generators/resource_generator_test.rb index dcdff22152..581d80d60e 100644 --- a/railties/test/generators/resource_generator_test.rb +++ b/railties/test/generators/resource_generator_test.rb @@ -36,7 +36,6 @@ class ResourceGeneratorTest < Rails::Generators::TestCase assert_file "test/controllers/accounts_controller_test.rb", /class AccountsControllerTest < ActionController::TestCase/ assert_file "app/helpers/accounts_helper.rb", /module AccountsHelper/ - assert_file "test/helpers/accounts_helper_test.rb", /class AccountsHelperTest < ActionView::TestCase/ end def test_resource_controller_with_actions diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb index 46eacd2845..ca972a3bdd 100644 --- a/railties/test/generators/scaffold_controller_generator_test.rb +++ b/railties/test/generators/scaffold_controller_generator_test.rb @@ -81,7 +81,6 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase def test_helper_are_invoked_with_a_pluralized_name run_generator assert_file "app/helpers/users_helper.rb", /module UsersHelper/ - assert_file "test/helpers/users_helper_test.rb", /class UsersHelperTest < ActionView::TestCase/ end def test_views_are_generated @@ -126,7 +125,6 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase def test_skip_helper_if_required run_generator ["User", "name:string", "age:integer", "--no-helper"] assert_no_file "app/helpers/users_helper.rb" - assert_no_file "test/helpers/users_helper_test.rb" end def test_skip_layout_if_required diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb index c44ce32122..ad365f45d0 100644 --- a/railties/test/generators/scaffold_generator_test.rb +++ b/railties/test/generators/scaffold_generator_test.rb @@ -81,7 +81,6 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase # Helpers assert_file "app/helpers/product_lines_helper.rb" - assert_file "test/helpers/product_lines_helper_test.rb" # Assets assert_file "app/assets/stylesheets/scaffold.css" @@ -125,7 +124,6 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase # Helpers assert_no_file "app/helpers/product_lines_helper.rb" - assert_no_file "test/helpers/product_lines_helper_test.rb" # Assets assert_file "app/assets/stylesheets/scaffold.css", /:visited/ @@ -193,7 +191,6 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase # Helpers assert_file "app/helpers/admin/roles_helper.rb" - assert_file "test/helpers/admin/roles_helper_test.rb" # Assets assert_file "app/assets/stylesheets/scaffold.css", /:visited/ @@ -227,7 +224,6 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase # Helpers assert_no_file "app/helpers/admin/roles_helper.rb" - assert_no_file "test/helpers/admin/roles_helper_test.rb" # Assets assert_file "app/assets/stylesheets/scaffold.css" @@ -264,13 +260,27 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase assert_no_file "app/assets/stylesheets/posts.css" end - def test_scaffold_generator_no_assets_with_switch_resource_route_false + def test_scaffold_generator_with_switch_resource_route_false run_generator [ "posts", "--resource-route=false" ] assert_file "config/routes.rb" do |route| assert_no_match(/resources :posts$/, route) end end + def test_scaffold_generator_no_helper_with_switch_no_helper + output = run_generator [ "posts", "--no-helper" ] + + assert_no_match(/error/, output) + assert_no_file "app/helpers/posts_helper.rb" + end + + def test_scaffold_generator_no_helper_with_switch_helper_false + output = run_generator [ "posts", "--helper=false" ] + + assert_no_match(/error/, output) + assert_no_file "app/helpers/posts_helper.rb" + end + def test_scaffold_generator_no_stylesheets run_generator [ "posts", "--no-stylesheets" ] assert_no_file "app/assets/stylesheets/scaffold.css" diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index b5765c391e..127e059bf1 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -152,6 +152,8 @@ class GeneratorsTest < Rails::Generators::TestCase klass = Rails::Generators.find_by_namespace(:plugin, :remarkable) assert klass assert_equal "test_unit:plugin", klass.namespace + ensure + Rails::Generators.fallbacks.delete(:remarkable) end def test_fallbacks_for_generators_on_find_by_namespace_with_context @@ -159,18 +161,26 @@ class GeneratorsTest < Rails::Generators::TestCase klass = Rails::Generators.find_by_namespace(:remarkable, :rails, :plugin) assert klass assert_equal "test_unit:plugin", klass.namespace + ensure + Rails::Generators.fallbacks.delete(:remarkable) end def test_fallbacks_for_generators_on_invoke Rails::Generators.fallbacks[:shoulda] = :test_unit TestUnit::Generators::ModelGenerator.expects(:start).with(["Account"], {}) Rails::Generators.invoke "shoulda:model", ["Account"] + ensure + Rails::Generators.fallbacks.delete(:shoulda) end def test_nested_fallbacks_for_generators + Rails::Generators.fallbacks[:shoulda] = :test_unit Rails::Generators.fallbacks[:super_shoulda] = :shoulda TestUnit::Generators::ModelGenerator.expects(:start).with(["Account"], {}) Rails::Generators.invoke "super_shoulda:model", ["Account"] + ensure + Rails::Generators.fallbacks.delete(:shoulda) + Rails::Generators.fallbacks.delete(:super_shoulda) end def test_developer_options_are_overwritten_by_user_options diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index 92d6a1729c..9ad0ec0d34 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -9,6 +9,7 @@ require 'fileutils' require 'bundler/setup' unless defined?(Bundler) +require 'active_support' require 'active_support/testing/autorun' require 'active_support/test_case' @@ -140,7 +141,9 @@ module TestHelpers config.eager_load = false config.session_store :cookie_store, key: "_myapp_session" config.active_support.deprecation = :log + config.active_support.test_order = :random config.action_controller.allow_forgery_protection = false + config.log_level = :info RUBY end @@ -160,6 +163,8 @@ module TestHelpers app.secrets.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4" app.config.session_store :cookie_store, key: "_myapp_session" app.config.active_support.deprecation = :log + app.config.active_support.test_order = :random + app.config.log_level = :info yield app if block_given? app.initialize! @@ -229,6 +234,15 @@ module TestHelpers end end + def add_to_top_of_config(str) + environment = File.read("#{app_path}/config/application.rb") + if environment =~ /(Rails::Application\s*)/ + File.open("#{app_path}/config/application.rb", 'w') do |f| + f.puts $` + $1 + "\n#{str}\n" + $' + end + end + end + def add_to_config(str) environment = File.read("#{app_path}/config/application.rb") if environment =~ /(\n\s*end\s*end\s*)\Z/ @@ -276,8 +290,12 @@ module TestHelpers end def use_frameworks(arr) - to_remove = [:actionmailer, - :activerecord] - arr + to_remove = [:actionmailer, :activerecord] - arr + + if to_remove.include?(:activerecord) + remove_from_config 'config.active_record.*' + end + $:.reject! {|path| path =~ %r'/(#{to_remove.join('|')})/' } end @@ -292,6 +310,8 @@ class ActiveSupport::TestCase include TestHelpers::Rack include TestHelpers::Generation + self.test_order = :sorted + private def capture(stream) diff --git a/railties/test/path_generation_test.rb b/railties/test/path_generation_test.rb new file mode 100644 index 0000000000..13bf29d3c3 --- /dev/null +++ b/railties/test/path_generation_test.rb @@ -0,0 +1,88 @@ +# encoding: utf-8 +require 'abstract_unit' +require 'active_support/core_ext/object/with_options' +require 'active_support/core_ext/object/json' +require 'rails' +require 'rails/application' + +ROUTING = ActionDispatch::Routing + +class PathGenerationTest < ActiveSupport::TestCase + attr_reader :app + + class TestSet < ROUTING::RouteSet + def initialize(block) + @block = block + super() + end + + class Dispatcher < ROUTING::RouteSet::Dispatcher + def initialize(defaults, set, block) + super(defaults) + @block = block + @set = set + end + + def controller_reference(controller_param) + block = @block + set = @set + Class.new(ActionController::Base) { + include set.url_helpers + define_method(:process) { |name| block.call(self) } + def to_a; [200, {}, []]; end + } + end + end + + def dispatcher defaults + TestSet::Dispatcher.new defaults, self, @block + end + end + + def send_request(uri_or_host, method, path, script_name = nil) + host = uri_or_host.host unless path + path ||= uri_or_host.path + + params = {'PATH_INFO' => path, + 'REQUEST_METHOD' => method, + 'HTTP_HOST' => host } + + params['SCRIPT_NAME'] = script_name if script_name + + status, headers, body = app.call(params) + new_body = [] + body.each { |part| new_body << part } + body.close if body.respond_to? :close + [status, headers, new_body] + end + + def test_original_script_name + original_logger = Rails.logger + Rails.logger = Logger.new nil + + app = Class.new(Rails::Application) { + attr_accessor :controller + def initialize + super + app = self + @routes = TestSet.new ->(c) { app.controller = c } + secrets.secret_key_base = "foo" + secrets.secret_token = "foo" + end + def app; routes; end + } + + @app = app + app.routes.draw { resource :blogs } + + url = URI("http://example.org/blogs") + + send_request(url, 'GET', nil, '/FOO') + assert_equal '/FOO/blogs', app.instance.controller.blogs_path + + send_request(url, 'GET', nil) + assert_equal '/blogs', app.instance.controller.blogs_path + ensure + Rails.logger = original_logger + end +end diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb index 8d61af4972..d336a2e6c0 100644 --- a/railties/test/rails_info_controller_test.rb +++ b/railties/test/rails_info_controller_test.rb @@ -1,5 +1,4 @@ require 'abstract_unit' -require 'mocha/setup' # FIXME: stop using mocha module ActionController class Base @@ -15,26 +14,26 @@ class InfoControllerTest < ActionController::TestCase get '/rails/info/properties' => "rails/info#properties" get '/rails/info/routes' => "rails/info#routes" end - @controller.stubs(:local_request? => true) @routes = Rails.application.routes Rails::InfoController.send(:include, @routes.url_helpers) + + @request.env["REMOTE_ADDR"] = "127.0.0.1" end test "info controller does not allow remote requests" do - @controller.stubs(local_request?: false) + @request.env["REMOTE_ADDR"] = "example.org" get :properties assert_response :forbidden end test "info controller renders an error message when request was forbidden" do - @controller.stubs(local_request?: false) + @request.env["REMOTE_ADDR"] = "example.org" get :properties assert_select 'p' end test "info controller allows requests when all requests are considered local" do - @controller.stubs(local_request?: true) get :properties assert_response :success end diff --git a/railties/test/rails_info_test.rb b/railties/test/rails_info_test.rb index 4bec302ff8..92e4af25b5 100644 --- a/railties/test/rails_info_test.rb +++ b/railties/test/rails_info_test.rb @@ -38,21 +38,10 @@ class InfoTest < ActiveSupport::TestCase end def test_rails_version - assert_property 'Rails version', + assert_property 'Rails version', File.read(File.realpath('../../../RAILS_VERSION', __FILE__)).chomp end - def test_framework_version - assert_property 'Active Support version', ActiveSupport.version.to_s - end - - def test_frameworks_exist - Rails::Info.frameworks.each do |framework| - dir = File.dirname(__FILE__) + "/../../" + framework.delete('_') - assert File.directory?(dir), "#{framework.classify} does not exist" - end - end - def test_html_includes_middleware Rails::Info.module_eval do property 'Middleware', ['Rack::Lock', 'Rack::Static'] diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb index ec64ce5941..4ffcf64275 100644 --- a/railties/test/railties/engine_test.rb +++ b/railties/test/railties/engine_test.rb @@ -144,6 +144,42 @@ module RailtiesTest end end + test "dont reverse default railties order" do + @api = engine "api" do |plugin| + plugin.write "lib/api.rb", <<-RUBY + module Api + class Engine < ::Rails::Engine; end + end + RUBY + end + + # added last but here is loaded before api engine + @core = engine "core" do |plugin| + plugin.write "lib/core.rb", <<-RUBY + module Core + class Engine < ::Rails::Engine; end + end + RUBY + end + + @core.write "db/migrate/1_create_users.rb", <<-RUBY + class CreateUsers < ActiveRecord::Migration; end + RUBY + + @api.write "db/migrate/2_create_keys.rb", <<-RUBY + class CreateKeys < ActiveRecord::Migration; end + RUBY + + boot_rails + + Dir.chdir(app_path) do + output = `bundle exec rake railties:install:migrations`.split("\n") + + assert_match(/Copied migration \d+_create_users.core_engine.rb from core_engine/, output.first) + assert_match(/Copied migration \d+_create_keys.api_engine.rb from api_engine/, output.last) + end + end + test "mountable engine should copy migrations within engine_path" do @plugin.write "lib/bukkits.rb", <<-RUBY module Bukkits @@ -462,17 +498,12 @@ YAML boot_rails initializers = Rails.application.initializers.tsort - index = initializers.index { |i| i.name == "dummy_initializer" } - selection = initializers[(index-3)..(index)].map(&:name).map(&:to_s) - - assert_equal %w( - load_config_initializers - load_config_initializers - engines_blank_point - dummy_initializer - ), selection + dummy_index = initializers.index { |i| i.name == "dummy_initializer" } + config_index = initializers.rindex { |i| i.name == :load_config_initializers } + stack_index = initializers.index { |i| i.name == :build_middleware_stack } - assert index < initializers.index { |i| i.name == :build_middleware_stack } + assert config_index < dummy_index + assert dummy_index < stack_index end class Upcaser @@ -482,12 +513,12 @@ YAML def call(env) response = @app.call(env) - response[2].each { |b| b.upcase! } + response[2].each(&:upcase!) response end end - test "engine is a rack app and can have his own middleware stack" do + test "engine is a rack app and can have its own middleware stack" do add_to_config("config.action_dispatch.show_exceptions = false") @plugin.write "lib/bukkits.rb", <<-RUBY @@ -1174,7 +1205,7 @@ YAML test "engine can be properly mounted at root" do add_to_config("config.action_dispatch.show_exceptions = false") - add_to_config("config.serve_static_assets = false") + add_to_config("config.serve_static_files = false") @plugin.write "lib/bukkits.rb", <<-RUBY module Bukkits |