diff options
Diffstat (limited to 'railties/test')
26 files changed, 855 insertions, 277 deletions
diff --git a/railties/test/app_rails_loader_test.rb b/railties/test/app_loader_test.rb index d4885447e6..5946c8fd4c 100644 --- a/railties/test/app_rails_loader_test.rb +++ b/railties/test/app_loader_test.rb @@ -1,11 +1,11 @@ require 'tmpdir' require 'abstract_unit' -require 'rails/app_rails_loader' +require 'rails/app_loader' -class AppRailsLoaderTest < ActiveSupport::TestCase +class AppLoaderTest < ActiveSupport::TestCase def loader @loader ||= Class.new do - extend Rails::AppRailsLoader + extend Rails::AppLoader def self.exec_arguments @exec_arguments @@ -23,7 +23,7 @@ class AppRailsLoaderTest < ActiveSupport::TestCase end def expects_exec(exe) - assert_equal [Rails::AppRailsLoader::RUBY, exe], loader.exec_arguments + assert_equal [Rails::AppLoader::RUBY, exe], loader.exec_arguments end setup do @@ -38,20 +38,20 @@ class AppRailsLoaderTest < 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_rails + assert !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_rails + assert !loader.exec_app end ['APP_PATH', 'ENGINE_PATH'].each do |keyword| test "is in a Rails application if #{exe} exists and contains #{keyword}" do write exe, keyword - loader.exec_app_rails + loader.exec_app expects_exec exe end @@ -59,7 +59,7 @@ class AppRailsLoaderTest < ActiveSupport::TestCase test "is not in a Rails application if #{exe} exists but doesn't contain #{keyword}" do write exe - assert !loader.exec_app_rails + assert !loader.exec_app end test "is in a Rails application if parent directory has #{exe} containing #{keyword} and chdirs to the root directory" do @@ -68,7 +68,7 @@ class AppRailsLoaderTest < ActiveSupport::TestCase Dir.chdir('foo/bar') - loader.exec_app_rails + loader.exec_app expects_exec exe diff --git a/railties/test/application/configuration/custom_test.rb b/railties/test/application/configuration/custom_test.rb index f5c99d030e..28b3b2f2d6 100644 --- a/railties/test/application/configuration/custom_test.rb +++ b/railties/test/application/configuration/custom_test.rb @@ -1,5 +1,4 @@ require 'isolation/abstract_unit' -require 'env_helpers' module ApplicationTests module ConfigurationTests diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 38516a1c1a..f677a7c42a 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -745,6 +745,19 @@ module ApplicationTests assert_equal [::MyMailObserver, ::MyOtherMailObserver], ::Mail.send(:class_variable_get, "@@delivery_notification_observers") end + test "allows setting the queue name for the ActionMailer::DeliveryJob" do + add_to_config <<-RUBY + config.action_mailer.deliver_later_queue_name = 'test_default' + RUBY + + require "#{app_path}/config/environment" + require "mail" + + _ = ActionMailer::Base + + assert_equal 'test_default', ActionMailer::Base.send(:class_variable_get, "@@deliver_later_queue_name") + end + test "valid timezone is setup correctly" do add_to_config <<-RUBY config.root = "#{app_path}" diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb index 31bc003dcb..7bf123d12b 100644 --- a/railties/test/application/console_test.rb +++ b/railties/test/application/console_test.rb @@ -29,6 +29,18 @@ class ConsoleTest < ActiveSupport::TestCase assert_instance_of ActionDispatch::Integration::Session, console_session end + def test_app_can_access_path_helper_method + app_file 'config/routes.rb', <<-RUBY + Rails.application.routes.draw do + get 'foo', to: 'foo#index' + end + RUBY + + load_environment + console_session = irb_context.app + assert_equal '/foo', console_session.foo_path + end + def test_new_session_should_return_integration_session load_environment session = irb_context.new_session diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb index 78ada58ec8..84cc6e120b 100644 --- a/railties/test/application/generators_test.rb +++ b/railties/test/application/generators_test.rb @@ -125,5 +125,40 @@ module ApplicationTests assert_equal expected, c.generators.options end end + + test "api only generators hide assets, helper, js and css namespaces and set api option" do + add_to_config <<-RUBY + config.api_only = true + RUBY + + # Initialize the application + require "#{app_path}/config/environment" + Rails.application.load_generators + + assert Rails::Generators.hidden_namespaces.include?("assets") + assert Rails::Generators.hidden_namespaces.include?("helper") + assert Rails::Generators.hidden_namespaces.include?("js") + assert Rails::Generators.hidden_namespaces.include?("css") + assert Rails::Generators.options[:rails][:api] + assert_equal false, Rails::Generators.options[:rails][:assets] + assert_equal false, Rails::Generators.options[:rails][:helper] + assert_nil Rails::Generators.options[:rails][:template_engine] + end + + test "api only generators allow overriding generator options" do + add_to_config <<-RUBY + config.generators.helper = true + config.api_only = true + config.generators.template_engine = :my_template + RUBY + + # Initialize the application + require "#{app_path}/config/environment" + Rails.application.load_generators + + assert Rails::Generators.options[:rails][:api] + assert Rails::Generators.options[:rails][:helper] + assert_equal :my_template, Rails::Generators.options[:rails][:template_engine] + end end end diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index 97b51911d9..af98e08d0e 100644 --- a/railties/test/application/initializers/frameworks_test.rb +++ b/railties/test/application/initializers/frameworks_test.rb @@ -129,6 +129,35 @@ module ApplicationTests assert_equal "false", last_response.body end + test "action_controller api executes using all the middleware stack" do + add_to_config "config.api_only = true" + + app_file "app/controllers/application_controller.rb", <<-RUBY + class ApplicationController < ActionController::API + end + RUBY + + app_file "app/controllers/omg_controller.rb", <<-RUBY + class OmgController < ApplicationController + def show + render json: { omg: 'omg' } + end + end + RUBY + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + get "/:controller(/:action)" + end + RUBY + + require 'rack/test' + extend Rack::Test::Methods + + get 'omg/show' + assert_equal '{"omg":"omg"}', last_response.body + end + # AD test "action_dispatch extensions are applied to ActionDispatch" do add_to_config "config.action_dispatch.tld_length = 2" diff --git a/railties/test/application/middleware/session_test.rb b/railties/test/application/middleware/session_test.rb index a8dc79d10a..25eadfc387 100644 --- a/railties/test/application/middleware/session_test.rb +++ b/railties/test/application/middleware/session_test.rb @@ -35,7 +35,7 @@ module ApplicationTests flash[:notice] = "notice" end - render nothing: true + head :ok end end @@ -60,7 +60,7 @@ module ApplicationTests def write_session session[:foo] = 1 - render nothing: true + head :ok end def read_session @@ -101,7 +101,7 @@ module ApplicationTests def write_cookie cookies[:foo] = '1' - render nothing: true + head :ok end def read_cookie @@ -139,7 +139,7 @@ module ApplicationTests class FooController < ActionController::Base def write_session session[:foo] = 1 - render nothing: true + head :ok end def read_session @@ -184,7 +184,7 @@ module ApplicationTests class FooController < ActionController::Base def write_session session[:foo] = 1 - render nothing: true + head :ok end def read_session @@ -234,12 +234,12 @@ module ApplicationTests def write_raw_session # {"session_id"=>"1965d95720fffc123941bdfb7d2e6870", "foo"=>1} cookies[:_myapp_session] = "BAh7B0kiD3Nlc3Npb25faWQGOgZFRkkiJTE5NjVkOTU3MjBmZmZjMTIzOTQxYmRmYjdkMmU2ODcwBjsAVEkiCGZvbwY7AEZpBg==--315fb9931921a87ae7421aec96382f0294119749" - render nothing: true + head :ok end def write_session session[:foo] = session[:foo] + 1 - render nothing: true + head :ok end def read_session @@ -293,12 +293,12 @@ module ApplicationTests def write_raw_session # {"session_id"=>"1965d95720fffc123941bdfb7d2e6870", "foo"=>1} cookies[:_myapp_session] = "BAh7B0kiD3Nlc3Npb25faWQGOgZFRkkiJTE5NjVkOTU3MjBmZmZjMTIzOTQxYmRmYjdkMmU2ODcwBjsAVEkiCGZvbwY7AEZpBg==--315fb9931921a87ae7421aec96382f0294119749" - render nothing: true + head :ok end def write_session session[:foo] = session[:foo] + 1 - render nothing: true + head :ok end def read_session diff --git a/railties/test/application/middleware/static_test.rb b/railties/test/application/middleware/static_test.rb index 121c5d3321..1a46cd3568 100644 --- a/railties/test/application/middleware/static_test.rb +++ b/railties/test/application/middleware/static_test.rb @@ -26,5 +26,26 @@ module ApplicationTests assert_not last_response.headers.has_key?('Cache-Control'), "Cache-Control should not be set" end + + test "static_index defaults to 'index'" do + app_file "public/index.html", "/index.html" + + require "#{app_path}/config/environment" + + get '/' + + assert_equal "/index.html\n", last_response.body + end + + test "static_index configurable" do + app_file "public/other-index.html", "/other-index.html" + add_to_config "config.static_index = 'other-index'" + + require "#{app_path}/config/environment" + + get '/' + + assert_equal "/other-index.html\n", last_response.body + end end end diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb index 04bd19784a..ce92ebbf66 100644 --- a/railties/test/application/middleware_test.rb +++ b/railties/test/application/middleware_test.rb @@ -50,6 +50,33 @@ module ApplicationTests ], middleware end + test "api middleware stack" do + add_to_config "config.api_only = true" + + boot! + + assert_equal [ + "Rack::Sendfile", + "ActionDispatch::Static", + "Rack::Lock", + "ActiveSupport::Cache::Strategy::LocalCache", + "Rack::Runtime", + "ActionDispatch::RequestId", + "Rails::Rack::Logger", # must come after Rack::MethodOverride to properly log overridden methods + "ActionDispatch::ShowExceptions", + "ActionDispatch::DebugExceptions", + "ActionDispatch::RemoteIp", + "ActionDispatch::Reloader", + "ActionDispatch::Callbacks", + "ActiveRecord::ConnectionAdapters::ConnectionManagement", + "ActiveRecord::QueryCache", + "ActionDispatch::ParamsParser", + "Rack::Head", + "Rack::ConditionalGet", + "Rack::ETag" + ], middleware + end + test "Rack::Cache is not included by default" do boot! diff --git a/railties/test/application/multiple_applications_test.rb b/railties/test/application/multiple_applications_test.rb index cddc79cc85..f2770a9cb4 100644 --- a/railties/test/application/multiple_applications_test.rb +++ b/railties/test/application/multiple_applications_test.rb @@ -118,7 +118,7 @@ module ApplicationTests 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! + AppTemplate::Application.create { config.eager_load = false }.initialize! assert_equal 3, run_count, "There should have been three initializers that incremented the count" end diff --git a/railties/test/application/rake/framework_test.rb b/railties/test/application/rake/framework_test.rb new file mode 100644 index 0000000000..ec57af79f6 --- /dev/null +++ b/railties/test/application/rake/framework_test.rb @@ -0,0 +1,48 @@ +require "isolation/abstract_unit" +require "active_support/core_ext/string/strip" + +module ApplicationTests + module RakeTests + class FrameworkTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + boot_rails + FileUtils.rm_rf("#{app_path}/config/environments") + end + + def teardown + teardown_app + end + + def load_tasks + require 'rake' + require 'rdoc/task' + require 'rake/testtask' + + Rails.application.load_tasks + end + + test 'requiring the rake task should not define method .app_generator on Object' do + require "#{app_path}/config/environment" + + load_tasks + + assert_raise NameError do + Object.method(:app_generator) + end + end + + test 'requiring the rake task should not define method .invoke_from_app_generator on Object' do + require "#{app_path}/config/environment" + + load_tasks + + assert_raise NameError do + Object.method(:invoke_from_app_generator) + end + end + end + end +end diff --git a/railties/test/application/rake/restart_test.rb b/railties/test/application/rake/restart_test.rb index 35099913fb..4cae199e6b 100644 --- a/railties/test/application/rake/restart_test.rb +++ b/railties/test/application/rake/restart_test.rb @@ -13,12 +13,12 @@ module ApplicationTests def teardown teardown_app end - + test 'rake restart touches tmp/restart.txt' do Dir.chdir(app_path) do `rake restart` assert File.exist?("tmp/restart.txt") - + prev_mtime = File.mtime("tmp/restart.txt") sleep(1) `rake restart` @@ -26,6 +26,14 @@ module ApplicationTests assert_not_equal prev_mtime, curr_mtime end end + + test 'rake restart should work even if tmp folder does not exist' do + Dir.chdir(app_path) do + FileUtils.remove_dir('tmp') + `rake restart` + assert File.exist?('tmp/restart.txt') + end + end end end end diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb index de14f269df..4c1913f0cc 100644 --- a/railties/test/application/rake_test.rb +++ b/railties/test/application/rake_test.rb @@ -194,6 +194,25 @@ module ApplicationTests assert_no_match(/Errors running/, output) end + def test_api_scaffold_tests_pass_by_default + add_to_config <<-RUBY + config.api_only = true + RUBY + + app_file "app/controllers/application_controller.rb", <<-RUBY + class ApplicationController < ActionController::API + end + RUBY + + output = Dir.chdir(app_path) do + `rails generate scaffold user username:string password:string; + bundle exec rake db:migrate test` + end + + assert_match(/5 runs, 7 assertions, 0 failures, 0 errors/, output) + assert_no_match(/Errors running/, output) + end + def test_scaffold_with_references_columns_tests_pass_when_belongs_to_is_optional app_file "config/initializers/active_record_belongs_to_required_by_default.rb", "Rails.application.config.active_record.belongs_to_required_by_default = false" @@ -285,5 +304,12 @@ module ApplicationTests assert_match(/Hello, World!/, output) end + + def test_tmp_clear_should_work_if_folder_missing + FileUtils.remove_dir("#{app_path}/tmp") + errormsg = Dir.chdir(app_path) { `bundle exec rake tmp:clear` } + assert_predicate $?, :success? + assert_empty errormsg + end end end diff --git a/railties/test/application/test_runner_test.rb b/railties/test/application/test_runner_test.rb index c122b315c0..bbaab42a7f 100644 --- a/railties/test/application/test_runner_test.rb +++ b/railties/test/application/test_runner_test.rb @@ -1,9 +1,10 @@ require 'isolation/abstract_unit' require 'active_support/core_ext/string/strip' +require 'env_helpers' module ApplicationTests class TestRunnerTest < ActiveSupport::TestCase - include ActiveSupport::Testing::Isolation + include ActiveSupport::Testing::Isolation, EnvHelpers def setup build_app @@ -14,20 +15,6 @@ module ApplicationTests teardown_app end - def test_run_in_test_environment - app_file 'test/unit/env_test.rb', <<-RUBY - require 'test_helper' - - class EnvTest < ActiveSupport::TestCase - def test_env - puts "Current Environment: \#{Rails.env}" - end - end - RUBY - - assert_match "Current Environment: test", run_test_command('test/unit/env_test.rb') - end - def test_run_single_file create_test_file :models, 'foo' create_test_file :models, 'bar' @@ -187,7 +174,7 @@ module ApplicationTests end RUBY - run_test_command('-p rikka test/unit/chu_2_koi_test.rb').tap do |output| + run_test_command('-n /rikka/ test/unit/chu_2_koi_test.rb').tap do |output| assert_match "Rikka", output assert_no_match "Sanae", output end @@ -229,24 +216,128 @@ module ApplicationTests assert_match "development", run_test_command('test/unit/env_test.rb') end + def test_run_in_test_environment_by_default + create_env_test + + assert_match "Current Environment: test", run_test_command('test/unit/env_test.rb') + end + def test_run_different_environment - env = "development" - app_file 'test/unit/env_test.rb', <<-RUBY + create_env_test + + assert_match "Current Environment: development", + run_test_command("-e development test/unit/env_test.rb") + end + + def test_generated_scaffold_works_with_rails_test + create_scaffold + assert_match "0 failures, 0 errors, 0 skips", run_test_command('') + end + + def test_run_multiple_folders + create_test_file :models, 'account' + create_test_file :controllers, 'accounts_controller' + + run_test_command('test/models test/controllers').tap do |output| + assert_match 'AccountTest', output + assert_match 'AccountsControllerTest', output + assert_match '2 runs, 2 assertions, 0 failures, 0 errors, 0 skips', output + end + end + + def test_run_with_ruby_command + app_file 'test/models/post_test.rb', <<-RUBY require 'test_helper' - class EnvTest < ActiveSupport::TestCase - def test_env - puts Rails.env + class PostTest < ActiveSupport::TestCase + test 'declarative syntax works' do + puts 'PostTest' + assert true end end RUBY - assert_match env, run_test_command("-e #{env} test/unit/env_test.rb") + Dir.chdir(app_path) do + `ruby -Itest test/models/post_test.rb`.tap do |output| + assert_match 'PostTest', output + assert_no_match 'is already defined in', output + end + end end - def test_generated_scaffold_works_with_rails_test - create_scaffold - assert_match "0 failures, 0 errors, 0 skips", run_test_command('') + def test_mix_files_and_line_filters + create_test_file :models, 'account' + app_file 'test/models/post_test.rb', <<-RUBY + require 'test_helper' + + class PostTest < ActiveSupport::TestCase + def test_post + puts 'PostTest' + assert true + end + + def test_line_filter_does_not_run_this + assert true + end + end + RUBY + + run_test_command('test/models/account_test.rb test/models/post_test.rb:4').tap do |output| + assert_match 'AccountTest', output + assert_match 'PostTest', output + assert_match '2 runs, 2 assertions', output + end + end + + def test_multiple_line_filters + create_test_file :models, 'account' + create_test_file :models, 'post' + + run_test_command('test/models/account_test.rb:4 test/models/post_test.rb:4').tap do |output| + assert_match 'AccountTest', output + assert_match 'PostTest', output + end + end + + def test_line_filter_without_line_runs_all_tests + create_test_file :models, 'account' + + run_test_command('test/models/account_test.rb:').tap do |output| + assert_match 'AccountTest', output + end + end + + def test_shows_filtered_backtrace_by_default + create_backtrace_test + + assert_match 'Rails::BacktraceCleaner', run_test_command('test/unit/backtrace_test.rb') + end + + def test_backtrace_option + create_backtrace_test + + assert_match 'Minitest::BacktraceFilter', run_test_command('test/unit/backtrace_test.rb -b') + assert_match 'Minitest::BacktraceFilter', + run_test_command('test/unit/backtrace_test.rb --backtrace') + end + + def test_show_full_backtrace_using_backtrace_environment_variable + create_backtrace_test + + switch_env 'BACKTRACE', 'true' do + assert_match 'Minitest::BacktraceFilter', run_test_command('test/unit/backtrace_test.rb') + end + end + + def test_run_app_without_rails_loaded + # Simulate a real Rails app boot. + app_file 'config/boot.rb', <<-RUBY + ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) + + require 'bundler/setup' # Set up gems listed in the Gemfile. + RUBY + + assert_match '0 runs, 0 assertions', run_test_command('') end private @@ -284,6 +375,18 @@ module ApplicationTests RUBY end + def create_backtrace_test + app_file 'test/unit/backtrace_test.rb', <<-RUBY + require 'test_helper' + + class BacktraceTest < ActiveSupport::TestCase + def test_backtrace + puts Minitest.backtrace_filter + end + end + RUBY + end + def create_schema app_file 'db/schema.rb', '' end @@ -301,6 +404,18 @@ module ApplicationTests RUBY end + def create_env_test + app_file 'test/unit/env_test.rb', <<-RUBY + require 'test_helper' + + class EnvTest < ActiveSupport::TestCase + def test_env + puts "Current Environment: \#{Rails.env}" + end + end + RUBY + end + def create_scaffold script 'generate scaffold user name:string' Dir.chdir(app_path) { File.exist?('app/models/user.rb') } diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb index 61652e5052..0e997f4ba7 100644 --- a/railties/test/application/test_test.rb +++ b/railties/test/application/test_test.rb @@ -44,7 +44,7 @@ module ApplicationTests def test_index get '/posts' assert_response :success - assert_template "index" + assert_includes @response.body, 'Posts#index' end end RUBY @@ -64,8 +64,8 @@ module ApplicationTests RUBY output = run_test_file('unit/failing_test.rb', env: { "BACKTRACE" => "1" }) - assert_match %r{/app/test/unit/failing_test\.rb}, output - assert_match %r{/app/test/unit/failing_test\.rb:4}, output + assert_match %r{test/unit/failing_test\.rb}, output + assert_match %r{test/unit/failing_test\.rb:4}, output end test "ruby schema migrations" do diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb index c0b88089b3..4a4317c4f4 100644 --- a/railties/test/generators/actions_test.rb +++ b/railties/test/generators/actions_test.rb @@ -1,7 +1,7 @@ require 'generators/generators_test_helper' require 'rails/generators/rails/app/app_generator' require 'env_helpers' -require 'mocha/setup' # FIXME: stop using mocha +require 'minitest/mock' class ActionsTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -12,11 +12,13 @@ class ActionsTest < Rails::Generators::TestCase def setup Rails.application = TestApp::Application + @mock_generator = Minitest::Mock.new super end def teardown Rails.application = TestApp::Application.instance + @mock_generator.verify end def test_invoke_other_generator_with_shortcut @@ -140,13 +142,18 @@ class ActionsTest < Rails::Generators::TestCase end def test_git_with_symbol_should_run_command_using_git_scm - generator.expects(:run).once.with('git init') - action :git, :init + @mock_generator.expect(:call, nil, ['git init']) + generator.stub(:run, @mock_generator) do + action :git, :init + end end def test_git_with_hash_should_run_each_command_using_git_scm - generator.expects(:run).times(2) - action :git, rm: 'README', add: '.' + @mock_generator.expect(:call, nil, ["git rm README"]) + @mock_generator.expect(:call, nil, ["git add ."]) + generator.stub(:run, @mock_generator) do + action :git, rm: 'README', add: '.' + end end def test_vendor_should_write_data_to_file_in_vendor @@ -170,46 +177,60 @@ class ActionsTest < Rails::Generators::TestCase end def test_generate_should_run_script_generate_with_argument_and_options - generator.expects(:run_ruby_script).once.with('bin/rails generate model MyModel', verbose: false) - action :generate, 'model', 'MyModel' + @mock_generator.expect(:call, nil, ['bin/rails generate model MyModel', verbose: false]) + generator.stub(:run_ruby_script, @mock_generator) do + action :generate, 'model', 'MyModel' + end end def test_rake_should_run_rake_command_with_default_env - generator.expects(:run).once.with("rake log:clear RAILS_ENV=development", verbose: false) - with_rails_env nil do - action :rake, 'log:clear' + @mock_generator.expect(:call, nil, ["rake log:clear RAILS_ENV=development", verbose: false]) + generator.stub(:run, @mock_generator) do + with_rails_env nil do + action :rake, 'log:clear' + end end end def test_rake_with_env_option_should_run_rake_command_in_env - generator.expects(:run).once.with('rake log:clear RAILS_ENV=production', verbose: false) - action :rake, 'log:clear', env: 'production' + @mock_generator.expect(:call, nil, ['rake log:clear RAILS_ENV=production', verbose: false]) + generator.stub(:run, @mock_generator) do + action :rake, 'log:clear', env: 'production' + end end def test_rake_with_rails_env_variable_should_run_rake_command_in_env - generator.expects(:run).once.with('rake log:clear RAILS_ENV=production', verbose: false) - with_rails_env "production" do - action :rake, 'log:clear' + @mock_generator.expect(:call, nil, ['rake log:clear RAILS_ENV=production', verbose: false]) + generator.stub(:run, @mock_generator) do + with_rails_env "production" do + action :rake, 'log:clear' + end end end def test_env_option_should_win_over_rails_env_variable_when_running_rake - generator.expects(:run).once.with('rake log:clear RAILS_ENV=production', verbose: false) - with_rails_env "staging" do - action :rake, 'log:clear', env: 'production' + @mock_generator.expect(:call, nil, ['rake log:clear RAILS_ENV=production', verbose: false]) + generator.stub(:run, @mock_generator) do + with_rails_env "staging" do + action :rake, 'log:clear', env: 'production' + end end end def test_rake_with_sudo_option_should_run_rake_command_with_sudo - generator.expects(:run).once.with("sudo rake log:clear RAILS_ENV=development", verbose: false) - with_rails_env nil do - action :rake, 'log:clear', sudo: true + @mock_generator.expect(:call, nil, ["sudo rake log:clear RAILS_ENV=development", verbose: false]) + generator.stub(:run, @mock_generator) do + with_rails_env nil do + action :rake, 'log:clear', sudo: true + end end end def test_capify_should_run_the_capify_command - generator.expects(:run).once.with('capify .', verbose: false) - action :capify! + @mock_generator.expect(:call, nil, ['capify .', verbose: false]) + generator.stub(:run, @mock_generator) do + action :capify! + end end def test_route_should_add_data_to_the_routes_block_in_config_routes @@ -245,15 +266,19 @@ F def test_readme run_generator - Rails::Generators::AppGenerator.expects(:source_root).times(2).returns(destination_root) - assert_match "application up and running", action(:readme, "README.md") + 2.times { @mock_generator.expect(:call, destination_root,[]) } + Rails::Generators::AppGenerator.stub(:source_root, @mock_generator) do + assert_match "application up and running", action(:readme, "README.md") + end end def test_readme_with_quiet generator(default_arguments, quiet: true) run_generator - Rails::Generators::AppGenerator.expects(:source_root).times(2).returns(destination_root) - assert_no_match "application up and running", action(:readme, "README.md") + 2.times { @mock_generator.expect(:call, destination_root,[]) } + Rails::Generators::AppGenerator.stub(:source_root, @mock_generator) do + assert_no_match "application up and running", action(:readme, "README.md") + end end def test_log diff --git a/railties/test/generators/api_app_generator_test.rb b/railties/test/generators/api_app_generator_test.rb new file mode 100644 index 0000000000..9978ad0da1 --- /dev/null +++ b/railties/test/generators/api_app_generator_test.rb @@ -0,0 +1,96 @@ +require 'generators/generators_test_helper' +require 'rails/generators/rails/app/app_generator' + +class ApiAppGeneratorTest < Rails::Generators::TestCase + include GeneratorsTestHelper + tests Rails::Generators::AppGenerator + + arguments [destination_root, '--api'] + + def setup + Rails.application = TestApp::Application + super + + Kernel::silence_warnings do + Thor::Base.shell.send(:attr_accessor, :always_force) + @shell = Thor::Base.shell.new + @shell.send(:always_force=, true) + end + end + + def teardown + super + Rails.application = TestApp::Application.instance + end + + def test_skeleton_is_created + run_generator + + default_files.each { |path| assert_file path } + skipped_files.each { |path| assert_no_file path } + end + + def test_api_modified_files + run_generator + + assert_file "Gemfile" do |content| + assert_no_match(/gem 'coffee-rails'/, content) + assert_no_match(/gem 'jquery-rails'/, content) + assert_no_match(/gem 'sass-rails'/, content) + assert_no_match(/gem 'jbuilder'/, content) + assert_match(/gem 'active_model_serializers'/, content) + end + + assert_file "config/application.rb" do |content| + assert_match(/config.api_only = true/, content) + end + + assert_file "config/initializers/cors.rb" + + assert_file "config/initializers/wrap_parameters.rb" + + assert_file "app/controllers/application_controller.rb", /ActionController::API/ + end + + private + + def default_files + files = %W( + .gitignore + Gemfile + Rakefile + config.ru + app/controllers + app/mailers + app/models + config/environments + config/initializers + config/locales + db + lib + lib/tasks + log + test/fixtures + test/controllers + test/integration + test/models + tmp + vendor + ) + files.concat %w(bin/bundle bin/rails bin/rake) + files + end + + def skipped_files + %w(app/assets + app/helpers + app/views + config/initializers/assets.rb + config/initializers/cookies_serializer.rb + config/initializers/session_store.rb + lib/assets + vendor/assets + test/helpers + tmp/cache/assets) + end +end diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 2bfa05a0b8..af1c05cab1 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -44,6 +44,7 @@ DEFAULT_APP_FILES = %w( vendor/assets vendor/assets/stylesheets vendor/assets/javascripts + tmp tmp/cache tmp/cache/assets ) @@ -606,6 +607,32 @@ class AppGeneratorTest < Rails::Generators::TestCase end end + def test_create_keeps + run_generator + folders_with_keep = %w( + app/assets/images + app/mailers + app/models + app/controllers/concerns + app/models/concerns + lib/tasks + lib/assets + log + test/fixtures + test/fixtures/files + test/controllers + test/mailers + test/models + test/helpers + test/integration + tmp + vendor/assets/stylesheets + ) + folders_with_keep.each do |folder| + assert_file("#{folder}/.keep") + end + end + def test_psych_gem run_generator gem_regex = /gem 'psych',\s+'~> 2.0',\s+platforms: :rbx/ diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb index 34e752cea1..5dae36b65e 100644 --- a/railties/test/generators/scaffold_controller_generator_test.rb +++ b/railties/test/generators/scaffold_controller_generator_test.rb @@ -174,4 +174,62 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase end end end + + def test_controller_tests_pass_by_default_inside_mountable_engine + Dir.chdir(destination_root) { `bundle exec rails plugin new bukkits --mountable` } + + engine_path = File.join(destination_root, "bukkits") + + Dir.chdir(engine_path) do + quietly { `bin/rails g controller dashboard foo` } + assert_match(/2 runs, 2 assertions, 0 failures, 0 errors/, `bundle exec rake test 2>&1`) + end + end + + def test_api_only_generates_a_proper_api_controller + run_generator ["User", "--api"] + + assert_file "app/controllers/users_controller.rb" do |content| + assert_match(/class UsersController < ApplicationController/, content) + assert_no_match(/respond_to/, content) + + assert_match(/before_action :set_user, only: \[:show, :update, :destroy\]/, content) + + assert_instance_method :index, content do |m| + assert_match(/@users = User\.all/, m) + assert_match(/render json: @users/, m) + end + + assert_instance_method :show, content do |m| + assert_match(/render json: @user/, m) + end + + assert_instance_method :create, content do |m| + assert_match(/@user = User\.new\(user_params\)/, m) + assert_match(/@user\.save/, m) + assert_match(/@user\.errors/, m) + end + + assert_instance_method :update, content do |m| + assert_match(/@user\.update\(user_params\)/, m) + assert_match(/@user\.errors/, m) + end + + assert_instance_method :destroy, content do |m| + assert_match(/@user\.destroy/, m) + end + end + end + + def test_api_controller_tests + run_generator ["User", "name:string", "age:integer", "organization:references{polymorphic}", "--api"] + + assert_file "test/controllers/users_controller_test.rb" do |content| + assert_match(/class UsersControllerTest < ActionController::TestCase/, content) + assert_match(/test "should get index"/, content) + assert_match(/post :create, params: \{ user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}/, content) + assert_match(/patch :update, params: \{ id: @user, user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}/, content) + assert_no_match(/assert_redirected_to/, content) + end + end end diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb index ee06802874..3401b96d7d 100644 --- a/railties/test/generators/scaffold_generator_test.rb +++ b/railties/test/generators/scaffold_generator_test.rb @@ -87,6 +87,76 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase assert_file "app/assets/stylesheets/product_lines.css" end + def test_api_scaffold_on_invoke + run_generator %w(product_line title:string product:belongs_to user:references --api --no-template-engine --no-helper --no-assets) + + # Model + assert_file "app/models/product_line.rb", /class ProductLine < ActiveRecord::Base/ + assert_file "test/models/product_line_test.rb", /class ProductLineTest < ActiveSupport::TestCase/ + assert_file "test/fixtures/product_lines.yml" + assert_migration "db/migrate/create_product_lines.rb", /belongs_to :product, index: true/ + assert_migration "db/migrate/create_product_lines.rb", /references :user, index: true/ + + # Route + assert_file "config/routes.rb" do |route| + assert_match(/resources :product_lines$/, route) + end + + # Controller + assert_file "app/controllers/product_lines_controller.rb" do |content| + assert_match(/class ProductLinesController < ApplicationController/, content) + assert_no_match(/respond_to/, content) + + assert_match(/before_action :set_product_line, only: \[:show, :update, :destroy\]/, content) + + assert_instance_method :index, content do |m| + assert_match(/@product_lines = ProductLine\.all/, m) + assert_match(/render json: @product_lines/, m) + end + + assert_instance_method :show, content do |m| + assert_match(/render json: @product_line/, m) + end + + assert_instance_method :create, content do |m| + assert_match(/@product_line = ProductLine\.new\(product_line_params\)/, m) + assert_match(/@product_line\.save/, m) + assert_match(/@product_line\.errors/, m) + end + + assert_instance_method :update, content do |m| + assert_match(/@product_line\.update\(product_line_params\)/, m) + assert_match(/@product_line\.errors/, m) + end + + assert_instance_method :destroy, content do |m| + assert_match(/@product_line\.destroy/, m) + end + end + + assert_file "test/controllers/product_lines_controller_test.rb" do |test| + assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, test) + assert_match(/post :create, params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test) + assert_match(/patch :update, params: \{ id: @product_line, product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test) + assert_no_match(/assert_redirected_to/, test) + end + + # Views + assert_no_file "app/views/layouts/product_lines.html.erb" + + %w(index show new edit _form).each do |view| + assert_no_file "app/views/product_lines/#{view}.html.erb" + end + + # Helpers + assert_no_file "app/helpers/product_lines_helper.rb" + + # Assets + assert_no_file "app/assets/stylesheets/scaffold.css" + assert_no_file "app/assets/javascripts/product_lines.js" + assert_no_file "app/assets/stylesheets/product_lines.css" + end + def test_functional_tests_without_attributes run_generator ["product_line"] @@ -282,6 +352,20 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase assert_no_file "app/assets/stylesheets/posts.css" end + def test_scaffold_generator_no_scaffold_stylesheet_with_switch_no_scaffold_stylesheet + run_generator [ "posts", "--no-scaffold-stylesheet" ] + assert_no_file "app/assets/stylesheets/scaffold.css" + assert_file "app/assets/javascripts/posts.js" + assert_file "app/assets/stylesheets/posts.css" + end + + def test_scaffold_generator_no_scaffold_stylesheet_with_switch_scaffold_stylesheet_false + run_generator [ "posts", "--scaffold-stylesheet=false" ] + assert_no_file "app/assets/stylesheets/scaffold.css" + assert_file "app/assets/javascripts/posts.js" + assert_file "app/assets/stylesheets/posts.css" + end + def test_scaffold_generator_with_switch_resource_route_false run_generator [ "posts", "--resource-route=false" ] assert_file "config/routes.rb" do |route| @@ -393,4 +477,18 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase assert_match(/password_digest: <%= BCrypt::Password.create\('secret'\) %>/, content) end end + + def test_scaffold_tests_pass_by_default_inside_mountable_engine + Dir.chdir(destination_root) { `bundle exec rails plugin new bukkits --mountable` } + + engine_path = File.join(destination_root, "bukkits") + + Dir.chdir(engine_path) do + quietly do + `bin/rails g scaffold User name:string age:integer; + bundle exec rake db:migrate` + end + assert_match(/8 runs, 13 assertions, 0 failures, 0 errors/, `bundle exec rake test 2>&1`) + end + end end diff --git a/railties/test/generators/shared_generator_tests.rb b/railties/test/generators/shared_generator_tests.rb index 3bcf3894ce..f983b45d2b 100644 --- a/railties/test/generators/shared_generator_tests.rb +++ b/railties/test/generators/shared_generator_tests.rb @@ -86,15 +86,6 @@ module SharedGeneratorTests end end - def test_template_is_executed_when_supplied - path = "https://gist.github.com/josevalim/103208/raw/" - template = %{ say "It works!" } - template.instance_eval "def read; self; end" # Make the string respond to read - - generator([destination_root], template: path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) - quietly { assert_match(/It works!/, capture(:stdout) { generator.invoke_all }) } - end - def test_template_is_executed_when_supplied_an_https_path path = "https://gist.github.com/josevalim/103208/raw/" template = %{ say "It works!" } @@ -138,7 +129,11 @@ module SharedGeneratorTests def test_skip_keeps run_generator [destination_root, '--skip-keeps', '--full'] - assert_file('.gitignore') + + assert_file '.gitignore' do |content| + assert_no_match(/\.keep/, content) + end + assert_no_file('app/mailers/.keep') end end diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index ce75aba4eb..31a575749a 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -1,7 +1,7 @@ require 'generators/generators_test_helper' require 'rails/generators/rails/model/model_generator' require 'rails/generators/test_unit/model/model_generator' -require 'mocha/setup' # FIXME: stop using mocha +require 'minitest/mock' class GeneratorsTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -9,16 +9,20 @@ class GeneratorsTest < Rails::Generators::TestCase def setup @path = File.expand_path("lib", Rails.root) $LOAD_PATH.unshift(@path) + @mock_generator = MiniTest::Mock.new end def teardown $LOAD_PATH.delete(@path) + @mock_generator.verify end def test_simple_invoke assert File.exist?(File.join(@path, 'generators', 'model_generator.rb')) - TestUnit::Generators::ModelGenerator.expects(:start).with(["Account"], {}) - Rails::Generators.invoke("test_unit:model", ["Account"]) + @mock_generator.expect(:call, nil, [["Account"],{}]) + TestUnit::Generators::ModelGenerator.stub(:start, @mock_generator) do + Rails::Generators.invoke("test_unit:model", ["Account"]) + end end def test_invoke_when_generator_is_not_found @@ -47,19 +51,25 @@ class GeneratorsTest < Rails::Generators::TestCase def test_should_give_higher_preference_to_rails_generators assert File.exist?(File.join(@path, 'generators', 'model_generator.rb')) - Rails::Generators::ModelGenerator.expects(:start).with(["Account"], {}) - warnings = capture(:stderr){ Rails::Generators.invoke :model, ["Account"] } - assert warnings.empty? + @mock_generator.expect(:call, nil, [["Account"],{}]) + Rails::Generators::ModelGenerator.stub(:start, @mock_generator) do + warnings = capture(:stderr){ Rails::Generators.invoke :model, ["Account"] } + assert warnings.empty? + end end def test_invoke_with_default_values - Rails::Generators::ModelGenerator.expects(:start).with(["Account"], {}) - Rails::Generators.invoke :model, ["Account"] + @mock_generator.expect(:call, nil, [["Account"],{}]) + Rails::Generators::ModelGenerator.stub(:start, @mock_generator) do + Rails::Generators.invoke :model, ["Account"] + end end def test_invoke_with_config_values - Rails::Generators::ModelGenerator.expects(:start).with(["Account"], behavior: :skip) - Rails::Generators.invoke :model, ["Account"], behavior: :skip + @mock_generator.expect(:call, nil, [["Account"],{behavior: :skip}]) + Rails::Generators::ModelGenerator.stub(:start, @mock_generator) do + Rails::Generators.invoke :model, ["Account"], behavior: :skip + end end def test_find_by_namespace @@ -103,11 +113,13 @@ class GeneratorsTest < Rails::Generators::TestCase end def test_invoke_with_nested_namespaces - model_generator = mock('ModelGenerator') do - expects(:start).with(["Account"], {}) + model_generator = Minitest::Mock.new + model_generator.expect(:start, nil, [["Account"], {}]) + @mock_generator.expect(:call, model_generator, ['namespace', 'my:awesome']) + Rails::Generators.stub(:find_by_namespace, @mock_generator) do + Rails::Generators.invoke 'my:awesome:namespace', ["Account"] end - Rails::Generators.expects(:find_by_namespace).with('namespace', 'my:awesome').returns(model_generator) - Rails::Generators.invoke 'my:awesome:namespace', ["Account"] + model_generator.verify end def test_rails_generators_help_with_builtin_information @@ -173,8 +185,10 @@ class GeneratorsTest < Rails::Generators::TestCase 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"] + @mock_generator.expect(:call, nil, [["Account"],{}]) + TestUnit::Generators::ModelGenerator.stub(:start, @mock_generator) do + Rails::Generators.invoke "shoulda:model", ["Account"] + end ensure Rails::Generators.fallbacks.delete(:shoulda) end @@ -182,8 +196,10 @@ class GeneratorsTest < Rails::Generators::TestCase 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"] + @mock_generator.expect(:call, nil, [["Account"],{}]) + TestUnit::Generators::ModelGenerator.stub(:start, @mock_generator) do + Rails::Generators.invoke "super_shoulda:model", ["Account"] + end ensure Rails::Generators.fallbacks.delete(:shoulda) Rails::Generators.fallbacks.delete(:super_shoulda) diff --git a/railties/test/path_generation_test.rb b/railties/test/path_generation_test.rb index d22374a1ff..27e64b97b7 100644 --- a/railties/test/path_generation_test.rb +++ b/railties/test/path_generation_test.rb @@ -1,8 +1,6 @@ require 'abstract_unit' require 'active_support/core_ext/object/with_options' require 'active_support/core_ext/object/json' -require 'rails' -require 'rails/application' class PathGenerationTest < ActiveSupport::TestCase attr_reader :app diff --git a/railties/test/paths_test.rb b/railties/test/paths_test.rb index 1aeb9ec339..12630e4d01 100644 --- a/railties/test/paths_test.rb +++ b/railties/test/paths_test.rb @@ -1,10 +1,9 @@ require 'abstract_unit' require 'rails/paths' -require 'mocha/setup' # FIXME: stop using mocha +require 'minitest/mock' class PathsTest < ActiveSupport::TestCase def setup - File.stubs(:exist?).returns(true) @root = Rails::Paths::Root.new("/foo/bar") end @@ -93,10 +92,12 @@ class PathsTest < ActiveSupport::TestCase end test "it is possible to add a path that should be autoloaded only once" do - @root.add "app", with: "/app" - @root["app"].autoload_once! - assert @root["app"].autoload_once? - assert @root.autoload_once.include?(@root["app"].expanded.first) + File.stub(:exist?, true) do + @root.add "app", with: "/app" + @root["app"].autoload_once! + assert @root["app"].autoload_once? + assert @root.autoload_once.include?(@root["app"].expanded.first) + end end test "it is possible to remove a path that should be autoloaded only once" do @@ -110,37 +111,47 @@ class PathsTest < ActiveSupport::TestCase end test "it is possible to add a path without assignment and specify it should be loaded only once" do - @root.add "app", with: "/app", autoload_once: true - assert @root["app"].autoload_once? - assert @root.autoload_once.include?("/app") + File.stub(:exist?, true) do + @root.add "app", with: "/app", autoload_once: true + assert @root["app"].autoload_once? + assert @root.autoload_once.include?("/app") + end end test "it is possible to add multiple paths without assignment and specify it should be loaded only once" do - @root.add "app", with: ["/app", "/app2"], autoload_once: true - assert @root["app"].autoload_once? - assert @root.autoload_once.include?("/app") - assert @root.autoload_once.include?("/app2") + File.stub(:exist?, true) do + @root.add "app", with: ["/app", "/app2"], autoload_once: true + assert @root["app"].autoload_once? + assert @root.autoload_once.include?("/app") + assert @root.autoload_once.include?("/app2") + end end test "making a path autoload_once more than once only includes it once in @root.load_once" do - @root["app"] = "/app" - @root["app"].autoload_once! - @root["app"].autoload_once! - assert_equal 1, @root.autoload_once.select {|p| p == @root["app"].expanded.first }.size + File.stub(:exist?, true) do + @root["app"] = "/app" + @root["app"].autoload_once! + @root["app"].autoload_once! + assert_equal 1, @root.autoload_once.select {|p| p == @root["app"].expanded.first }.size + end end test "paths added to a load_once path should be added to the autoload_once collection" do - @root["app"] = "/app" - @root["app"].autoload_once! - @root["app"] << "/app2" - assert_equal 2, @root.autoload_once.size + File.stub(:exist?, true) do + @root["app"] = "/app" + @root["app"].autoload_once! + @root["app"] << "/app2" + assert_equal 2, @root.autoload_once.size + end end test "it is possible to mark a path as eager loaded" do - @root["app"] = "/app" - @root["app"].eager_load! - assert @root["app"].eager_load? - assert @root.eager_load.include?(@root["app"].to_a.first) + File.stub(:exist?, true) do + @root["app"] = "/app" + @root["app"].eager_load! + assert @root["app"].eager_load? + assert @root.eager_load.include?(@root["app"].to_a.first) + end end test "it is possible to skip a path from eager loading" do @@ -154,38 +165,48 @@ class PathsTest < ActiveSupport::TestCase end test "it is possible to add a path without assignment and mark it as eager" do - @root.add "app", with: "/app", eager_load: true - assert @root["app"].eager_load? - assert @root.eager_load.include?("/app") + File.stub(:exist?, true) do + @root.add "app", with: "/app", eager_load: true + assert @root["app"].eager_load? + assert @root.eager_load.include?("/app") + end end test "it is possible to add multiple paths without assignment and mark them as eager" do - @root.add "app", with: ["/app", "/app2"], eager_load: true - assert @root["app"].eager_load? - assert @root.eager_load.include?("/app") - assert @root.eager_load.include?("/app2") + File.stub(:exist?, true) do + @root.add "app", with: ["/app", "/app2"], eager_load: true + assert @root["app"].eager_load? + assert @root.eager_load.include?("/app") + assert @root.eager_load.include?("/app2") + end end test "it is possible to create a path without assignment and mark it both as eager and load once" do - @root.add "app", with: "/app", eager_load: true, autoload_once: true - assert @root["app"].eager_load? - assert @root["app"].autoload_once? - assert @root.eager_load.include?("/app") - assert @root.autoload_once.include?("/app") + File.stub(:exist?, true) do + @root.add "app", with: "/app", eager_load: true, autoload_once: true + assert @root["app"].eager_load? + assert @root["app"].autoload_once? + assert @root.eager_load.include?("/app") + assert @root.autoload_once.include?("/app") + end end test "making a path eager more than once only includes it once in @root.eager_paths" do - @root["app"] = "/app" - @root["app"].eager_load! - @root["app"].eager_load! - assert_equal 1, @root.eager_load.select {|p| p == @root["app"].expanded.first }.size + File.stub(:exist?, true) do + @root["app"] = "/app" + @root["app"].eager_load! + @root["app"].eager_load! + assert_equal 1, @root.eager_load.select {|p| p == @root["app"].expanded.first }.size + end end test "paths added to an eager_load path should be added to the eager_load collection" do - @root["app"] = "/app" - @root["app"].eager_load! - @root["app"] << "/app2" - assert_equal 2, @root.eager_load.size + File.stub(:exist?, true) do + @root["app"] = "/app" + @root["app"].eager_load! + @root["app"] << "/app2" + assert_equal 2, @root.eager_load.size + end end test "it should be possible to add a path's default glob" do @@ -207,28 +228,36 @@ class PathsTest < ActiveSupport::TestCase end test "a path can be added to the load path" do - @root["app"] = "app" - @root["app"].load_path! - @root["app/models"] = "app/models" - assert_equal ["/foo/bar/app"], @root.load_paths + File.stub(:exist?, true) do + @root["app"] = "app" + @root["app"].load_path! + @root["app/models"] = "app/models" + assert_equal ["/foo/bar/app"], @root.load_paths + end end test "a path can be added to the load path on creation" do - @root.add "app", with: "/app", load_path: true - assert @root["app"].load_path? - assert_equal ["/app"], @root.load_paths + File.stub(:exist?, true) do + @root.add "app", with: "/app", load_path: true + assert @root["app"].load_path? + assert_equal ["/app"], @root.load_paths + end end test "a path can be marked as autoload path" do - @root["app"] = "app" - @root["app"].autoload! - @root["app/models"] = "app/models" - assert_equal ["/foo/bar/app"], @root.autoload_paths + File.stub(:exist?, true) do + @root["app"] = "app" + @root["app"].autoload! + @root["app/models"] = "app/models" + assert_equal ["/foo/bar/app"], @root.autoload_paths + end end test "a path can be marked as autoload on creation" do - @root.add "app", with: "/app", autoload: true - assert @root["app"].autoload? - assert_equal ["/app"], @root.autoload_paths + File.stub(:exist?, true) do + @root.add "app", with: "/app", autoload: true + assert @root["app"].autoload? + assert_equal ["/app"], @root.autoload_paths + end end end diff --git a/railties/test/test_unit/reporter_test.rb b/railties/test/test_unit/reporter_test.rb index 77883612f5..d619a3e515 100644 --- a/railties/test/test_unit/reporter_test.rb +++ b/railties/test/test_unit/reporter_test.rb @@ -43,6 +43,20 @@ class TestUnitReporterTest < ActiveSupport::TestCase assert_rerun_snippet_count 1 end + test "allows to customize the executable in the rerun snippet" do + original_executable = Rails::TestUnitReporter.executable + begin + Rails::TestUnitReporter.executable = "bin/test" + verbose = Rails::TestUnitReporter.new @output, verbose: true + @reporter.record(failed_test) + @reporter.report + + assert_match %r{^bin/test .*test/test_unit/reporter_test.rb:6$}, @output.string + ensure + Rails::TestUnitReporter.executable = original_executable + end + end + private def assert_rerun_snippet_count(snippet_count) assert_equal snippet_count, @output.string.scan(%r{^bin/rails test }).size diff --git a/railties/test/test_unit/runner_test.rb b/railties/test/test_unit/runner_test.rb deleted file mode 100644 index 9ea8b2c114..0000000000 --- a/railties/test/test_unit/runner_test.rb +++ /dev/null @@ -1,111 +0,0 @@ -require 'abstract_unit' -require 'env_helpers' -require 'rails/test_unit/runner' - -class TestUnitTestRunnerTest < ActiveSupport::TestCase - include EnvHelpers - - setup do - @options = Rails::TestRunner::Options - end - - test "shows the filtered backtrace by default" do - options = @options.parse([]) - assert_not options[:backtrace] - end - - test "has --backtrace (-b) option to show the full backtrace" do - options = @options.parse(["-b"]) - assert options[:backtrace] - - options = @options.parse(["--backtrace"]) - assert options[:backtrace] - end - - test "show full backtrace using BACKTRACE environment variable" do - switch_env "BACKTRACE", "true" do - options = @options.parse([]) - assert options[:backtrace] - end - end - - test "tests run in the test environment by default" do - options = @options.parse([]) - assert_equal "test", options[:environment] - end - - test "can run in a specific environment" do - options = @options.parse(["-e development"]) - assert_equal "development", options[:environment] - end - - test "parse the filename and line" do - file = "test/test_unit/runner_test.rb" - absolute_file = File.expand_path __FILE__ - options = @options.parse(["#{file}:20"]) - assert_equal absolute_file, options[:filename] - assert_equal 20, options[:line] - - options = @options.parse(["#{file}:"]) - assert_equal [absolute_file], options[:patterns] - assert_nil options[:line] - - options = @options.parse([file]) - assert_equal [absolute_file], options[:patterns] - assert_nil options[:line] - end - - test "find_method on same file" do - options = @options.parse(["#{__FILE__}:#{__LINE__}"]) - runner = Rails::TestRunner.new(options) - assert_equal "test_find_method_on_same_file", runner.find_method - end - - test "find_method on a different file" do - options = @options.parse(["foobar.rb:#{__LINE__}"]) - runner = Rails::TestRunner.new(options) - assert_nil runner.find_method - end - - test "run all tests in a directory" do - options = @options.parse([__dir__]) - - assert_equal ["#{__dir__}/**/*_test.rb"], options[:patterns] - assert_nil options[:filename] - assert_nil options[:line] - end - - test "run multiple folders" do - application_dir = File.expand_path("#{__dir__}/../application") - - options = @options.parse([__dir__, application_dir]) - - assert_equal ["#{__dir__}/**/*_test.rb", "#{application_dir}/**/*_test.rb"], options[:patterns] - assert_nil options[:filename] - assert_nil options[:line] - - runner = Rails::TestRunner.new(options) - assert runner.test_files.size > 0 - end - - test "run multiple files and run one file by line" do - line = __LINE__ - absolute_file = File.expand_path(__FILE__) - options = @options.parse([__dir__, "#{__FILE__}:#{line}"]) - - assert_equal ["#{__dir__}/**/*_test.rb"], options[:patterns] - assert_equal absolute_file, options[:filename] - assert_equal line, options[:line] - - runner = Rails::TestRunner.new(options) - assert_equal [absolute_file], runner.test_files, 'Only returns the file that running by line' - end - - test "running multiple files passing line number" do - line = __LINE__ - options = @options.parse(["foobar.rb:8", "#{__FILE__}:#{line}"]) - - assert_equal File.expand_path(__FILE__), options[:filename], 'Returns the last file' - assert_equal line, options[:line] - end -end |