diff options
Diffstat (limited to 'railties/test')
39 files changed, 741 insertions, 222 deletions
diff --git a/railties/test/app_loader_test.rb b/railties/test/app_loader_test.rb index bb556f1968..0deb1a76df 100644 --- a/railties/test/app_loader_test.rb +++ b/railties/test/app_loader_test.rb @@ -9,12 +9,12 @@ class AppLoaderTest < ActiveSupport::TestCase @loader ||= Class.new do extend Rails::AppLoader - def self.exec_arguments - @exec_arguments - end + class << self + attr_accessor :exec_arguments - def self.exec(*args) - @exec_arguments = args + def exec(*args) + self.exec_arguments = args + end end end end @@ -40,13 +40,13 @@ class AppLoaderTest < ActiveSupport::TestCase test "is not in a Rails application if #{exe} is not found in the current or parent directories" do def loader.find_executables; end - assert !loader.exec_app + assert_not loader.exec_app end test "is not in a Rails application if #{exe} exists but is a folder" do FileUtils.mkdir_p(exe) - assert !loader.exec_app + assert_not loader.exec_app end ["APP_PATH", "ENGINE_PATH"].each do |keyword| @@ -61,7 +61,7 @@ class AppLoaderTest < ActiveSupport::TestCase test "is not in a Rails application if #{exe} exists but doesn't contain #{keyword}" do write exe - assert !loader.exec_app + assert_not loader.exec_app end test "is in a Rails application if parent directory has #{exe} containing #{keyword} and chdirs to the root directory" do @@ -76,7 +76,7 @@ class AppLoaderTest < ActiveSupport::TestCase # Compare the realpath in case either of them has symlinks. # - # This happens in particular in Mac OS X, where @tmp starts + # This happens in particular in macOS, where @tmp starts # with "/var", and Dir.pwd with "/private/var", due to a # default system symlink var -> private/var. assert_equal File.realpath("#@tmp/foo"), File.realpath(Dir.pwd) diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index 0d3262d6f6..4ca6d02b85 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -47,7 +47,7 @@ module ApplicationTests end def assert_no_file_exists(filename) - assert !File.exist?(filename), "#{filename} does exist" + assert_not File.exist?(filename), "#{filename} does exist" end test "assets routes have higher priority" do @@ -76,7 +76,7 @@ module ApplicationTests # Load app env app "production" - assert !defined?(Uglifier) + assert_not defined?(Uglifier) get "/assets/demo.js" assert_match "alert()", last_response.body assert defined?(Uglifier) @@ -270,10 +270,10 @@ module ApplicationTests app "production" # Checking if Uglifier is defined we can know if Sprockets was reached or not - assert !defined?(Uglifier) + assert_not defined?(Uglifier) get "/assets/#{asset_path}" assert_match "alert()", last_response.body - assert !defined?(Uglifier) + assert_not defined?(Uglifier) end test "precompile properly refers files referenced with asset_path" do diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index bd9b87467c..c2699006f6 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -361,7 +361,7 @@ module ApplicationTests end RUBY - assert !$prepared + assert_not $prepared app "development" @@ -576,6 +576,7 @@ module ApplicationTests app "development" assert_equal "3b7cd727ee24e8444053437c36cc66c3", app.secrets.secret_key_base + assert_equal "3b7cd727ee24e8444053437c36cc66c3", app.secret_key_base end test "secret_key_base is copied from config to secrets when not set" do @@ -1416,7 +1417,7 @@ module ApplicationTests assert_equal "XML", last_response.body end - test "Rails.application#env_config exists and include some existing parameters" do + test "Rails.application#env_config exists and includes some existing parameters" do make_basic_app assert_equal app.env_config["action_dispatch.parameter_filter"], app.config.filter_parameters @@ -1509,7 +1510,7 @@ module ApplicationTests end end - assert_not_nil SourceAnnotationExtractor::Annotation.extensions[/\.(coffee)$/] + assert_not_nil Rails::SourceAnnotationExtractor::Annotation.extensions[/\.(coffee)$/] end test "rake_tasks block works at instance level" do @@ -1978,6 +1979,23 @@ module ApplicationTests assert_equal true, ActionView::Helpers::FormTagHelper.default_enforce_utf8 end + test "ActionView::Template.finalize_compiled_template_methods is true by default" do + app "test" + assert_equal true, ActionView::Template.finalize_compiled_template_methods + end + + test "ActionView::Template.finalize_compiled_template_methods can be configured via config.action_view.finalize_compiled_template_methods" do + app_file "config/environments/test.rb", <<-RUBY + Rails.application.configure do + config.action_view.finalize_compiled_template_methods = false + end + RUBY + + app "test" + + assert_equal false, ActionView::Template.finalize_compiled_template_methods + end + private def force_lazy_load_hooks yield # Tasty clarifying sugar, homie! We only need to reference a constant to load it. diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index e631318f82..1530ea82d6 100644 --- a/railties/test/application/initializers/frameworks_test.rb +++ b/railties/test/application/initializers/frameworks_test.rb @@ -226,7 +226,7 @@ module ApplicationTests rails %w(generate model post title:string) rails %w(db:migrate db:schema:cache:dump db:rollback) require "#{app_path}/config/environment" - assert !ActiveRecord::Base.connection.schema_cache.data_sources("posts") + assert_not ActiveRecord::Base.connection.schema_cache.data_sources("posts") end test "active record establish_connection uses Rails.env if DATABASE_URL is not set" do diff --git a/railties/test/application/middleware/sendfile_test.rb b/railties/test/application/middleware/sendfile_test.rb index 9def3a0ce7..818ad61c64 100644 --- a/railties/test/application/middleware/sendfile_test.rb +++ b/railties/test/application/middleware/sendfile_test.rb @@ -29,7 +29,7 @@ module ApplicationTests simple_controller get "/" - assert !last_response.headers["X-Sendfile"] + assert_not last_response.headers["X-Sendfile"] assert_equal File.read(__FILE__), last_response.body end diff --git a/railties/test/application/middleware/session_test.rb b/railties/test/application/middleware/session_test.rb index a17988235a..9182a63ab7 100644 --- a/railties/test/application/middleware/session_test.rb +++ b/railties/test/application/middleware/session_test.rb @@ -31,7 +31,7 @@ module ApplicationTests add_to_config "config.force_ssl = true" add_to_config "config.ssl_options = { secure_cookies: false }" require "#{app_path}/config/environment" - assert !app.config.session_options[:secure] + assert_not app.config.session_options[:secure] end test "session is not loaded if it's not used" do @@ -51,7 +51,7 @@ module ApplicationTests get "/" assert last_request.env["HTTP_COOKIE"] - assert !last_response.headers["Set-Cookie"] + assert_not last_response.headers["Set-Cookie"] end test "session is empty and isn't saved on unverified request when using :null_session protect method" do diff --git a/railties/test/application/paths_test.rb b/railties/test/application/paths_test.rb index 0abc5cc9aa..28a9206daa 100644 --- a/railties/test/application/paths_test.rb +++ b/railties/test/application/paths_test.rb @@ -37,7 +37,7 @@ module ApplicationTests end def assert_not_in_load_path(*path) - assert !$:.any? { |p| File.expand_path(p) == root(*path) }, "Load path includes '#{root(*path)}'. They are:\n-----\n #{$:.join("\n")}\n-----" + assert_not $:.any? { |p| File.expand_path(p) == root(*path) }, "Load path includes '#{root(*path)}'. They are:\n-----\n #{$:.join("\n")}\n-----" end test "booting up Rails yields a valid paths object" do diff --git a/railties/test/application/per_request_digest_cache_test.rb b/railties/test/application/per_request_digest_cache_test.rb index 10d3313f6e..ab055c7648 100644 --- a/railties/test/application/per_request_digest_cache_test.rb +++ b/railties/test/application/per_request_digest_cache_test.rb @@ -5,11 +5,9 @@ require "rack/test" require "minitest/mock" require "action_view" -require "active_support/testing/method_call_assertions" class PerRequestDigestCacheTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation - include ActiveSupport::Testing::MethodCallAssertions include Rack::Test::Methods setup do diff --git a/railties/test/application/rack/logger_test.rb b/railties/test/application/rack/logger_test.rb index d949a48366..ea425d5fa5 100644 --- a/railties/test/application/rack/logger_test.rb +++ b/railties/test/application/rack/logger_test.rb @@ -53,6 +53,12 @@ module ApplicationTests wait assert_match 'Started HEAD "/"', logs end + + test "logger logs correct remote IP address" do + get "/", {}, { "REMOTE_ADDR" => "127.0.0.1", "HTTP_X_FORWARDED_FOR" => "1.2.3.4" } + wait + assert_match 'Started GET "/" for 1.2.3.4', logs + end end end end diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb index 5b4c42c189..0594236b1f 100644 --- a/railties/test/application/rake/dbs_test.rb +++ b/railties/test/application/rake/dbs_test.rb @@ -34,7 +34,7 @@ module ApplicationTests assert_equal expected_database, ActiveRecord::Base.connection_config[:database] if environment_loaded output = rails("db:drop") assert_match(/Dropped database/, output) - assert !File.exist?(expected_database) + assert_not File.exist?(expected_database) end end diff --git a/railties/test/application/rake/migrations_test.rb b/railties/test/application/rake/migrations_test.rb index bf5b07afbd..47c5ac105a 100644 --- a/railties/test/application/rake/migrations_test.rb +++ b/railties/test/application/rake/migrations_test.rb @@ -417,7 +417,7 @@ module ApplicationTests version = output =~ %r{[^/]+db/migrate/(\d+)_create_authors\.rb} && $1 rails "db:migrate", "db:rollback", "db:forward", "db:migrate:up", "db:migrate:down", "VERSION=#{version}" - assert !File.exist?("db/schema.rb"), "should not dump schema when configured not to" + assert_not File.exist?("db/schema.rb"), "should not dump schema when configured not to" end add_to_config("config.active_record.dump_schema_after_migration = true") diff --git a/railties/test/application/rake/multi_dbs_test.rb b/railties/test/application/rake/multi_dbs_test.rb new file mode 100644 index 0000000000..07d96fcb56 --- /dev/null +++ b/railties/test/application/rake/multi_dbs_test.rb @@ -0,0 +1,164 @@ +# frozen_string_literal: true + +require "isolation/abstract_unit" + +module ApplicationTests + module RakeTests + class RakeMultiDbsTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app(multi_db: true) + FileUtils.rm_rf("#{app_path}/config/environments") + end + + def teardown + teardown_app + end + + def db_create_and_drop(namespace, expected_database, environment_loaded: true) + Dir.chdir(app_path) do + output = rails("db:create") + assert_match(/Created database/, output) + assert_match_namespace(namespace, output) + assert File.exist?(expected_database) + + output = rails("db:drop") + assert_match(/Dropped database/, output) + assert_match_namespace(namespace, output) + assert_not File.exist?(expected_database) + end + end + + def db_create_and_drop_namespace(namespace, expected_database, environment_loaded: true) + Dir.chdir(app_path) do + output = rails("db:create:#{namespace}") + assert_match(/Created database/, output) + assert_match_namespace(namespace, output) + assert File.exist?(expected_database) + + output = rails("db:drop:#{namespace}") + assert_match(/Dropped database/, output) + assert_match_namespace(namespace, output) + assert_not File.exist?(expected_database) + end + end + + def assert_match_namespace(namespace, output) + if namespace == "primary" + assert_match(/#{Rails.env}.sqlite3/, output) + else + assert_match(/#{Rails.env}_#{namespace}.sqlite3/, output) + end + end + + def db_migrate_and_schema_dump_and_load(namespace, expected_database, format) + Dir.chdir(app_path) do + rails "generate", "model", "book", "title:string" + rails "generate", "model", "dog", "name:string" + write_models_for_animals + rails "db:migrate", "db:#{format}:dump" + + if format == "schema" + schema_dump = File.read("db/#{format}.rb") + schema_dump_animals = File.read("db/animals_#{format}.rb") + assert_match(/create_table \"books\"/, schema_dump) + assert_match(/create_table \"dogs\"/, schema_dump_animals) + else + schema_dump = File.read("db/#{format}.sql") + schema_dump_animals = File.read("db/animals_#{format}.sql") + assert_match(/CREATE TABLE (?:IF NOT EXISTS )?\"books\"/, schema_dump) + assert_match(/CREATE TABLE (?:IF NOT EXISTS )?\"dogs\"/, schema_dump_animals) + end + + rails "db:#{format}:load" + + ar_tables = lambda { rails("runner", "p ActiveRecord::Base.connection.tables").strip } + animals_tables = lambda { rails("runner", "p AnimalsBase.connection.tables").strip } + + assert_equal '["schema_migrations", "ar_internal_metadata", "books"]', ar_tables[] + assert_equal '["schema_migrations", "ar_internal_metadata", "dogs"]', animals_tables[] + end + end + + def db_migrate_namespaced(namespace, expected_database) + Dir.chdir(app_path) do + rails "generate", "model", "book", "title:string" + rails "generate", "model", "dog", "name:string" + write_models_for_animals + output = rails("db:migrate:#{namespace}") + if namespace == "primary" + assert_match(/CreateBooks: migrated/, output) + else + assert_match(/CreateDogs: migrated/, output) + end + end + end + + def write_models_for_animals + # make a directory for the animals migration + FileUtils.mkdir_p("#{app_path}/db/animals_migrate") + # move the dogs migration if it unless it already lives there + FileUtils.mv(Dir.glob("#{app_path}/db/migrate/**/*dogs.rb").first, "db/animals_migrate/") unless Dir.glob("#{app_path}/db/animals_migrate/**/*dogs.rb").first + # delete the dogs migration if it's still present in the + # migrate folder. This is necessary because sometimes + # the code isn't fast enough and an extra migration gets made + FileUtils.rm(Dir.glob("#{app_path}/db/migrate/**/*dogs.rb").first) if Dir.glob("#{app_path}/db/migrate/**/*dogs.rb").first + + # change the base of the dog model + app_path("/app/models/dog.rb") do |file_name| + file = File.read("#{app_path}/app/models/dog.rb") + file.sub!(/ApplicationRecord/, "AnimalsBase") + File.write(file_name, file) + end + + # create the base model for dog to inherit from + File.open("#{app_path}/app/models/animals_base.rb", "w") do |file| + file.write(<<-EOS +class AnimalsBase < ActiveRecord::Base + self.abstract_class = true + + establish_connection :animals +end +EOS +) + end + end + + test "db:create and db:drop works on all databases for env" do + require "#{app_path}/config/environment" + ActiveRecord::Base.configurations[Rails.env].each do |namespace, config| + db_create_and_drop namespace, config["database"] + end + end + + test "db:create:namespace and db:drop:namespace works on specified databases" do + require "#{app_path}/config/environment" + ActiveRecord::Base.configurations[Rails.env].each do |namespace, config| + db_create_and_drop_namespace namespace, config["database"] + end + end + + test "db:migrate and db:schema:dump and db:schema:load works on all databases" do + require "#{app_path}/config/environment" + ActiveRecord::Base.configurations[Rails.env].each do |namespace, config| + db_migrate_and_schema_dump_and_load namespace, config["database"], "schema" + end + end + + test "db:migrate and db:structure:dump and db:structure:load works on all databases" do + require "#{app_path}/config/environment" + ActiveRecord::Base.configurations[Rails.env].each do |namespace, config| + db_migrate_and_schema_dump_and_load namespace, config["database"], "structure" + end + end + + test "db:migrate:namespace works" do + require "#{app_path}/config/environment" + ActiveRecord::Base.configurations[Rails.env].each do |namespace, config| + db_migrate_namespaced namespace, config["database"] + end + end + end + end +end diff --git a/railties/test/application/rake/notes_test.rb b/railties/test/application/rake/notes_test.rb index 8e9fe9b6b4..9e22ba84b5 100644 --- a/railties/test/application/rake/notes_test.rb +++ b/railties/test/application/rake/notes_test.rb @@ -30,19 +30,22 @@ module ApplicationTests app_file "config/locales/en.yaml", "# TODO: note in yaml" app_file "app/views/home/index.ruby", "# TODO: note in ruby" - run_rake_notes do |output, lines| - assert_match(/note in erb/, output) - assert_match(/note in js/, output) - assert_match(/note in css/, output) - assert_match(/note in rake/, output) - assert_match(/note in builder/, output) - assert_match(/note in yml/, output) - assert_match(/note in yaml/, output) - assert_match(/note in ruby/, output) - - assert_equal 9, lines.size - assert_equal [4], lines.map(&:size).uniq + stderr = capture(:stderr) do + run_rake_notes do |output, lines| + assert_match(/note in erb/, output) + assert_match(/note in js/, output) + assert_match(/note in css/, output) + assert_match(/note in rake/, output) + assert_match(/note in builder/, output) + assert_match(/note in yml/, output) + assert_match(/note in yaml/, output) + assert_match(/note in ruby/, output) + + assert_equal 9, lines.size + assert_equal [4], lines.map(&:size).uniq + end end + assert_match(/DEPRECATION WARNING: This rake task is deprecated and will be removed in Rails 6.1/, stderr) end test "notes finds notes in default directories" do @@ -54,17 +57,20 @@ module ApplicationTests app_file "some_other_dir/blah.rb", "# TODO: note in some_other directory" - run_rake_notes do |output, lines| - assert_match(/note in app directory/, output) - assert_match(/note in config directory/, output) - assert_match(/note in db directory/, output) - assert_match(/note in lib directory/, output) - assert_match(/note in test directory/, output) - assert_no_match(/note in some_other directory/, output) - - assert_equal 5, lines.size - assert_equal [4], lines.map(&:size).uniq + stderr = capture(:stderr) do + run_rake_notes do |output, lines| + assert_match(/note in app directory/, output) + assert_match(/note in config directory/, output) + assert_match(/note in db directory/, output) + assert_match(/note in lib directory/, output) + assert_match(/note in test directory/, output) + assert_no_match(/note in some_other directory/, output) + + assert_equal 5, lines.size + assert_equal [4], lines.map(&:size).uniq + end end + assert_match(/DEPRECATION WARNING: This rake task is deprecated and will be removed in Rails 6.1/, stderr) end test "notes finds notes in custom directories" do @@ -76,18 +82,22 @@ module ApplicationTests app_file "some_other_dir/blah.rb", "# TODO: note in some_other directory" - run_rake_notes "SOURCE_ANNOTATION_DIRECTORIES='some_other_dir' bin/rails notes" do |output, lines| - assert_match(/note in app directory/, output) - assert_match(/note in config directory/, output) - assert_match(/note in db directory/, output) - assert_match(/note in lib directory/, output) - assert_match(/note in test directory/, output) + stderr = capture(:stderr) do + run_rake_notes "SOURCE_ANNOTATION_DIRECTORIES='some_other_dir' bin/rake notes" do |output, lines| + assert_match(/note in app directory/, output) + assert_match(/note in config directory/, output) + assert_match(/note in db directory/, output) + assert_match(/note in lib directory/, output) + assert_match(/note in test directory/, output) - assert_match(/note in some_other directory/, output) + assert_match(/note in some_other directory/, output) - assert_equal 6, lines.size - assert_equal [4], lines.map(&:size).uniq + assert_equal 6, lines.size + assert_equal [4], lines.map(&:size).uniq + end end + assert_match(/DEPRECATION WARNING: This rake task is deprecated and will be removed in Rails 6.1/, stderr) + assert_match(/DEPRECATION WARNING: `SOURCE_ANNOTATION_DIRECTORIES` is deprecated and will be removed in Rails 6.1/, stderr) end test "custom rake task finds specific notes in specific directories" do @@ -101,7 +111,7 @@ module ApplicationTests task :notes_custom do tags = 'TODO|FIXME' opts = { dirs: %w(lib test), tag: true } - SourceAnnotationExtractor.enumerate(tags, opts) + Rails::SourceAnnotationExtractor.enumerate(tags, opts) end EOS @@ -122,11 +132,14 @@ module ApplicationTests app_file "app/assets/stylesheets/application.css.scss", "// TODO: note in scss" app_file "app/assets/stylesheets/application.css.sass", "// TODO: note in sass" - run_rake_notes do |output, lines| - assert_match(/note in scss/, output) - assert_match(/note in sass/, output) - assert_equal 2, lines.size + stderr = capture(:stderr) do + run_rake_notes do |output, lines| + assert_match(/note in scss/, output) + assert_match(/note in sass/, output) + assert_equal 2, lines.size + end end + assert_match(/DEPRECATION WARNING: This rake task is deprecated and will be removed in Rails 6.1/, stderr) end test "register additional directories" do @@ -134,38 +147,27 @@ module ApplicationTests app_file "spec/models/user_spec.rb", "# TODO: note in model spec" add_to_config ' config.annotations.register_directories("spec") ' - run_rake_notes do |output, lines| - assert_match(/note in spec/, output) - assert_match(/note in model spec/, output) - assert_equal 2, lines.size + stderr = capture(:stderr) do + run_rake_notes do |output, lines| + assert_match(/note in spec/, output) + assert_match(/note in model spec/, output) + assert_equal 2, lines.size + end end + assert_match(/DEPRECATION WARNING: This rake task is deprecated and will be removed in Rails 6.1/, stderr) end private - def run_rake_notes(command = "bin/rails notes") - boot_rails - load_tasks - + def run_rake_notes(command = "bin/rake notes") Dir.chdir(app_path) do output = `#{command}` - lines = output.scan(/\[([0-9\s]+)\]\s/).flatten + + lines = output.scan(/\[([0-9\s]+)\]\s/).flatten yield output, lines end end - - def load_tasks - require "rake" - require "rdoc/task" - require "rake/testtask" - - Rails.application.load_tasks - end - - def boot_rails - require "#{app_path}/config/environment" - end end end end diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb index 9683230d07..1522a2bbc5 100644 --- a/railties/test/application/rake_test.rb +++ b/railties/test/application/rake_test.rb @@ -41,7 +41,7 @@ module ApplicationTests rails "db:create", "db:migrate" output = rails("db:test:prepare", "test") - refute_match(/ActiveRecord::ProtectedEnvironmentError/, output) + assert_no_match(/ActiveRecord::ProtectedEnvironmentError/, output) end end @@ -229,7 +229,7 @@ module ApplicationTests def test_rake_clear_schema_cache rails "db:schema:cache:dump", "db:schema:cache:clear" - assert !File.exist?(File.join(app_path, "db", "schema_cache.yml")) + assert_not File.exist?(File.join(app_path, "db", "schema_cache.yml")) end def test_copy_templates diff --git a/railties/test/application/rendering_test.rb b/railties/test/application/rendering_test.rb index 3724886c54..ab1591f388 100644 --- a/railties/test/application/rendering_test.rb +++ b/railties/test/application/rendering_test.rb @@ -4,7 +4,7 @@ require "isolation/abstract_unit" require "rack/test" module ApplicationTests - class RoutingTest < ActiveSupport::TestCase + class RenderingTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation include Rack::Test::Methods diff --git a/railties/test/application/server_test.rb b/railties/test/application/server_test.rb index f3a7e00a4d..92b991dd05 100644 --- a/railties/test/application/server_test.rb +++ b/railties/test/application/server_test.rb @@ -36,7 +36,7 @@ module ApplicationTests skip "PTY unavailable" unless available_pty? File.open("#{app_path}/config/boot.rb", "w") do |f| - f.puts "ENV['BUNDLE_GEMFILE'] = '#{Bundler.default_gemfile.to_s}'" + f.puts "ENV['BUNDLE_GEMFILE'] = '#{Bundler.default_gemfile}'" f.puts "require 'bundler/setup'" end diff --git a/railties/test/application/test_runner_test.rb b/railties/test/application/test_runner_test.rb index 8e5ccf94cc..455dc60efd 100644 --- a/railties/test/application/test_runner_test.rb +++ b/railties/test/application/test_runner_test.rb @@ -504,7 +504,7 @@ module ApplicationTests create_test_file :models, "post", pass: false, print: false output = run_test_command("test/models/post_test.rb") - expect = %r{Running:\n\nF\n\nFailure:\nPostTest#test_truth \[[^\]]+test/models/post_test.rb:6\]:\nwups!\n\nbin/rails test test/models/post_test.rb:4\n\n\n\n} + expect = %r{Running:\n\nF\n\nFailure:\nPostTest#test_truth \[[^\]]+test/models/post_test.rb:6\]:\nwups!\n\nrails test test/models/post_test.rb:4\n\n\n\n} assert_match expect, output end @@ -553,7 +553,7 @@ module ApplicationTests create_test_file :models, "account" create_test_file :models, "post", pass: false # This specifically verifies TEST for backwards compatibility with rake test - # as bin/rails test already supports running tests from a single file more cleanly. + # as `rails test` already supports running tests from a single file more cleanly. output = Dir.chdir(app_path) { `bin/rake test TEST=test/models/post_test.rb` } assert_match "PostTest", output, "passing TEST= should run selected test" diff --git a/railties/test/backtrace_cleaner_test.rb b/railties/test/backtrace_cleaner_test.rb index 70917ba20b..8490f9eb10 100644 --- a/railties/test/backtrace_cleaner_test.rb +++ b/railties/test/backtrace_cleaner_test.rb @@ -25,10 +25,18 @@ class BacktraceCleanerTest < ActiveSupport::TestCase end test "should consider traces from irb lines as User code" do - backtrace = [ "from (irb):1", - "from /Path/to/rails/railties/lib/rails/commands/console.rb:77:in `start'", - "from bin/rails:4:in `<main>'" ] + backtrace = [ "(irb):1", + "/Path/to/rails/railties/lib/rails/commands/console.rb:77:in `start'", + "bin/rails:4:in `<main>'" ] + result = @cleaner.clean(backtrace) + assert_equal "(irb):1", result[0] + assert_equal 1, result.length + end + + test "should omit ActionView template methods names" do + method_name = ActionView::Template.new(nil, "app/views/application/index.html.erb", nil, {}).send :method_name + backtrace = [ "app/views/application/index.html.erb:4:in `block in #{method_name}'"] result = @cleaner.clean(backtrace, :all) - assert_equal "from (irb):1", result[0] + assert_equal "app/views/application/index.html.erb:4", result[0] end end diff --git a/railties/test/command/spellchecker_test.rb b/railties/test/command/spellchecker_test.rb index aff50a3e73..e6a7a3957c 100644 --- a/railties/test/command/spellchecker_test.rb +++ b/railties/test/command/spellchecker_test.rb @@ -5,6 +5,6 @@ require "rails/command/spellchecker" class Rails::Command::SpellcheckerTest < ActiveSupport::TestCase test "suggests a word correction from dictionary" do - assert_equal %w(thin cgi puma), Rails::Command::Spellchecker.suggest("tin", from: %w(puma thin cgi)) + assert_equal "thin", Rails::Command::Spellchecker.suggest("tin", from: %w(puma thin cgi)) end end diff --git a/railties/test/commands/console_test.rb b/railties/test/commands/console_test.rb index b7cdb8229e..0b2fe204f8 100644 --- a/railties/test/commands/console_test.rb +++ b/railties/test/commands/console_test.rb @@ -151,7 +151,8 @@ class Rails::ConsoleTest < ActiveSupport::TestCase def build_app(console) mocked_console = Class.new do - attr_reader :sandbox, :console + attr_accessor :sandbox + attr_reader :console def initialize(console) @console = console @@ -161,10 +162,6 @@ class Rails::ConsoleTest < ActiveSupport::TestCase self end - def sandbox=(arg) - @sandbox = arg - end - def load_console end end diff --git a/railties/test/commands/credentials_test.rb b/railties/test/commands/credentials_test.rb index 663ee73bcd..5b8b9e4eda 100644 --- a/railties/test/commands/credentials_test.rb +++ b/railties/test/commands/credentials_test.rb @@ -15,7 +15,7 @@ class Rails::Command::CredentialsCommandTest < ActiveSupport::TestCase test "edit without editor gives hint" do run_edit_command(editor: "").tap do |output| assert_match "No $EDITOR to open file in", output - assert_match "bin/rails credentials:edit", output + assert_match "rails credentials:edit", output end end @@ -49,7 +49,7 @@ class Rails::Command::CredentialsCommandTest < ActiveSupport::TestCase FileUtils.rm("config/master.key") switch_env("RAILS_MASTER_KEY", key) do - run_edit_command + assert_match(/access_key_id: 123/, run_edit_command) assert_not File.exist?("config/master.key") end end diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb index 6ad96b28c7..5e3eca6585 100644 --- a/railties/test/commands/dbconsole_test.rb +++ b/railties/test/commands/dbconsole_test.rb @@ -123,31 +123,31 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase def test_mysql start(adapter: "mysql2", database: "db") - assert !aborted + assert_not aborted assert_equal [%w[mysql mysql5], "db"], dbconsole.find_cmd_and_exec_args end def test_mysql_full start(adapter: "mysql2", database: "db", host: "locahost", port: 1234, socket: "socket", username: "user", password: "qwerty", encoding: "UTF-8") - assert !aborted + assert_not aborted assert_equal [%w[mysql mysql5], "--host=locahost", "--port=1234", "--socket=socket", "--user=user", "--default-character-set=UTF-8", "-p", "db"], dbconsole.find_cmd_and_exec_args end def test_mysql_include_password start({ adapter: "mysql2", database: "db", username: "user", password: "qwerty" }, ["-p"]) - assert !aborted + assert_not aborted assert_equal [%w[mysql mysql5], "--user=user", "--password=qwerty", "db"], dbconsole.find_cmd_and_exec_args end def test_postgresql start(adapter: "postgresql", database: "db") - assert !aborted + assert_not aborted assert_equal ["psql", "db"], dbconsole.find_cmd_and_exec_args end def test_postgresql_full start(adapter: "postgresql", database: "db", username: "user", password: "q1w2e3", host: "host", port: 5432) - assert !aborted + assert_not aborted assert_equal ["psql", "db"], dbconsole.find_cmd_and_exec_args assert_equal "user", ENV["PGUSER"] assert_equal "host", ENV["PGHOST"] @@ -157,7 +157,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase def test_postgresql_include_password start({ adapter: "postgresql", database: "db", username: "user", password: "q1w2e3" }, ["-p"]) - assert !aborted + assert_not aborted assert_equal ["psql", "db"], dbconsole.find_cmd_and_exec_args assert_equal "user", ENV["PGUSER"] assert_equal "q1w2e3", ENV["PGPASSWORD"] @@ -165,13 +165,13 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase def test_sqlite3 start(adapter: "sqlite3", database: "db.sqlite3") - assert !aborted + assert_not aborted assert_equal ["sqlite3", Rails.root.join("db.sqlite3").to_s], dbconsole.find_cmd_and_exec_args end def test_sqlite3_mode start({ adapter: "sqlite3", database: "db.sqlite3" }, ["--mode", "html"]) - assert !aborted + assert_not aborted assert_equal ["sqlite3", "-html", Rails.root.join("db.sqlite3").to_s], dbconsole.find_cmd_and_exec_args end @@ -182,27 +182,27 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase def test_sqlite3_db_absolute_path start(adapter: "sqlite3", database: "/tmp/db.sqlite3") - assert !aborted + assert_not aborted assert_equal ["sqlite3", "/tmp/db.sqlite3"], dbconsole.find_cmd_and_exec_args end def test_sqlite3_db_without_defined_rails_root Rails.stub(:respond_to?, false) do start(adapter: "sqlite3", database: "config/db.sqlite3") - assert !aborted + assert_not aborted assert_equal ["sqlite3", Rails.root.join("../config/db.sqlite3").to_s], dbconsole.find_cmd_and_exec_args end end def test_oracle start(adapter: "oracle", database: "db", username: "user", password: "secret") - assert !aborted + assert_not aborted assert_equal ["sqlplus", "user@db"], dbconsole.find_cmd_and_exec_args end def test_oracle_include_password start({ adapter: "oracle", database: "db", username: "user", password: "secret" }, ["-p"]) - assert !aborted + assert_not aborted assert_equal ["sqlplus", "user/secret@db"], dbconsole.find_cmd_and_exec_args end @@ -265,14 +265,14 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase stdout = capture(:stdout) do Rails::Command.invoke(:dbconsole, ["-h"]) end - assert_match(/bin\/rails dbconsole \[environment\]/, stdout) + assert_match(/rails dbconsole \[environment\]/, stdout) end def test_print_help_long stdout = capture(:stdout) do Rails::Command.invoke(:dbconsole, ["--help"]) end - assert_match(/bin\/rails dbconsole \[environment\]/, stdout) + assert_match(/rails dbconsole \[environment\]/, stdout) end attr_reader :aborted, :output diff --git a/railties/test/commands/encrypted_test.rb b/railties/test/commands/encrypted_test.rb index 9fc73d5f18..8b608fe8c0 100644 --- a/railties/test/commands/encrypted_test.rb +++ b/railties/test/commands/encrypted_test.rb @@ -14,7 +14,7 @@ class Rails::Command::EncryptedCommandTest < ActiveSupport::TestCase test "edit without editor gives hint" do run_edit_command("config/tokens.yml.enc", editor: "").tap do |output| assert_match "No $EDITOR to open file in", output - assert_match "bin/rails encrypted:edit", output + assert_match "rails encrypted:edit", output end end diff --git a/railties/test/commands/notes_test.rb b/railties/test/commands/notes_test.rb new file mode 100644 index 0000000000..147019e299 --- /dev/null +++ b/railties/test/commands/notes_test.rb @@ -0,0 +1,128 @@ +# frozen_string_literal: true + +require "isolation/abstract_unit" +require "rails/command" +require "rails/commands/notes/notes_command" + +class Rails::Command::NotesTest < ActiveSupport::TestCase + setup :build_app + teardown :teardown_app + + test "`rails notes` displays results for default directories and default annotations with aligned line number and annotation tag" do + app_file "app/controllers/some_controller.rb", "# OPTIMIZE: note in app directory" + app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory" + app_file "db/some_seeds.rb", "# FIXME: note in db directory" + app_file "lib/some_file.rb", "# TODO: note in lib directory" + app_file "test/some_test.rb", "\n" * 100 + "# FIXME: note in test directory" + + app_file "some_other_dir/blah.rb", "# TODO: note in some_other directory" + + assert_equal <<~OUTPUT, run_notes_command + app/controllers/some_controller.rb: + * [ 1] [OPTIMIZE] note in app directory + + config/initializers/some_initializer.rb: + * [ 1] [TODO] note in config directory + + db/some_seeds.rb: + * [ 1] [FIXME] note in db directory + + lib/some_file.rb: + * [ 1] [TODO] note in lib directory + + test/some_test.rb: + * [101] [FIXME] note in test directory + + OUTPUT + end + + test "`rails notes` displays an empty string when no results were found" do + assert_equal "", run_notes_command + end + + test "`rails notes --annotations` displays results for a single annotation without being prefixed by a tag" do + app_file "db/some_seeds.rb", "# FIXME: note in db directory" + app_file "test/some_test.rb", "# FIXME: note in test directory" + + app_file "app/controllers/some_controller.rb", "# OPTIMIZE: note in app directory" + app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory" + + assert_equal <<~OUTPUT, run_notes_command(["--annotations", "FIXME"]) + db/some_seeds.rb: + * [1] note in db directory + + test/some_test.rb: + * [1] note in test directory + + OUTPUT + end + + test "`rails notes --annotations` displays results for multiple annotations being prefixed by a tag" do + app_file "app/controllers/some_controller.rb", "# FOOBAR: note in app directory" + app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory" + app_file "lib/some_file.rb", "# TODO: note in lib directory" + + app_file "test/some_test.rb", "# FIXME: note in test directory" + + assert_equal <<~OUTPUT, run_notes_command(["--annotations", "FOOBAR", "TODO"]) + app/controllers/some_controller.rb: + * [1] [FOOBAR] note in app directory + + config/initializers/some_initializer.rb: + * [1] [TODO] note in config directory + + lib/some_file.rb: + * [1] [TODO] note in lib directory + + OUTPUT + end + + test "displays results from additional directories added to the default directories from a config file" do + app_file "db/some_seeds.rb", "# FIXME: note in db directory" + app_file "lib/some_file.rb", "# TODO: note in lib directory" + app_file "spec/spec_helper.rb", "# TODO: note in spec" + app_file "spec/models/user_spec.rb", "# TODO: note in model spec" + + add_to_config "config.annotations.register_directories \"spec\"" + + assert_equal <<~OUTPUT, run_notes_command + db/some_seeds.rb: + * [1] [FIXME] note in db directory + + lib/some_file.rb: + * [1] [TODO] note in lib directory + + spec/models/user_spec.rb: + * [1] [TODO] note in model spec + + spec/spec_helper.rb: + * [1] [TODO] note in spec + + OUTPUT + end + + test "displays results from additional file extensions added to the default extensions from a config file" do + add_to_config "config.assets.precompile = []" + add_to_config %q{ config.annotations.register_extensions("scss", "sass") { |annotation| /\/\/\s*(#{annotation}):?\s*(.*)$/ } } + app_file "db/some_seeds.rb", "# FIXME: note in db directory" + app_file "app/assets/stylesheets/application.css.scss", "// TODO: note in scss" + app_file "app/assets/stylesheets/application.css.sass", "// TODO: note in sass" + + assert_equal <<~OUTPUT, run_notes_command + app/assets/stylesheets/application.css.sass: + * [1] [TODO] note in sass + + app/assets/stylesheets/application.css.scss: + * [1] [TODO] note in scss + + db/some_seeds.rb: + * [1] [FIXME] note in db directory + + OUTPUT + end + + private + def run_notes_command(args = []) + rails "notes", args + end +end diff --git a/railties/test/commands/server_test.rb b/railties/test/commands/server_test.rb index 467afe7cea..e5b1da6ea4 100644 --- a/railties/test/commands/server_test.rb +++ b/railties/test/commands/server_test.rb @@ -29,7 +29,7 @@ class Rails::Command::ServerCommandTest < ActiveSupport::TestCase end def test_using_server_mistype - assert_match(/Could not find server "tin". Maybe you meant "thin" or "cgi"/, run_command("--using", "tin")) + assert_match(/Could not find server "tin". Maybe you meant "thin"?/, run_command("--using", "tin")) end def test_using_positional_argument_deprecation @@ -90,6 +90,15 @@ class Rails::Command::ServerCommandTest < ActiveSupport::TestCase def test_environment_with_host switch_env "HOST", "1.2.3.4" do + assert_deprecated do + options = parse_arguments + assert_equal "1.2.3.4", options[:Host] + end + end + end + + def test_environment_with_binding + switch_env "BINDING", "1.2.3.4" do options = parse_arguments assert_equal "1.2.3.4", options[:Host] end @@ -134,10 +143,22 @@ class Rails::Command::ServerCommandTest < ActiveSupport::TestCase options = parse_arguments(args) assert_equal true, options[:log_stdout] + args = ["-e", "development", "-d"] + options = parse_arguments(args) + assert_equal false, options[:log_stdout] + args = ["-e", "production"] options = parse_arguments(args) assert_equal false, options[:log_stdout] + args = ["-e", "development", "--no-log-to-stdout"] + options = parse_arguments(args) + assert_equal false, options[:log_stdout] + + args = ["-e", "production", "--log-to-stdout"] + options = parse_arguments(args) + assert_equal true, options[:log_stdout] + with_rack_env "development" do args = [] options = parse_arguments(args) @@ -196,7 +217,7 @@ class Rails::Command::ServerCommandTest < ActiveSupport::TestCase assert_equal 3000, options[:Port] end - switch_env "HOST", "1.2.3.4" do + switch_env "BINDING", "1.2.3.4" do args = ["-b", "127.0.0.1"] options = parse_arguments(args) assert_equal "127.0.0.1", options[:Host] @@ -215,6 +236,11 @@ class Rails::Command::ServerCommandTest < ActiveSupport::TestCase server_options = parse_arguments(["--port=3001"]) assert_equal [:Port], server_options[:user_supplied_options] + + switch_env "BINDING", "1.2.3.4" do + server_options = parse_arguments + assert_equal [:Host], server_options[:user_supplied_options] + end end def test_default_options @@ -231,10 +257,9 @@ class Rails::Command::ServerCommandTest < ActiveSupport::TestCase args = %w(-p 4567 -b 127.0.0.1 -c dummy_config.ru -d -e test -P tmp/server.pid -C) ARGV.replace args - options = parse_arguments(args) - expected = "bin/rails server -p 4567 -b 127.0.0.1 -c dummy_config.ru -d -e test -P tmp/server.pid -C --restart" + expected = "bin/rails server -p 4567 -b 127.0.0.1 -c dummy_config.ru -d -e test -P tmp/server.pid -C --restart" - assert_equal expected, options[:restart_cmd] + assert_equal expected, parse_arguments(args)[:restart_cmd] ensure ARGV.replace original_args end diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb index f421207025..a54a6dbc28 100644 --- a/railties/test/generators/actions_test.rb +++ b/railties/test/generators/actions_test.rb @@ -403,7 +403,7 @@ class ActionsTest < Rails::Generators::TestCase content.gsub!(/^ \#.*\n/, "") content.gsub!(/^\n/, "") - File.open(route_path, "wb") { |file| file.write(content) } + File.write(route_path, content) routes = <<-F Rails.application.routes.draw do diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 1d2e0fd354..b0f958091c 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -296,6 +296,51 @@ class AppGeneratorTest < Rails::Generators::TestCase end end + def test_app_update_does_not_generate_yarn_contents_when_bin_yarn_is_not_used + app_root = File.join(destination_root, "myapp") + run_generator [app_root, "--skip-yarn"] + + stub_rails_application(app_root) do + generator = Rails::Generators::AppGenerator.new ["rails"], { update: true, skip_yarn: true }, { destination_root: app_root, shell: @shell } + generator.send(:app_const) + quietly { generator.send(:update_bin_files) } + + assert_no_file "#{app_root}/bin/yarn" + + assert_file "#{app_root}/bin/setup" do |content| + assert_no_match(/system\('bin\/yarn'\)/, content) + end + + assert_file "#{app_root}/bin/update" do |content| + assert_no_match(/system\('bin\/yarn'\)/, content) + end + end + end + + def test_app_update_does_not_generate_assets_initializer_when_skip_sprockets_is_given + app_root = File.join(destination_root, "myapp") + run_generator [app_root, "--skip-sprockets"] + + stub_rails_application(app_root) do + generator = Rails::Generators::AppGenerator.new ["rails"], { update: true, skip_sprockets: true }, { destination_root: app_root, shell: @shell } + generator.send(:app_const) + quietly { generator.send(:update_config_files) } + + assert_no_file "#{app_root}/config/initializers/assets.rb" + end + end + + def test_app_update_does_not_generate_spring_contents_when_skip_spring_is_given + app_root = File.join(destination_root, "myapp") + run_generator [app_root, "--skip-spring"] + + FileUtils.cd(app_root) do + quietly { system("bin/rails app:update") } + end + + assert_no_file "#{app_root}/config/spring.rb" + end + def test_app_update_does_not_generate_action_cable_contents_when_skip_action_cable_is_given app_root = File.join(destination_root, "myapp") run_generator [app_root, "--skip-action-cable"] @@ -310,18 +355,28 @@ class AppGeneratorTest < Rails::Generators::TestCase end end - def test_active_storage_mini_magick_gem + def test_app_update_does_not_generate_bootsnap_contents_when_skip_bootsnap_is_given + app_root = File.join(destination_root, "myapp") + run_generator [app_root, "--skip-bootsnap"] + + FileUtils.cd(app_root) do + quietly { system("bin/rails app:update") } + end + + assert_file "#{app_root}/config/boot.rb" do |content| + assert_no_match(/require 'bootsnap\/setup'/, content) + end + end + + def test_gem_for_active_storage run_generator - assert_file "Gemfile", /^# gem 'mini_magick'/ + assert_file "Gemfile", /^# gem 'image_processing'/ end - def test_mini_magick_gem_when_skip_active_storage_is_given - app_root = File.join(destination_root, "myapp") - run_generator [app_root, "--skip-active-storage"] + def test_gem_for_active_storage_when_skip_active_storage_is_given + run_generator [destination_root, "--skip-active-storage"] - assert_file "#{app_root}/Gemfile" do |content| - assert_no_match(/gem 'mini_magick'/, content) - end + assert_no_gem "image_processing" end def test_app_update_does_not_generate_active_storage_contents_when_skip_active_storage_is_given @@ -383,6 +438,30 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "config/application.rb", /\s+config\.load_defaults 5\.1/ end + def test_app_update_does_not_change_app_name_when_app_name_is_hyphenated_name + app_root = File.join(destination_root, "hyphenated-app") + run_generator [app_root, "-d", "postgresql"] + + assert_file "#{app_root}/config/database.yml" do |content| + assert_match(/hyphenated_app_development/, content) + assert_no_match(/hyphenated-app_development/, content) + end + + assert_file "#{app_root}/config/cable.yml" do |content| + assert_match(/hyphenated_app/, content) + assert_no_match(/hyphenated-app/, content) + end + + FileUtils.cd(app_root) do + quietly { system("bin/rails app:update") } + end + + assert_file "#{app_root}/config/cable.yml" do |content| + assert_match(/hyphenated_app/, content) + assert_no_match(/hyphenated-app/, content) + end + end + def test_application_names_are_not_singularized run_generator [File.join(destination_root, "hats")] assert_file "hats/config/environment.rb", /Rails\.application\.initialize!/ @@ -408,13 +487,13 @@ class AppGeneratorTest < Rails::Generators::TestCase end end - def test_config_another_database + def test_config_mysql_database run_generator([destination_root, "-d", "mysql"]) assert_file "config/database.yml", /mysql/ if defined?(JRUBY_VERSION) assert_gem "activerecord-jdbcmysql-adapter" else - assert_gem "mysql2", "'~> 0.4.4'" + assert_gem "mysql2", "'>= 0.4.4', '< 0.6.0'" end end @@ -474,9 +553,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_generator_if_skip_puma_is_given run_generator [destination_root, "--skip-puma"] assert_no_file "config/puma.rb" - assert_file "Gemfile" do |content| - assert_no_match(/puma/, content) - end + assert_no_gem "puma" end def test_generator_has_assets_gems @@ -496,22 +573,18 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file "config/application.rb", /#\s+require\s+["']rails\/test_unit\/railtie["']/ - assert_file "Gemfile" do |content| - assert_no_match(/capybara/, content) - assert_no_match(/selenium-webdriver/, content) - assert_no_match(/chromedriver-helper/, content) - end + assert_no_gem "capybara" + assert_no_gem "selenium-webdriver" + assert_no_gem "chromedriver-helper" assert_no_directory("test") end def test_generator_if_skip_system_test_is_given run_generator [destination_root, "--skip-system-test"] - assert_file "Gemfile" do |content| - assert_no_match(/capybara/, content) - assert_no_match(/selenium-webdriver/, content) - assert_no_match(/chromedriver-helper/, content) - end + assert_no_gem "capybara" + assert_no_gem "selenium-webdriver" + assert_no_gem "chromedriver-helper" assert_directory("test") @@ -557,10 +630,8 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_no_match(/javascript_include_tag\s+'application' \%>/, contents) end - assert_file "Gemfile" do |content| - assert_no_match(/coffee-rails/, content) - assert_no_match(/uglifier/, content) - end + assert_no_gem "coffee-rails" + assert_no_gem "uglifier" assert_file "config/environments/production.rb" do |content| assert_no_match(/config\.assets\.js_compressor = :uglifier/, content) @@ -584,9 +655,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_inclusion_of_a_debugger run_generator if defined?(JRUBY_VERSION) || RUBY_ENGINE == "rbx" - assert_file "Gemfile" do |content| - assert_no_match(/byebug/, content) - end + assert_no_gem "byebug" else assert_gem "byebug" end @@ -737,9 +806,7 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_called_with(Process, :respond_to?, [[:fork], [:fork]], returns: false) do run_generator - assert_file "Gemfile" do |content| - assert_no_match(/spring/, content) - end + assert_no_gem "spring" end end @@ -747,17 +814,13 @@ class AppGeneratorTest < Rails::Generators::TestCase run_generator [destination_root, "--skip-spring"] assert_no_file "config/spring.rb" - assert_file "Gemfile" do |content| - assert_no_match(/spring/, content) - end + assert_no_gem "spring" end def test_spring_with_dev_option run_generator [destination_root, "--dev"] - assert_file "Gemfile" do |content| - assert_no_match(/spring/, content) - end + assert_no_gem "spring" end def test_webpack_option @@ -802,9 +865,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_generator_if_skip_turbolinks_is_given run_generator [destination_root, "--skip-turbolinks"] - assert_file "Gemfile" do |content| - assert_no_match(/turbolinks/, content) - end + assert_no_gem "turbolinks" assert_file "app/views/layouts/application.html.erb" do |content| assert_no_match(/data-turbolinks-track/, content) end @@ -816,18 +877,23 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_bootsnap run_generator - assert_gem "bootsnap" - assert_file "config/boot.rb" do |content| - assert_match(/require 'bootsnap\/setup'/, content) + unless defined?(JRUBY_VERSION) + assert_gem "bootsnap" + assert_file "config/boot.rb" do |content| + assert_match(/require 'bootsnap\/setup'/, content) + end + else + assert_no_gem "bootsnap" + assert_file "config/boot.rb" do |content| + assert_no_match(/require 'bootsnap\/setup'/, content) + end end end def test_skip_bootsnap run_generator [destination_root, "--skip-bootsnap"] - assert_file "Gemfile" do |content| - assert_no_match(/bootsnap/, content) - end + assert_no_gem "bootsnap" assert_file "config/boot.rb" do |content| assert_no_match(/require 'bootsnap\/setup'/, content) end @@ -836,9 +902,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_bootsnap_with_dev_option run_generator [destination_root, "--dev"] - assert_file "Gemfile" do |content| - assert_no_match(/bootsnap/, content) - end + assert_no_gem "bootsnap" assert_file "config/boot.rb" do |content| assert_no_match(/require 'bootsnap\/setup'/, content) end @@ -851,7 +915,13 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_match(/ruby '#{RUBY_VERSION}'/, content) end assert_file ".ruby-version" do |content| - assert_match(/#{RUBY_VERSION}/, content) + if ENV["RBENV_VERSION"] + assert_match(/#{ENV["RBENV_VERSION"]}/, content) + elsif ENV["rvm_ruby_string"] + assert_match(/#{ENV["rvm_ruby_string"]}/, content) + else + assert_match(/#{RUBY_ENGINE}-#{RUBY_ENGINE_VERSION}/, content) + end end end @@ -937,8 +1007,17 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_system_tests_directory_generated run_generator - assert_file("test/system/.keep") assert_directory("test/system") + assert_file("test/system/.keep") + end + + unless Gem.win_platform? + def test_master_key_is_only_readable_by_the_owner + run_generator + + stat = File.stat("config/master.key") + assert_equal "100600", sprintf("%o", stat.mode) + end end private @@ -961,6 +1040,12 @@ class AppGeneratorTest < Rails::Generators::TestCase end end + def assert_no_gem(gem) + assert_file "Gemfile" do |content| + assert_no_match(gem, content) + end + end + def assert_listen_related_configuration assert_gem "listen" assert_gem "spring-watcher-listen" @@ -971,9 +1056,7 @@ class AppGeneratorTest < Rails::Generators::TestCase end def assert_no_listen_related_configuration - assert_file "Gemfile" do |content| - assert_no_match(/listen/, content) - end + assert_no_gem "listen" assert_file "config/environments/development.rb" do |content| assert_match(/^\s*# config\.file_watcher = ActiveSupport::EventedFileUpdateChecker/, content) diff --git a/railties/test/generators/channel_generator_test.rb b/railties/test/generators/channel_generator_test.rb index e238197eba..e543cc11b8 100644 --- a/railties/test/generators/channel_generator_test.rb +++ b/railties/test/generators/channel_generator_test.rb @@ -76,4 +76,14 @@ class ChannelGeneratorTest < Rails::Generators::TestCase assert_file "app/channels/application_cable/connection.rb" assert_file "app/assets/javascripts/cable.js" end + + def test_channel_suffix_is_not_duplicated + run_generator ["chat_channel"] + + assert_no_file "app/channels/chat_channel_channel.rb" + assert_file "app/channels/chat_channel.rb" + + assert_no_file "app/assets/javascripts/channels/chat_channel.js" + assert_file "app/assets/javascripts/channels/chat.js" + end end diff --git a/railties/test/generators/controller_generator_test.rb b/railties/test/generators/controller_generator_test.rb index 91e4a86775..021004c9b8 100644 --- a/railties/test/generators/controller_generator_test.rb +++ b/railties/test/generators/controller_generator_test.rb @@ -116,4 +116,26 @@ class ControllerGeneratorTest < Rails::Generators::TestCase assert_no_match(/namespace :admin/, routes) end end + + def test_controller_suffix_is_not_duplicated + run_generator ["account_controller"] + + assert_no_file "app/controllers/account_controller_controller.rb" + assert_file "app/controllers/account_controller.rb" + + assert_no_file "app/views/account_controller/" + assert_file "app/views/account/" + + assert_no_file "test/controllers/account_controller_controller_test.rb" + assert_file "test/controllers/account_controller_test.rb" + + assert_no_file "app/helpers/account_controller_helper.rb" + assert_file "app/helpers/account_helper.rb" + + assert_no_file "app/assets/javascripts/account_controller.js" + assert_file "app/assets/javascripts/account.js" + + assert_no_file "app/assets/stylesheets/account_controller.css" + assert_file "app/assets/stylesheets/account.css" + end end diff --git a/railties/test/generators/job_generator_test.rb b/railties/test/generators/job_generator_test.rb index 13276fac65..234ba6dad7 100644 --- a/railties/test/generators/job_generator_test.rb +++ b/railties/test/generators/job_generator_test.rb @@ -35,4 +35,14 @@ class JobGeneratorTest < Rails::Generators::TestCase assert_match(/class ApplicationJob < ActiveJob::Base/, job) end end + + def test_job_suffix_is_not_duplicated + run_generator ["notifier_job"] + + assert_no_file "app/jobs/notifier_job_job.rb" + assert_file "app/jobs/notifier_job.rb" + + assert_no_file "test/jobs/notifier_job_job_test.rb" + assert_file "test/jobs/notifier_job_test.rb" + end end diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb index 29426cd99f..3e631f6021 100644 --- a/railties/test/generators/scaffold_generator_test.rb +++ b/railties/test/generators/scaffold_generator_test.rb @@ -347,7 +347,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase content = File.read(route_path).gsub(/\.routes\.draw do/) do |match| "#{match} |map|" end - File.open(route_path, "wb") { |file| file.write(content) } + File.write(route_path, content) run_generator ["product_line"], behavior: :revoke @@ -364,7 +364,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase content.gsub!(/^ \#.*\n/, "") content.gsub!(/^\n/, "") - File.open(route_path, "wb") { |file| file.write(content) } + File.write(route_path, content) assert_file "config/routes.rb", /\.routes\.draw do\n resources :product_lines\nend\n\z/ run_generator ["product_line"], behavior: :revoke diff --git a/railties/test/generators/test_runner_in_engine_test.rb b/railties/test/generators/test_runner_in_engine_test.rb index 0e15b5e388..bd102a32b5 100644 --- a/railties/test/generators/test_runner_in_engine_test.rb +++ b/railties/test/generators/test_runner_in_engine_test.rb @@ -19,7 +19,7 @@ class TestRunnerInEngineTest < ActiveSupport::TestCase create_test_file "post", pass: false output = run_test_command("test/post_test.rb") - expect = %r{Running:\n\nPostTest\nF\n\nFailure:\nPostTest#test_truth \[[^\]]+test/post_test\.rb:6\]:\nwups!\n\nbin/rails test test/post_test\.rb:4} + expect = %r{Running:\n\nPostTest\nF\n\nFailure:\nPostTest#test_truth \[[^\]]+test/post_test\.rb:6\]:\nwups!\n\nrails test test/post_test\.rb:4} assert_match expect, output end diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index 9f1f2a2289..f98c1f78f7 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -33,7 +33,7 @@ class GeneratorsTest < Rails::Generators::TestCase def test_generator_suggestions name = :migrationz output = capture(:stdout) { Rails::Generators.invoke name } - assert_match "Maybe you meant 'migration'", output + assert_match 'Maybe you meant "migration"?', output end def test_generator_suggestions_except_en_locale @@ -43,18 +43,12 @@ class GeneratorsTest < Rails::Generators::TestCase I18n.default_locale = :ja name = :tas output = capture(:stdout) { Rails::Generators.invoke name } - assert_match "Maybe you meant 'task', 'job' or", output + assert_match 'Maybe you meant "task"?', output ensure I18n.available_locales = orig_available_locales I18n.default_locale = orig_default_locale end - def test_generator_multiple_suggestions - name = :tas - output = capture(:stdout) { Rails::Generators.invoke name } - assert_match "Maybe you meant 'task', 'job' or", output - end - def test_help_when_a_generator_with_required_arguments_is_invoked_without_arguments output = capture(:stdout) { Rails::Generators.invoke :model, [] } assert_match(/Description:/, output) diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index 0a4d2a9167..516c457e48 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -14,6 +14,7 @@ require "bundler/setup" unless defined?(Bundler) require "active_support" require "active_support/testing/autorun" require "active_support/testing/stream" +require "active_support/testing/method_call_assertions" require "active_support/test_case" RAILS_FRAMEWORK_ROOT = File.expand_path("../../..", __dir__) @@ -112,22 +113,57 @@ module TestHelpers end end - File.open("#{app_path}/config/database.yml", "w") do |f| - f.puts <<-YAML - default: &default - adapter: sqlite3 - pool: 5 - timeout: 5000 - development: - <<: *default - database: db/development.sqlite3 - test: - <<: *default - database: db/test.sqlite3 - production: - <<: *default - database: db/production.sqlite3 - YAML + if options[:multi_db] + File.open("#{app_path}/config/database.yml", "w") do |f| + f.puts <<-YAML + default: &default + adapter: sqlite3 + pool: 5 + timeout: 5000 + development: + primary: + <<: *default + database: db/development.sqlite3 + animals: + <<: *default + database: db/development_animals.sqlite3 + migrations_paths: db/animals_migrate + test: + primary: + <<: *default + database: db/test.sqlite3 + animals: + <<: *default + database: db/test_animals.sqlite3 + migrations_paths: db/animals_migrate + production: + primary: + <<: *default + database: db/production.sqlite3 + animals: + <<: *default + database: db/production_animals.sqlite3 + migrations_paths: db/animals_migrate + YAML + end + else + File.open("#{app_path}/config/database.yml", "w") do |f| + f.puts <<-YAML + default: &default + adapter: sqlite3 + pool: 5 + timeout: 5000 + development: + <<: *default + database: db/development.sqlite3 + test: + <<: *default + database: db/test.sqlite3 + production: + <<: *default + database: db/production.sqlite3 + YAML + end end add_to_config <<-RUBY @@ -395,6 +431,7 @@ class ActiveSupport::TestCase include TestHelpers::Rack include TestHelpers::Generation include ActiveSupport::Testing::Stream + include ActiveSupport::Testing::MethodCallAssertions def frozen_error_class Object.const_defined?(:FrozenError) ? FrozenError : RuntimeError diff --git a/railties/test/rack_logger_test.rb b/railties/test/rack_logger_test.rb index e47f30d5b6..6e8f333e1d 100644 --- a/railties/test/rack_logger_test.rb +++ b/railties/test/rack_logger_test.rb @@ -14,14 +14,21 @@ module Rails attr_reader :logger - def initialize(logger = NULL, taggers = nil, &block) - super(->(_) { block.call; [200, {}, []] }, taggers) + def initialize(logger = NULL, app: nil, taggers: nil, &block) + app ||= ->(_) { block.call; [200, {}, []] } + super(app, taggers) @logger = logger end def development?; false; end end + class TestApp < Struct.new(:response) + def call(_env) + response + end + end + Subscriber = Struct.new(:starts, :finishes) do def initialize(starts = [], finishes = []) super @@ -72,6 +79,17 @@ module Rails end end end + + def test_logger_does_not_mutate_app_return + response = [].freeze + app = TestApp.new(response) + logger = TestLogger.new(app: app) + assert_no_changes("response") do + assert_nothing_raised do + logger.call("REQUEST_METHOD" => "GET") + end + end + end end end end diff --git a/railties/test/rails_info_test.rb b/railties/test/rails_info_test.rb index 43b60b9144..50522c1be6 100644 --- a/railties/test/rails_info_test.rb +++ b/railties/test/rails_info_test.rb @@ -9,7 +9,7 @@ class InfoTest < ActiveSupport::TestCase property("Bogus") { raise } end end - assert !property_defined?("Bogus") + assert_not property_defined?("Bogus") end def test_property_with_string diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb index a59c63f343..4ac8f8d741 100644 --- a/railties/test/railties/engine_test.rb +++ b/railties/test/railties/engine_test.rb @@ -226,7 +226,7 @@ module RailtiesTest require "rdoc/task" require "rake/testtask" Rails.application.load_tasks - assert !Rake::Task.task_defined?("bukkits:install:migrations") + assert_not Rake::Task.task_defined?("bukkits:install:migrations") end test "puts its lib directory on load path" do @@ -570,7 +570,6 @@ YAML get("/arunagw") assert_equal "arunagw", last_response.body - end test "it provides routes as default endpoint" do @@ -745,7 +744,7 @@ YAML assert_equal "bukkits", Bukkits::Engine.engine_name assert_equal Bukkits.railtie_namespace, Bukkits::Engine assert ::Bukkits::MyMailer.method_defined?(:foo_url) - assert !::Bukkits::MyMailer.method_defined?(:bar_url) + assert_not ::Bukkits::MyMailer.method_defined?(:bar_url) get("/bukkits/from_app") assert_equal "false", last_response.body diff --git a/railties/test/railties/railtie_test.rb b/railties/test/railties/railtie_test.rb index 359ab0fdae..7c3d1e3759 100644 --- a/railties/test/railties/railtie_test.rb +++ b/railties/test/railties/railtie_test.rb @@ -65,7 +65,7 @@ module RailtiesTest test "railtie can add to_prepare callbacks" do $to_prepare = false class Foo < Rails::Railtie ; config.to_prepare { $to_prepare = true } ; end - assert !$to_prepare + assert_not $to_prepare require "#{app_path}/config/environment" require "rack/test" extend Rack::Test::Methods @@ -91,7 +91,7 @@ module RailtiesTest test "railtie can add after_initialize callbacks" do $after_initialize = false class Foo < Rails::Railtie ; config.after_initialize { $after_initialize = true } ; end - assert !$after_initialize + assert_not $after_initialize require "#{app_path}/config/environment" assert $after_initialize end @@ -107,7 +107,7 @@ module RailtiesTest require "#{app_path}/config/environment" - assert !$ran_block + assert_not $ran_block require "rake" require "rake/testtask" require "rdoc/task" @@ -151,7 +151,7 @@ module RailtiesTest require "#{app_path}/config/environment" - assert !$ran_block + assert_not $ran_block Rails.application.load_generators assert $ran_block end @@ -167,7 +167,7 @@ module RailtiesTest require "#{app_path}/config/environment" - assert !$ran_block + assert_not $ran_block Rails.application.load_console assert $ran_block end @@ -183,7 +183,7 @@ module RailtiesTest require "#{app_path}/config/environment" - assert !$ran_block + assert_not $ran_block Rails.application.load_runner assert $ran_block end @@ -197,7 +197,7 @@ module RailtiesTest end end - assert !$ran_block + assert_not $ran_block require "#{app_path}/config/environment" assert $ran_block end diff --git a/railties/test/test_unit/reporter_test.rb b/railties/test/test_unit/reporter_test.rb index 91cb47779b..81b7ab19a1 100644 --- a/railties/test/test_unit/reporter_test.rb +++ b/railties/test/test_unit/reporter_test.rb @@ -18,7 +18,7 @@ class TestUnitReporterTest < ActiveSupport::TestCase @reporter.record(failed_test) @reporter.report - assert_match %r{^bin/rails test .*test/test_unit/reporter_test\.rb:\d+$}, @output.string + assert_match %r{^rails test .*test/test_unit/reporter_test\.rb:\d+$}, @output.string assert_rerun_snippet_count 1 end @@ -64,7 +64,7 @@ class TestUnitReporterTest < ActiveSupport::TestCase @reporter.record(failed_test) @reporter.report - expect = %r{\AF\n\nFailure:\nTestUnitReporterTest::ExampleTest#woot \[[^\]]+\]:\nboo\n\nbin/rails test test/test_unit/reporter_test\.rb:\d+\n\n\z} + expect = %r{\AF\n\nFailure:\nTestUnitReporterTest::ExampleTest#woot \[[^\]]+\]:\nboo\n\nrails test test/test_unit/reporter_test\.rb:\d+\n\n\z} assert_match expect, @output.string end @@ -72,7 +72,7 @@ class TestUnitReporterTest < ActiveSupport::TestCase @reporter.record(errored_test) @reporter.report - expect = %r{\AE\n\nError:\nTestUnitReporterTest::ExampleTest#woot:\nArgumentError: wups\n \n\nbin/rails test .*test/test_unit/reporter_test\.rb:\d+\n\n\z} + expect = %r{\AE\n\nError:\nTestUnitReporterTest::ExampleTest#woot:\nArgumentError: wups\n \n\nrails test .*test/test_unit/reporter_test\.rb:\d+\n\n\z} assert_match expect, @output.string end @@ -81,7 +81,7 @@ class TestUnitReporterTest < ActiveSupport::TestCase verbose.record(skipped_test) verbose.report - expect = %r{\ATestUnitReporterTest::ExampleTest#woot = 10\.00 s = S\n\n\nSkipped:\nTestUnitReporterTest::ExampleTest#woot \[[^\]]+\]:\nskipchurches, misstemples\n\nbin/rails test test/test_unit/reporter_test\.rb:\d+\n\n\z} + expect = %r{\ATestUnitReporterTest::ExampleTest#woot = 10\.00 s = S\n\n\nSkipped:\nTestUnitReporterTest::ExampleTest#woot \[[^\]]+\]:\nskipchurches, misstemples\n\nrails test test/test_unit/reporter_test\.rb:\d+\n\n\z} assert_match expect, @output.string end @@ -159,7 +159,7 @@ class TestUnitReporterTest < ActiveSupport::TestCase private def assert_rerun_snippet_count(snippet_count) - assert_equal snippet_count, @output.string.scan(%r{^bin/rails test }).size + assert_equal snippet_count, @output.string.scan(%r{^rails test }).size end def failed_test |