diff options
Diffstat (limited to 'railties/test')
47 files changed, 1371 insertions, 551 deletions
diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb index 0749615d03..794d180e5d 100644 --- a/railties/test/abstract_unit.rb +++ b/railties/test/abstract_unit.rb @@ -4,6 +4,7 @@ require File.expand_path("../../../load_paths", __FILE__) require 'stringio' require 'active_support/testing/autorun' +require 'active_support/testing/stream' require 'fileutils' require 'active_support' @@ -28,26 +29,5 @@ def jruby_skip(message = '') end class ActiveSupport::TestCase - # FIXME: we have tests that depend on run order, we should fix that and - # remove this method call. - self.test_order = :sorted - - private - - def capture(stream) - stream = stream.to_s - captured_stream = Tempfile.new(stream) - stream_io = eval("$#{stream}") - origin_stream = stream_io.dup - stream_io.reopen(captured_stream) - - yield - - stream_io.rewind - return captured_stream.read - ensure - captured_stream.close - captured_stream.unlink - stream_io.reopen(origin_stream) - end + include ActiveSupport::Testing::Stream end 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/asset_debugging_test.rb b/railties/test/application/asset_debugging_test.rb index 9a571fac3a..acd387256c 100644 --- a/railties/test/application/asset_debugging_test.rb +++ b/railties/test/application/asset_debugging_test.rb @@ -57,8 +57,8 @@ module ApplicationTests class ::PostsController < ActionController::Base ; end get '/posts?debug_assets=true' - assert_match(/<script src="\/assets\/application-([0-z]+)\.js\?body=1"><\/script>/, last_response.body) - assert_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js\?body=1"><\/script>/, last_response.body) + assert_match(/<script src="\/assets\/application(\.self)?-([0-z]+)\.js\?body=1"><\/script>/, last_response.body) + assert_match(/<script src="\/assets\/xmlhr(\.self)?-([0-z]+)\.js\?body=1"><\/script>/, last_response.body) end end end diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index d58a27403e..1e2a9ba040 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- require 'isolation/abstract_unit' require 'rack/test' require 'active_support/json' @@ -192,6 +191,7 @@ module ApplicationTests test "asset pipeline should use a Sprockets::Index when config.assets.digest is true" do add_to_config "config.action_controller.perform_caching = false" + add_to_env_config "production", "config.assets.compile = true" ENV["RAILS_ENV"] = "production" require "#{app_path}/config/environment" @@ -205,7 +205,7 @@ module ApplicationTests app_file "app/assets/javascripts/application.js", "alert();" precompile! - manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first + manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first assets = ActiveSupport::JSON.decode(File.read(manifest)) assert_match(/application-([0-z]+)\.js/, assets["assets"]["application.js"]) @@ -218,7 +218,7 @@ module ApplicationTests precompile! - manifest = Dir["#{app_path}/public/x/manifest-*.json"].first + manifest = Dir["#{app_path}/public/x/.sprockets-manifest-*.json"].first assets = ActiveSupport::JSON.decode(File.read(manifest)) assert_match(/application-([0-z]+)\.js/, assets["assets"]["application.js"]) end @@ -230,7 +230,7 @@ module ApplicationTests ENV["RAILS_ENV"] = "production" precompile! - manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first + manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first assets = ActiveSupport::JSON.decode(File.read(manifest)) asset_path = assets["assets"]["application.js"] @@ -262,7 +262,7 @@ module ApplicationTests ENV["RAILS_ENV"] = "production" precompile! - manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first + manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first assets = ActiveSupport::JSON.decode(File.read(manifest)) asset_path = assets["assets"]["application.css"] @@ -292,7 +292,7 @@ module ApplicationTests precompile! - manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first + manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first assets = ActiveSupport::JSON.decode(File.read(manifest)) assert asset_path = assets["assets"].find { |(k, _)| k && k =~ /.png/ }[1] @@ -438,9 +438,9 @@ module ApplicationTests class ::PostsController < ActionController::Base; end get '/posts', {}, {'HTTPS'=>'off'} - assert_match('src="http://example.com/assets/application.js', last_response.body) + assert_match('src="http://example.com/assets/application.self.js', last_response.body) get '/posts', {}, {'HTTPS'=>'on'} - assert_match('src="https://example.com/assets/application.js', last_response.body) + assert_match('src="https://example.com/assets/application.self.js', last_response.body) end test "asset urls should be protocol-relative if no request is in scope" do @@ -465,17 +465,6 @@ module ApplicationTests assert_match "src='/sub/uri/assets/rails.png'", File.read(Dir["#{app_path}/public/assets/app-*.js"].first) end - test "assets:cache:clean should clean cache" do - ENV["RAILS_ENV"] = "production" - precompile! - - quietly do - Dir.chdir(app_path){ `bundle exec rake assets:clobber` } - end - - assert !File.exist?("#{app_path}/tmp/cache/assets") - end - private def app_with_assets_in_view diff --git a/railties/test/application/bin_setup_test.rb b/railties/test/application/bin_setup_test.rb new file mode 100644 index 0000000000..1bdced02e9 --- /dev/null +++ b/railties/test/application/bin_setup_test.rb @@ -0,0 +1,54 @@ +require 'isolation/abstract_unit' + +module ApplicationTests + class BinSetupTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + end + + def teardown + teardown_app + end + + def test_bin_setup + Dir.chdir(app_path) do + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: 20140423102712) do + create_table(:articles) {} + end + RUBY + + list_tables = lambda { `bin/rails runner 'p ActiveRecord::Base.connection.tables'`.strip } + File.write("log/my.log", "zomg!") + + assert_equal '[]', list_tables.call + assert_equal 5, File.size("log/my.log") + assert_not File.exist?("tmp/restart.txt") + `bin/setup 2>&1` + assert_equal 0, File.size("log/my.log") + assert_equal '["articles", "schema_migrations"]', list_tables.call + assert File.exist?("tmp/restart.txt") + end + end + + def test_bin_setup_output + Dir.chdir(app_path) do + app_file 'db/schema.rb', "" + + output = `bin/setup 2>&1` + assert_equal(<<-OUTPUT, output) +== Installing dependencies == +The Gemfile's dependencies are satisfied + +== Preparing database == + +== Removing old logs and tempfiles == + +== Restarting application server == + OUTPUT + end + end + end +end diff --git a/railties/test/application/build_original_fullpath_test.rb b/railties/test/application/build_original_fullpath_test.rb deleted file mode 100644 index 647ffb097a..0000000000 --- a/railties/test/application/build_original_fullpath_test.rb +++ /dev/null @@ -1,27 +0,0 @@ -require "abstract_unit" - -module ApplicationTests - class BuildOriginalPathTest < ActiveSupport::TestCase - def test_include_original_PATH_info_in_ORIGINAL_FULLPATH - env = { 'PATH_INFO' => '/foo/' } - assert_equal "/foo/", Rails.application.send(:build_original_fullpath, env) - end - - def test_include_SCRIPT_NAME - env = { - 'SCRIPT_NAME' => '/foo', - 'PATH_INFO' => '/bar' - } - - assert_equal "/foo/bar", Rails.application.send(:build_original_fullpath, env) - end - - def test_include_QUERY_STRING - env = { - 'PATH_INFO' => '/foo', - 'QUERY_STRING' => 'bar', - } - assert_equal "/foo?bar", Rails.application.send(:build_original_fullpath, env) - end - end -end diff --git a/railties/test/application/configuration/base_test.rb b/railties/test/application/configuration/base_test.rb deleted file mode 100644 index d6a82b139d..0000000000 --- a/railties/test/application/configuration/base_test.rb +++ /dev/null @@ -1,37 +0,0 @@ -require 'isolation/abstract_unit' -require 'rack/test' -require 'env_helpers' - -module ApplicationTests - module ConfigurationTests - class BaseTest < ActiveSupport::TestCase - def setup - build_app - boot_rails - FileUtils.rm_rf("#{app_path}/config/environments") - end - - def teardown - teardown_app - FileUtils.rm_rf(new_app) if File.directory?(new_app) - end - - private - def new_app - File.expand_path("#{app_path}/../new_app") - end - - def copy_app - FileUtils.cp_r(app_path, new_app) - end - - def app - @app ||= Rails.application - end - - def require_environment - require "#{app_path}/config/environment" - end - end - end -end
\ No newline at end of file diff --git a/railties/test/application/configuration/custom_test.rb b/railties/test/application/configuration/custom_test.rb index f8d22f6d97..28b3b2f2d6 100644 --- a/railties/test/application/configuration/custom_test.rb +++ b/railties/test/application/configuration/custom_test.rb @@ -1,22 +1,54 @@ -require 'application/configuration/base_test' - -class ApplicationTests::ConfigurationTests::CustomTest < ApplicationTests::ConfigurationTests::BaseTest - test 'access custom configuration point' do - add_to_config <<-RUBY - config.x.payment_processing.schedule = :daily - config.x.payment_processing.retries = 3 - config.x.super_debugger = true - config.x.hyper_debugger = false - config.x.nil_debugger = nil - RUBY - require_environment - - x = Rails.configuration.x - assert_equal :daily, x.payment_processing.schedule - assert_equal 3, x.payment_processing.retries - assert_equal true, x.super_debugger - assert_equal false, x.hyper_debugger - assert_equal nil, x.nil_debugger - assert_nil x.i_do_not_exist.zomg +require 'isolation/abstract_unit' + +module ApplicationTests + module ConfigurationTests + class CustomTest < ActiveSupport::TestCase + def setup + build_app + boot_rails + FileUtils.rm_rf("#{app_path}/config/environments") + end + + def teardown + teardown_app + FileUtils.rm_rf(new_app) if File.directory?(new_app) + end + + test 'access custom configuration point' do + add_to_config <<-RUBY + config.x.payment_processing.schedule = :daily + config.x.payment_processing.retries = 3 + config.x.super_debugger = true + config.x.hyper_debugger = false + config.x.nil_debugger = nil + RUBY + require_environment + + x = Rails.configuration.x + assert_equal :daily, x.payment_processing.schedule + assert_equal 3, x.payment_processing.retries + assert_equal true, x.super_debugger + assert_equal false, x.hyper_debugger + assert_equal nil, x.nil_debugger + assert_nil x.i_do_not_exist.zomg + end + + private + def new_app + File.expand_path("#{app_path}/../new_app") + end + + def copy_app + FileUtils.cp_r(app_path, new_app) + end + + def app + @app ||= Rails.application + end + + def require_environment + require "#{app_path}/config/environment" + end + end end end diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index cb02e0427b..f677a7c42a 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -690,7 +690,7 @@ module ApplicationTests _ = ActionMailer::Base - assert_equal [::MyPreviewMailInterceptor], ActionMailer::Base.preview_interceptors + assert_equal [ActionMailer::InlinePreviewInterceptor, ::MyPreviewMailInterceptor], ActionMailer::Base.preview_interceptors end test "registers multiple preview interceptors with ActionMailer" do @@ -703,7 +703,20 @@ module ApplicationTests _ = ActionMailer::Base - assert_equal [MyPreviewMailInterceptor, MyOtherPreviewMailInterceptor], ActionMailer::Base.preview_interceptors + assert_equal [ActionMailer::InlinePreviewInterceptor, MyPreviewMailInterceptor, MyOtherPreviewMailInterceptor], ActionMailer::Base.preview_interceptors + end + + test "default preview interceptor can be removed" do + app_file 'config/initializers/preview_interceptors.rb', <<-RUBY + ActionMailer::Base.preview_interceptors.delete(ActionMailer::InlinePreviewInterceptor) + RUBY + + require "#{app_path}/config/environment" + require "mail" + + _ = ActionMailer::Base + + assert_equal [], ActionMailer::Base.preview_interceptors end test "registers observers with ActionMailer" do diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb index 85066210f3..1027bca2c1 100644 --- a/railties/test/application/loading_test.rb +++ b/railties/test/application/loading_test.rb @@ -210,7 +210,7 @@ class LoadingTest < ActiveSupport::TestCase app_file 'config/routes.rb', <<-RUBY $counter ||= 0 Rails.application.routes.draw do - get '/c', to: lambda { |env| User; [200, {"Content-Type" => "text/plain"}, [$counter.to_s]] } + get '/c', to: lambda { |env| User.name; [200, {"Content-Type" => "text/plain"}, [$counter.to_s]] } end RUBY @@ -243,7 +243,7 @@ class LoadingTest < ActiveSupport::TestCase $counter ||= 1 $counter *= 2 Rails.application.routes.draw do - get '/c', to: lambda { |env| User; [200, {"Content-Type" => "text/plain"}, [$counter.to_s]] } + get '/c', to: lambda { |env| User.name; [200, {"Content-Type" => "text/plain"}, [$counter.to_s]] } end RUBY diff --git a/railties/test/application/mailer_previews_test.rb b/railties/test/application/mailer_previews_test.rb index 1752a9f3c6..e462d2c15e 100644 --- a/railties/test/application/mailer_previews_test.rb +++ b/railties/test/application/mailer_previews_test.rb @@ -1,5 +1,7 @@ require 'isolation/abstract_unit' require 'rack/test' +require 'base64' + module ApplicationTests class MailerPreviewsTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation @@ -327,6 +329,32 @@ module ApplicationTests assert_match "Email 'bar' not found in NotifierPreview", last_response.body end + test "mailer preview NullMail" do + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + # does not call +mail+ + end + end + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers/notifier/foo" + assert_match "You are trying to preview an email that does not have any content.", last_response.body + assert_match "notifier#foo", last_response.body + end + test "mailer preview email part not found" do mailer 'notifier', <<-RUBY class Notifier < ActionMailer::Base @@ -428,6 +456,222 @@ module ApplicationTests assert_match '<option selected value="?part=text%2Fplain">View as plain-text email</option>', last_response.body end + test "mailer previews create correct links when loaded on a subdirectory" do + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + mail to: "to@example.org" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers", {}, 'SCRIPT_NAME' => '/my_app' + assert_match '<h3><a href="/my_app/rails/mailers/notifier">Notifier</a></h3>', last_response.body + assert_match '<li><a href="/my_app/rails/mailers/notifier/foo">foo</a></li>', last_response.body + end + + test "plain text mailer preview with attachment" do + image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca/JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo=" + + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + attachments['pixel.png'] = File.read("#{app_path}/public/images/pixel.png", mode: 'rb') + mail to: "to@example.org" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers/notifier/foo" + assert_equal 200, last_response.status + assert_match %r[<iframe seamless name="messageBody"], last_response.body + + get "/rails/mailers/notifier/foo?part=text/plain" + assert_equal 200, last_response.status + assert_match %r[Hello, World!], last_response.body + end + + test "multipart mailer preview with attachment" do + image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca/JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo=" + + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + attachments['pixel.png'] = File.read("#{app_path}/public/images/pixel.png", mode: 'rb') + mail to: "to@example.org" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + html_template 'notifier/foo', <<-RUBY + <p>Hello, World!</p> + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers/notifier/foo" + assert_equal 200, last_response.status + assert_match %r[<iframe seamless name="messageBody"], last_response.body + + get "/rails/mailers/notifier/foo?part=text/plain" + assert_equal 200, last_response.status + assert_match %r[Hello, World!], last_response.body + + get "/rails/mailers/notifier/foo?part=text/html" + assert_equal 200, last_response.status + assert_match %r[<p>Hello, World!</p>], last_response.body + end + + test "multipart mailer preview with inline attachment" do + image_file "pixel.png", "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca/JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo=" + + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + attachments['pixel.png'] = File.read("#{app_path}/public/images/pixel.png", mode: 'rb') + mail to: "to@example.org" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + html_template 'notifier/foo', <<-RUBY + <p>Hello, World!</p> + <%= image_tag attachments['pixel.png'].url %> + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers/notifier/foo" + assert_equal 200, last_response.status + assert_match %r[<iframe seamless name="messageBody"], last_response.body + + get "/rails/mailers/notifier/foo?part=text/plain" + assert_equal 200, last_response.status + assert_match %r[Hello, World!], last_response.body + + get "/rails/mailers/notifier/foo?part=text/html" + assert_equal 200, last_response.status + assert_match %r[<p>Hello, World!</p>], last_response.body + assert_match %r[src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEWzIioca/JlAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJgggo="], last_response.body + end + + test "multipart mailer preview with attached email" do + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + message = ::Mail.new do + from 'foo@example.com' + to 'bar@example.com' + subject 'Important Message' + + text_part do + body 'Goodbye, World!' + end + + html_part do + body '<p>Goodbye, World!</p>' + end + end + + attachments['message.eml'] = message.to_s + mail to: "to@example.org" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + html_template 'notifier/foo', <<-RUBY + <p>Hello, World!</p> + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers/notifier/foo" + assert_equal 200, last_response.status + assert_match %r[<iframe seamless name="messageBody"], last_response.body + + get "/rails/mailers/notifier/foo?part=text/plain" + assert_equal 200, last_response.status + assert_match %r[Hello, World!], last_response.body + + get "/rails/mailers/notifier/foo?part=text/html" + assert_equal 200, last_response.status + assert_match %r[<p>Hello, World!</p>], last_response.body + end + private def build_app super @@ -449,5 +693,9 @@ module ApplicationTests def text_template(name, contents) app_file("app/views/#{name}.text.erb", contents) end + + def image_file(name, contents) + app_file("public/images/#{name}", Base64.strict_decode64(contents), 'wb') + end end end diff --git a/railties/test/application/middleware/exceptions_test.rb b/railties/test/application/middleware/exceptions_test.rb index a7472b37f1..4906f9a1e8 100644 --- a/railties/test/application/middleware/exceptions_test.rb +++ b/railties/test/application/middleware/exceptions_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'isolation/abstract_unit' require 'rack/test' diff --git a/railties/test/application/middleware/session_test.rb b/railties/test/application/middleware/session_test.rb index eb7885e5b1..25eadfc387 100644 --- a/railties/test/application/middleware/session_test.rb +++ b/railties/test/application/middleware/session_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'isolation/abstract_unit' require 'rack/test' @@ -36,7 +35,7 @@ module ApplicationTests flash[:notice] = "notice" end - render nothing: true + head :ok end end @@ -61,7 +60,7 @@ module ApplicationTests def write_session session[:foo] = 1 - render nothing: true + head :ok end def read_session @@ -102,7 +101,7 @@ module ApplicationTests def write_cookie cookies[:foo] = '1' - render nothing: true + head :ok end def read_cookie @@ -140,7 +139,7 @@ module ApplicationTests class FooController < ActionController::Base def write_session session[:foo] = 1 - render nothing: true + head :ok end def read_session @@ -185,7 +184,7 @@ module ApplicationTests class FooController < ActionController::Base def write_session session[:foo] = 1 - render nothing: true + head :ok end def read_session @@ -235,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 @@ -294,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 0a793f8f60..1a46cd3568 100644 --- a/railties/test/application/middleware/static_test.rb +++ b/railties/test/application/middleware/static_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'isolation/abstract_unit' require 'rack/test' @@ -27,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 c64fe082f3..04bd19784a 100644 --- a/railties/test/application/middleware_test.rb +++ b/railties/test/application/middleware_test.rb @@ -125,6 +125,22 @@ module ApplicationTests assert !middleware.include?("ActionDispatch::Static") end + test "can delete a middleware from the stack even if insert_before is added after delete" do + add_to_config "config.middleware.delete Rack::Runtime" + add_to_config "config.middleware.insert_before(Rack::Runtime, Rack::Config)" + boot! + assert middleware.include?("Rack::Config") + assert_not middleware.include?("Rack::Runtime") + end + + test "can delete a middleware from the stack even if insert_after is added after delete" do + add_to_config "config.middleware.delete Rack::Runtime" + add_to_config "config.middleware.insert_after(Rack::Runtime, Rack::Config)" + boot! + assert middleware.include?("Rack::Config") + assert_not middleware.include?("Rack::Runtime") + end + test "includes exceptions middlewares even if action_dispatch.show_exceptions is disabled" do add_to_config "config.action_dispatch.show_exceptions = false" boot! diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb index c414732f92..5cc9790b28 100644 --- a/railties/test/application/rake/dbs_test.rb +++ b/railties/test/application/rake/dbs_test.rb @@ -181,6 +181,34 @@ module ApplicationTests end end + test "db:schema:load with inflections" do + Dir.chdir(app_path) do + app_file 'config/initializers/inflection.rb', <<-RUBY + ActiveSupport::Inflector.inflections do |inflect| + inflect.irregular 'goose', 'geese' + end + RUBY + app_file 'config/initializers/primary_key_table_name.rb', <<-RUBY + ActiveRecord::Base.primary_key_prefix_type = :table_name + RUBY + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: 20140423102712) do + create_table("goose".pluralize) do |t| + t.string :name + end + end + RUBY + + `bin/rake db:schema:load` + + tables = `bin/rails runner 'p ActiveRecord::Base.connection.tables'`.strip + assert_match(/"geese"/, tables) + + columns = `bin/rails runner 'p ActiveRecord::Base.connection.columns("geese").map(&:name)'`.strip + assert_equal columns, '["gooseid", "name"]' + end + end + def db_test_load_structure Dir.chdir(app_path) do `rails generate model book title:string; 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 new file mode 100644 index 0000000000..4cae199e6b --- /dev/null +++ b/railties/test/application/rake/restart_test.rb @@ -0,0 +1,39 @@ +require "isolation/abstract_unit" + +module ApplicationTests + module RakeTests + class RakeRestartTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + boot_rails + end + + 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` + curr_mtime = File.mtime("tmp/restart.txt") + 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 e8c8de9f73..dd26ec867d 100644 --- a/railties/test/application/rake_test.rb +++ b/railties/test/application/rake_test.rb @@ -99,7 +99,7 @@ module ApplicationTests end def test_code_statistics_sanity - assert_match "Code LOC: 5 Test LOC: 0 Code to Test Ratio: 1:0.0", + assert_match "Code LOC: 7 Test LOC: 0 Code to Test Ratio: 1:0.0", Dir.chdir(app_path){ `rake stats` } end @@ -190,17 +190,20 @@ module ApplicationTests bundle exec rake db:migrate test` end - assert_match(/7 runs, 13 assertions, 0 failures, 0 errors/, output) + assert_match(/7 runs, 12 assertions, 0 failures, 0 errors/, output) assert_no_match(/Errors running/, output) end - def test_scaffold_with_references_columns_tests_pass_by_default + 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" + output = Dir.chdir(app_path) do `rails generate scaffold LineItems product:references cart:belongs_to; bundle exec rake db:migrate test` end - assert_match(/7 runs, 13 assertions, 0 failures, 0 errors/, output) + assert_match(/7 runs, 12 assertions, 0 failures, 0 errors/, output) assert_no_match(/Errors running/, output) end @@ -227,7 +230,7 @@ module ApplicationTests def test_rake_dump_structure_should_respect_db_structure_env_variable Dir.chdir(app_path) do # ensure we have a schema_migrations table to dump - `bundle exec rake db:migrate db:structure:dump DB_STRUCTURE=db/my_structure.sql` + `bundle exec rake db:migrate db:structure:dump SCHEMA=db/my_structure.sql` end assert File.exist?(File.join(app_path, 'db', 'my_structure.sql')) end @@ -282,5 +285,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 032b11a95f..c122b315c0 100644 --- a/railties/test/application/test_runner_test.rb +++ b/railties/test/application/test_runner_test.rb @@ -7,7 +7,6 @@ module ApplicationTests def setup build_app - ENV['RAILS_ENV'] = nil create_schema end @@ -47,16 +46,15 @@ module ApplicationTests def; end RUBY - error_stream = Tempfile.new('error') - redirect_stderr(error_stream) { run_test_command('test/models/error_test.rb') } - assert_match "syntax error", error_stream.read + error = capture(:stderr) { run_test_command('test/models/error_test.rb') } + assert_match "syntax error", error end def test_run_models create_test_file :models, 'foo' create_test_file :models, 'bar' create_test_file :controllers, 'foobar_controller' - run_test_models_command.tap do |output| + run_test_command("test/models").tap do |output| assert_match "FooTest", output assert_match "BarTest", output assert_match "2 runs, 2 assertions, 0 failures", output @@ -67,7 +65,7 @@ module ApplicationTests create_test_file :helpers, 'foo_helper' create_test_file :helpers, 'bar_helper' create_test_file :controllers, 'foobar_controller' - run_test_helpers_command.tap do |output| + run_test_command("test/helpers").tap do |output| assert_match "FooHelperTest", output assert_match "BarHelperTest", output assert_match "2 runs, 2 assertions, 0 failures", output @@ -75,6 +73,7 @@ module ApplicationTests end def test_run_units + skip "we no longer have the concept of unit tests. Just different directories..." create_test_file :models, 'foo' create_test_file :helpers, 'bar_helper' create_test_file :unit, 'baz_unit' @@ -91,7 +90,7 @@ module ApplicationTests create_test_file :controllers, 'foo_controller' create_test_file :controllers, 'bar_controller' create_test_file :models, 'foo' - run_test_controllers_command.tap do |output| + run_test_command("test/controllers").tap do |output| assert_match "FooControllerTest", output assert_match "BarControllerTest", output assert_match "2 runs, 2 assertions, 0 failures", output @@ -102,7 +101,7 @@ module ApplicationTests create_test_file :mailers, 'foo_mailer' create_test_file :mailers, 'bar_mailer' create_test_file :models, 'foo' - run_test_mailers_command.tap do |output| + run_test_command("test/mailers").tap do |output| assert_match "FooMailerTest", output assert_match "BarMailerTest", output assert_match "2 runs, 2 assertions, 0 failures", output @@ -113,7 +112,7 @@ module ApplicationTests create_test_file :jobs, 'foo_job' create_test_file :jobs, 'bar_job' create_test_file :models, 'foo' - run_test_jobs_command.tap do |output| + run_test_command("test/jobs").tap do |output| assert_match "FooJobTest", output assert_match "BarJobTest", output assert_match "2 runs, 2 assertions, 0 failures", output @@ -121,6 +120,7 @@ module ApplicationTests end def test_run_functionals + skip "we no longer have the concept of functional tests. Just different directories..." create_test_file :mailers, 'foo_mailer' create_test_file :controllers, 'bar_controller' create_test_file :functional, 'baz_functional' @@ -136,7 +136,7 @@ module ApplicationTests def test_run_integration create_test_file :integration, 'foo_integration' create_test_file :models, 'foo' - run_test_integration_command.tap do |output| + run_test_command("test/integration").tap do |output| assert_match "FooIntegration", output assert_match "1 runs, 1 assertions, 0 failures", output end @@ -166,7 +166,7 @@ module ApplicationTests end RUBY - run_test_command('test/unit/chu_2_koi_test.rb test_rikka').tap do |output| + run_test_command('-n test_rikka test/unit/chu_2_koi_test.rb').tap do |output| assert_match "Rikka", output assert_no_match "Sanae", output end @@ -187,7 +187,7 @@ module ApplicationTests end RUBY - run_test_command('test/unit/chu_2_koi_test.rb /rikka/').tap do |output| + run_test_command('-p rikka test/unit/chu_2_koi_test.rb').tap do |output| assert_match "Rikka", output assert_no_match "Sanae", output end @@ -195,18 +195,18 @@ module ApplicationTests def test_load_fixtures_when_running_test_suites create_model_with_fixture - suites = [:models, :helpers, [:units, :unit], :controllers, :mailers, - [:functionals, :functional], :integration] + suites = [:models, :helpers, :controllers, :mailers, :integration] suites.each do |suite, directory| directory ||= suite create_fixture_test directory - assert_match "3 users", run_task(["test:#{suite}"]) + assert_match "3 users", run_test_command("test/#{suite}") Dir.chdir(app_path) { FileUtils.rm_f "test/#{directory}" } end end def test_run_with_model + skip "These feel a bit odd. Not sure we should keep supporting them." create_model_with_fixture create_fixture_test 'models', 'user' assert_match "3 users", run_task(["test models/user"]) @@ -214,6 +214,7 @@ module ApplicationTests end def test_run_different_environment_using_env_var + skip "no longer possible. Running tests in a different environment should be explicit" app_file 'test/unit/env_test.rb', <<-RUBY require 'test_helper' @@ -228,7 +229,7 @@ module ApplicationTests assert_match "development", run_test_command('test/unit/env_test.rb') end - def test_run_different_environment_using_e_tag + def test_run_different_environment env = "development" app_file 'test/unit/env_test.rb', <<-RUBY require 'test_helper' @@ -240,7 +241,7 @@ module ApplicationTests end RUBY - assert_match env, run_test_command("test/unit/env_test.rb RAILS_ENV=#{env}") + assert_match env, run_test_command("-e #{env} test/unit/env_test.rb") end def test_generated_scaffold_works_with_rails_test @@ -249,17 +250,8 @@ module ApplicationTests end private - def run_task(tasks) - Dir.chdir(app_path) { `bundle exec rake #{tasks.join ' '}` } - end - def run_test_command(arguments = 'test/unit/test_test.rb') - run_task ['test', arguments] - end - %w{ mailers models helpers units controllers functionals integration jobs }.each do |type| - define_method("run_test_#{type}_command") do - run_task ["test:#{type}"] - end + Dir.chdir(app_path) { `bin/rails t #{arguments}` } end def create_model_with_fixture @@ -296,15 +288,6 @@ module ApplicationTests app_file 'db/schema.rb', '' end - def redirect_stderr(target_stream) - previous_stderr = STDERR.dup - $stderr.reopen(target_stream) - yield - target_stream.rewind - ensure - $stderr = previous_stderr - end - def create_test_file(path = :unit, name = 'test') app_file "test/#{path}/#{name}_test.rb", <<-RUBY require 'test_helper' diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb index c7132837b1..bb30940a74 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 @@ -65,6 +65,7 @@ module ApplicationTests 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 end test "ruby schema migrations" do @@ -300,23 +301,7 @@ Expected: ["id", "name"] end def run_test_file(name, options = {}) - ruby '-Itest', "#{app_path}/test/#{name}", options.deep_merge(env: {"RAILS_ENV" => "test"}) - end - - def ruby(*args) - options = args.extract_options! - env = options.fetch(:env, {}) - env["RUBYLIB"] = $:.join(':') - - Dir.chdir(app_path) do - `#{env_string(env)} #{Gem.ruby} #{args.join(' ')} 2>&1` - end - end - - def env_string(variables) - variables.map do |key, value| - "#{key}='#{value}'" - end.join " " + Dir.chdir(app_path) { `bin/rails test "#{app_path}/test/#{name}" 2>&1` } end end end diff --git a/railties/test/application/url_generation_test.rb b/railties/test/application/url_generation_test.rb index ef16ab56ed..894e18cb39 100644 --- a/railties/test/application/url_generation_test.rb +++ b/railties/test/application/url_generation_test.rb @@ -42,5 +42,18 @@ module ApplicationTests get "/" assert_equal "/", last_response.body end + + def test_routes_know_the_relative_root + boot_rails + require "rails" + require "action_controller/railtie" + require "action_view/railtie" + + relative_url = '/hello' + ENV["RAILS_RELATIVE_URL_ROOT"] = relative_url + app = Class.new(Rails::Application) + assert_equal relative_url, app.routes.relative_url_root + ENV["RAILS_RELATIVE_URL_ROOT"] = nil + end end end diff --git a/railties/test/code_statistics_test.rb b/railties/test/code_statistics_test.rb new file mode 100644 index 0000000000..1b1ff80bc1 --- /dev/null +++ b/railties/test/code_statistics_test.rb @@ -0,0 +1,20 @@ +require 'abstract_unit' +require 'rails/code_statistics' + +class CodeStatisticsTest < ActiveSupport::TestCase + def setup + @tmp_path = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'tmp')) + @dir_js = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'tmp', 'lib.js')) + FileUtils.mkdir_p(@dir_js) + end + + def teardown + FileUtils.rm_rf(@tmp_path) + end + + test 'ignores directories that happen to have source files extensions' do + assert_nothing_raised do + @code_statistics = CodeStatistics.new(['tmp dir', @tmp_path]) + end + end +end diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb index a3cd1eb0ed..7950ed6aa7 100644 --- a/railties/test/commands/dbconsole_test.rb +++ b/railties/test/commands/dbconsole_test.rb @@ -99,19 +99,15 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase end def test_rails_env_is_development_when_argument_is_dev - dbconsole = Rails::DBConsole.new - - dbconsole.stub(:available_environments, ['development', 'test']) do - options = dbconsole.send(:parse_arguments, ['dev']) + Rails::DBConsole.stub(:available_environments, ['development', 'test']) do + options = Rails::DBConsole.send(:parse_arguments, ['dev']) assert_match('development', options[:environment]) end end def test_rails_env_is_dev_when_argument_is_dev_and_dev_env_is_present - dbconsole = Rails::DBConsole.new - - dbconsole.stub(:available_environments, ['dev']) do - options = dbconsole.send(:parse_arguments, ['dev']) + Rails::DBConsole.stub(:available_environments, ['dev']) do + options = Rails::DBConsole.send(:parse_arguments, ['dev']) assert_match('dev', options[:environment]) end end @@ -158,12 +154,6 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase assert_equal 'q1w2e3', ENV['PGPASSWORD'] end - def test_sqlite - start(adapter: 'sqlite', database: 'db') - assert !aborted - assert_equal ['sqlite', 'db'], dbconsole.find_cmd_and_exec_args - end - def test_sqlite3 start(adapter: 'sqlite3', database: 'db.sqlite3') assert !aborted diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb index c4b6441397..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 @@ -219,17 +240,45 @@ class ActionsTest < Rails::Generators::TestCase assert_file 'config/routes.rb', /#{Regexp.escape(route_command)}/ end + def test_route_should_add_data_with_an_new_line + run_generator + action :route, "root 'welcome#index'" + route_path = File.expand_path("config/routes.rb", destination_root) + content = File.read(route_path) + + # Remove all of the comments and blank lines from the routes file + content.gsub!(/^ \#.*\n/, '') + content.gsub!(/^\n/, '') + + File.open(route_path, "wb") { |file| file.write(content) } + assert_file "config/routes.rb", /\.routes\.draw do\n root 'welcome#index'\nend\n\z/ + + action :route, "resources :product_lines" + + routes = <<-F +Rails.application.routes.draw do + resources :product_lines + root 'welcome#index' +end +F + assert_file "config/routes.rb", routes + end + 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.rdoc") + 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.rdoc") + 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/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 5d270555ed..af1c05cab1 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -5,7 +5,7 @@ require 'mocha/setup' # FIXME: stop using mocha DEFAULT_APP_FILES = %w( .gitignore - README.rdoc + README.md Gemfile Rakefile config.ru @@ -18,6 +18,7 @@ DEFAULT_APP_FILES = %w( app/mailers app/models app/models/concerns + app/jobs app/views/layouts bin/bundle bin/rails @@ -33,6 +34,7 @@ DEFAULT_APP_FILES = %w( log test/test_helper.rb test/fixtures + test/fixtures/files test/controllers test/models test/helpers @@ -42,6 +44,7 @@ DEFAULT_APP_FILES = %w( vendor/assets vendor/assets/stylesheets vendor/assets/javascripts + tmp tmp/cache tmp/cache/assets ) @@ -66,6 +69,11 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file("app/assets/javascripts/application.js") end + def test_application_job_file_present + run_generator + assert_file("app/jobs/application_job.rb") + end + def test_invalid_application_name_raises_an_error content = capture(:stderr){ run_generator [File.join(destination_root, "43-things")] } assert_equal "Invalid application name 43-things. Please give a name which does not start with numbers.\n", content @@ -208,6 +216,38 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file("#{app_root}/config/initializers/cookies_serializer.rb", /Rails\.application\.config\.action_dispatch\.cookies_serializer = :marshal/) end + def test_rails_update_does_not_create_active_record_belongs_to_required_by_default + app_root = File.join(destination_root, 'myapp') + run_generator [app_root] + + FileUtils.rm("#{app_root}/config/initializers/active_record_belongs_to_required_by_default.rb") + + Rails.application.config.root = app_root + Rails.application.class.stubs(:name).returns("Myapp") + Rails.application.stubs(:is_a?).returns(Rails::Application) + + generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, destination_root: app_root, shell: @shell + generator.send(:app_const) + quietly { generator.send(:update_config_files) } + assert_no_file "#{app_root}/config/initializers/active_record_belongs_to_required_by_default.rb" + end + + def test_rails_update_does_not_remove_active_record_belongs_to_required_by_default_if_already_present + app_root = File.join(destination_root, 'myapp') + run_generator [app_root] + + FileUtils.touch("#{app_root}/config/initializers/active_record_belongs_to_required_by_default.rb") + + Rails.application.config.root = app_root + Rails.application.class.stubs(:name).returns("Myapp") + Rails.application.stubs(:is_a?).returns(Rails::Application) + + generator = Rails::Generators::AppGenerator.new ["rails"], { with_dispatchers: true }, destination_root: app_root, shell: @shell + generator.send(:app_const) + quietly { generator.send(:update_config_files) } + assert_file "#{app_root}/config/initializers/active_record_belongs_to_required_by_default.rb" + end + def test_application_names_are_not_singularized run_generator [File.join(destination_root, "hats")] assert_file "hats/config/environment.rb", /Rails\.application\.initialize!/ @@ -308,6 +348,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_generator_if_skip_active_record_is_given run_generator [destination_root, "--skip-active-record"] assert_no_file "config/database.yml" + assert_no_file "config/initializers/active_record_belongs_to_required_by_default.rb" assert_file "config/application.rb", /#\s+require\s+["']active_record\/railtie["']/ assert_file "test/test_helper.rb" do |helper_content| assert_no_match(/fixtures :all/, helper_content) @@ -409,18 +450,6 @@ class AppGeneratorTest < Rails::Generators::TestCase end end - def test_inclusion_of_method_source - run_generator - assert_file "Gemfile" do |content| - assert_gem 'method_source' - end - end - - def test_inclusion_of_doc - run_generator - assert_file 'Gemfile', /gem 'sdoc',\s+'~> 0.4.0',\s+group: :doc/ - end - def test_template_from_dir_pwd FileUtils.cd(Rails.root) assert_match(/It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"])) @@ -445,13 +474,13 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_file 'lib/test_file.rb', 'heres test data' end - def test_test_unit_is_removed_from_frameworks_if_skip_test_unit_is_given - run_generator [destination_root, "--skip-test-unit"] + def test_tests_are_removed_from_frameworks_if_skip_test_is_given + run_generator [destination_root, "--skip-test"] assert_file "config/application.rb", /#\s+require\s+["']rails\/test_unit\/railtie["']/ end - def test_no_active_record_or_test_unit_if_skips_given - run_generator [destination_root, "--skip-test-unit", "--skip-active-record"] + def test_no_active_record_or_tests_if_skips_given + run_generator [destination_root, "--skip-test", "--skip-active-record"] assert_file "config/application.rb", /#\s+require\s+["']rails\/test_unit\/railtie["']/ assert_file "config/application.rb", /#\s+require\s+["']active_record\/railtie["']/ assert_file "config/application.rb", /\s+require\s+["']active_job\/railtie["']/ @@ -532,6 +561,14 @@ class AppGeneratorTest < Rails::Generators::TestCase end end + def test_spring_with_dev_option + run_generator [destination_root, "--dev"] + + assert_file "Gemfile" do |content| + assert_no_match(/spring/, content) + end + end + def test_generator_if_skip_turbolinks_is_given run_generator [destination_root, "--skip-turbolinks"] @@ -570,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/controller_generator_test.rb b/railties/test/generators/controller_generator_test.rb index a7d56dd352..1351151afb 100644 --- a/railties/test/generators/controller_generator_test.rb +++ b/railties/test/generators/controller_generator_test.rb @@ -96,6 +96,8 @@ class ControllerGeneratorTest < Rails::Generators::TestCase def test_namespaced_routes_are_created_in_routes run_generator ["admin/dashboard", "index"] - assert_file "config/routes.rb", /namespace :admin do\n\s+get 'dashboard\/index'\n/ + assert_file "config/routes.rb" do |route| + assert_match(/^ namespace :admin do\n get 'dashboard\/index'\n end$/, route) + end end end diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb index 7c5183e6c8..62ca0ecb4b 100644 --- a/railties/test/generators/generators_test_helper.rb +++ b/railties/test/generators/generators_test_helper.rb @@ -1,5 +1,6 @@ require 'abstract_unit' require 'active_support/core_ext/module/remove_method' +require 'active_support/testing/stream' require 'rails/generators' require 'rails/generators/test_case' @@ -23,6 +24,8 @@ require 'action_dispatch' require 'action_view' module GeneratorsTestHelper + include ActiveSupport::Testing::Stream + def self.included(base) base.class_eval do destination File.join(Rails.root, "tmp") @@ -42,21 +45,4 @@ module GeneratorsTestHelper FileUtils.cp routes, destination end - def quietly - silence_stream(STDOUT) do - silence_stream(STDERR) do - yield - end - end - end - - def silence_stream(stream) - old_stream = stream.dup - stream.reopen(IO::NULL) - stream.sync = true - yield - ensure - stream.reopen(old_stream) - old_stream.close - end end diff --git a/railties/test/generators/job_generator_test.rb b/railties/test/generators/job_generator_test.rb index a9e0cea94f..7fd8f2062f 100644 --- a/railties/test/generators/job_generator_test.rb +++ b/railties/test/generators/job_generator_test.rb @@ -7,14 +7,14 @@ class JobGeneratorTest < Rails::Generators::TestCase def test_job_skeleton_is_created run_generator ["refresh_counters"] assert_file "app/jobs/refresh_counters_job.rb" do |job| - assert_match(/class RefreshCountersJob < ActiveJob::Base/, job) + assert_match(/class RefreshCountersJob < ApplicationJob/, job) end end def test_job_queue_param run_generator ["refresh_counters", "--queue", "important"] assert_file "app/jobs/refresh_counters_job.rb" do |job| - assert_match(/class RefreshCountersJob < ActiveJob::Base/, job) + assert_match(/class RefreshCountersJob < ApplicationJob/, job) assert_match(/queue_as :important/, job) end end @@ -22,7 +22,7 @@ class JobGeneratorTest < Rails::Generators::TestCase def test_job_namespace run_generator ["admin/refresh_counters", "--queue", "admin"] assert_file "app/jobs/admin/refresh_counters_job.rb" do |job| - assert_match(/class Admin::RefreshCountersJob < ActiveJob::Base/, job) + assert_match(/class Admin::RefreshCountersJob < ApplicationJob/, job) assert_match(/queue_as :admin/, job) end end diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb index febd2fd12e..f01e8cd2d9 100644 --- a/railties/test/generators/mailer_generator_test.rb +++ b/railties/test/generators/mailer_generator_test.rb @@ -47,13 +47,13 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_match(/test "bar"/, test) end assert_file "test/mailers/previews/notifier_mailer_preview.rb" do |preview| - assert_match(/\# Preview all emails at http:\/\/localhost\:3000\/rails\/mailers\/notifier/, preview) + assert_match(/\# Preview all emails at http:\/\/localhost\:3000\/rails\/mailers\/notifier_mailer/, preview) assert_match(/class NotifierMailerPreview < ActionMailer::Preview/, preview) - assert_match(/\# Preview this email at http:\/\/localhost\:3000\/rails\/mailers\/notifier\/foo/, preview) + assert_match(/\# Preview this email at http:\/\/localhost\:3000\/rails\/mailers\/notifier_mailer\/foo/, preview) assert_instance_method :foo, preview do |foo| assert_match(/NotifierMailer.foo/, foo) end - assert_match(/\# Preview this email at http:\/\/localhost\:3000\/rails\/mailers\/notifier\/bar/, preview) + assert_match(/\# Preview this email at http:\/\/localhost\:3000\/rails\/mailers\/notifier_mailer\/bar/, preview) assert_instance_method :bar, preview do |bar| assert_match(/NotifierMailer.bar/, bar) end @@ -78,13 +78,13 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_invokes_default_text_template_engine run_generator - assert_file "app/views/notifier/foo.text.erb" do |view| - assert_match(%r(\sapp/views/notifier/foo\.text\.erb), view) + assert_file "app/views/notifier_mailer/foo.text.erb" do |view| + assert_match(%r(\sapp/views/notifier_mailer/foo\.text\.erb), view) assert_match(/<%= @greeting %>/, view) end - assert_file "app/views/notifier/bar.text.erb" do |view| - assert_match(%r(\sapp/views/notifier/bar\.text\.erb), view) + assert_file "app/views/notifier_mailer/bar.text.erb" do |view| + assert_match(%r(\sapp/views/notifier_mailer/bar\.text\.erb), view) assert_match(/<%= @greeting %>/, view) end @@ -95,13 +95,13 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_invokes_default_html_template_engine run_generator - assert_file "app/views/notifier/foo.html.erb" do |view| - assert_match(%r(\sapp/views/notifier/foo\.html\.erb), view) + assert_file "app/views/notifier_mailer/foo.html.erb" do |view| + assert_match(%r(\sapp/views/notifier_mailer/foo\.html\.erb), view) assert_match(/<%= @greeting %>/, view) end - assert_file "app/views/notifier/bar.html.erb" do |view| - assert_match(%r(\sapp/views/notifier/bar\.html\.erb), view) + assert_file "app/views/notifier_mailer/bar.html.erb" do |view| + assert_match(%r(\sapp/views/notifier_mailer/bar\.html\.erb), view) assert_match(/<%= @greeting %>/, view) end @@ -112,7 +112,7 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_invokes_default_template_engine_even_with_no_action run_generator ["notifier"] - assert_file "app/views/notifier" + assert_file "app/views/notifier_mailer" assert_file "app/views/layouts/mailer.text.erb" assert_file "app/views/layouts/mailer.html.erb" end @@ -129,12 +129,12 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_match(/en\.farm\.animal_mailer\.moos\.subject/, mailer) end assert_file "test/mailers/previews/farm/animal_mailer_preview.rb" do |preview| - assert_match(/\# Preview all emails at http:\/\/localhost\:3000\/rails\/mailers\/farm\/animal/, preview) + assert_match(/\# Preview all emails at http:\/\/localhost\:3000\/rails\/mailers\/farm\/animal_mailer/, preview) assert_match(/class Farm::AnimalMailerPreview < ActionMailer::Preview/, preview) - assert_match(/\# Preview this email at http:\/\/localhost\:3000\/rails\/mailers\/farm\/animal\/moos/, preview) + assert_match(/\# Preview this email at http:\/\/localhost\:3000\/rails\/mailers\/farm\/animal_mailer\/moos/, preview) end - assert_file "app/views/farm/animal/moos.text.erb" - assert_file "app/views/farm/animal/moos.html.erb" + assert_file "app/views/farm/animal_mailer/moos.text.erb" + assert_file "app/views/farm/animal_mailer/moos.html.erb" end def test_actions_are_turned_into_methods @@ -173,5 +173,14 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_no_file "app/mailers/notifier_mailer_mailer.rb" assert_file "app/mailers/notifier_mailer.rb" + + assert_no_file "app/views/notifier_mailer_mailer/" + assert_file "app/views/notifier_mailer/" + + assert_no_file "test/mailers/notifier_mailer_mailer_test.rb" + assert_file "test/mailers/notifier_mailer_test.rb" + + assert_no_file "test/mailers/previews/notifier_mailer_mailer_preview.rb" + assert_file "test/mailers/previews/notifier_mailer_preview.rb" end end diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb index 17a13fbf1f..abd3ff50a4 100644 --- a/railties/test/generators/model_generator_test.rb +++ b/railties/test/generators/model_generator_test.rb @@ -319,6 +319,16 @@ class ModelGeneratorTest < Rails::Generators::TestCase assert_no_file "test/fixtures/accounts.yml" end + def test_fixture_without_pluralization + original_pluralize_table_name = ActiveRecord::Base.pluralize_table_names + ActiveRecord::Base.pluralize_table_names = false + run_generator + assert_generated_fixture("test/fixtures/account.yml", + {"one"=>{"name"=>"MyString", "age"=>1}, "two"=>{"name"=>"MyString", "age"=>1}}) + ensure + ActiveRecord::Base.pluralize_table_names = original_pluralize_table_name + end + def test_check_class_collision content = capture(:stderr){ run_generator ["object"] } assert_match(/The name 'Object' is either already used in your application or reserved/, content) diff --git a/railties/test/generators/named_base_test.rb b/railties/test/generators/named_base_test.rb index 4199e00b0d..1c32fc1bfd 100644 --- a/railties/test/generators/named_base_test.rb +++ b/railties/test/generators/named_base_test.rb @@ -1,16 +1,6 @@ require 'generators/generators_test_helper' require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator' -require 'mocha/setup' # FIXME: stop using mocha - -# Mock out what we need from AR::Base. -module ActiveRecord - class Base - class << self - attr_accessor :pluralize_table_names - end - self.pluralize_table_names = true - end -end +require 'minitest/mock' class NamedBaseTest < Rails::Generators::TestCase include GeneratorsTestHelper @@ -59,11 +49,13 @@ class NamedBaseTest < Rails::Generators::TestCase end def test_named_generator_attributes_without_pluralized + original_pluralize_table_names = ActiveRecord::Base.pluralize_table_names ActiveRecord::Base.pluralize_table_names = false + g = generator ['admin/foo'] assert_name g, 'admin_foo', :table_name ensure - ActiveRecord::Base.pluralize_table_names = true + ActiveRecord::Base.pluralize_table_names = original_pluralize_table_names end def test_scaffold_plural_names @@ -88,10 +80,13 @@ class NamedBaseTest < Rails::Generators::TestCase def test_application_name g = generator ['Admin::Foo'] - Rails.stubs(:application).returns(Object.new) - assert_name g, "object", :application_name - Rails.stubs(:application).returns(nil) - assert_name g, "application", :application_name + Rails.stub(:application, Object.new) do + assert_name g, "object", :application_name + end + + Rails.stub(:application, nil) do + assert_name g, "application", :application_name + end end def test_index_helper @@ -111,11 +106,11 @@ class NamedBaseTest < Rails::Generators::TestCase def test_hide_namespace g = generator ['Hidden'] - g.class.stubs(:namespace).returns('hidden') - - assert !Rails::Generators.hidden_namespaces.include?('hidden') - g.class.hide! - assert Rails::Generators.hidden_namespaces.include?('hidden') + g.class.stub(:namespace, 'hidden') do + assert !Rails::Generators.hidden_namespaces.include?('hidden') + g.class.hide! + assert Rails::Generators.hidden_namespaces.include?('hidden') + end end def test_scaffold_plural_names_with_model_name_option diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb index d0ea01dfb0..e839b67960 100644 --- a/railties/test/generators/namespaced_generators_test.rb +++ b/railties/test/generators/namespaced_generators_test.rb @@ -173,20 +173,20 @@ class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase def test_invokes_default_template_engine run_generator - assert_file "app/views/test_app/notifier/foo.text.erb" do |view| - assert_match(%r(app/views/test_app/notifier/foo\.text\.erb), view) + assert_file "app/views/test_app/notifier_mailer/foo.text.erb" do |view| + assert_match(%r(app/views/test_app/notifier_mailer/foo\.text\.erb), view) assert_match(/<%= @greeting %>/, view) end - assert_file "app/views/test_app/notifier/bar.text.erb" do |view| - assert_match(%r(app/views/test_app/notifier/bar\.text\.erb), view) + assert_file "app/views/test_app/notifier_mailer/bar.text.erb" do |view| + assert_match(%r(app/views/test_app/notifier_mailer/bar\.text\.erb), view) assert_match(/<%= @greeting %>/, view) end end def test_invokes_default_template_engine_even_with_no_action run_generator ["notifier"] - assert_file "app/views/test_app/notifier" + assert_file "app/views/test_app/notifier_mailer" end end diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb index 318ea5b2cb..d6e5f4bd89 100644 --- a/railties/test/generators/plugin_generator_test.rb +++ b/railties/test/generators/plugin_generator_test.rb @@ -28,23 +28,30 @@ class PluginGeneratorTest < Rails::Generators::TestCase include SharedGeneratorTests def test_invalid_plugin_name_raises_an_error - content = capture(:stderr){ run_generator [File.join(destination_root, "things-43")] } - assert_equal "Invalid plugin name things-43. Please give a name which use only alphabetic or numeric or \"_\" characters.\n", content + content = capture(:stderr){ run_generator [File.join(destination_root, "my_plugin-31fr-extension")] } + assert_equal "Invalid plugin name my_plugin-31fr-extension. Please give a name which does not contain a namespace starting with numeric characters.\n", content content = capture(:stderr){ run_generator [File.join(destination_root, "things4.3")] } - assert_equal "Invalid plugin name things4.3. Please give a name which use only alphabetic or numeric or \"_\" characters.\n", content + assert_equal "Invalid plugin name things4.3. Please give a name which uses only alphabetic, numeric, \"_\" or \"-\" characters.\n", content content = capture(:stderr){ run_generator [File.join(destination_root, "43things")] } assert_equal "Invalid plugin name 43things. Please give a name which does not start with numbers.\n", content content = capture(:stderr){ run_generator [File.join(destination_root, "plugin")] } - assert_equal "Invalid plugin name plugin. Please give a name which does not match one of the reserved rails words.\n", content + assert_equal "Invalid plugin name plugin. Please give a name which does not match one of the reserved rails words: [\"application\", \"destroy\", \"plugin\", \"runner\", \"test\"]\n", content content = capture(:stderr){ run_generator [File.join(destination_root, "Digest")] } assert_equal "Invalid plugin name Digest, constant Digest is already in use. Please choose another plugin name.\n", content end - def test_camelcase_plugin_name_underscores_filenames + def test_correct_file_in_lib_folder_of_hyphenated_plugin_name + run_generator [File.join(destination_root, "hyphenated-name")] + assert_no_file "hyphenated-name/lib/hyphenated-name.rb" + assert_no_file "hyphenated-name/lib/hyphenated_name.rb" + assert_file "hyphenated-name/lib/hyphenated/name.rb", /module Hyphenated\n module Name\n # Your code goes here...\n end\nend/ + end + + def test_correct_file_in_lib_folder_of_camelcase_plugin_name run_generator [File.join(destination_root, "CamelCasedName")] assert_no_file "CamelCasedName/lib/CamelCasedName.rb" assert_file "CamelCasedName/lib/camel_cased_name.rb", /module CamelCasedName/ @@ -112,7 +119,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase def test_ensure_that_test_dummy_can_be_generated_from_a_template FileUtils.cd(Rails.root) - run_generator([destination_root, "-m", "lib/create_test_dummy_template.rb", "--skip-test-unit"]) + run_generator([destination_root, "-m", "lib/create_test_dummy_template.rb", "--skip-test"]) assert_file "spec/dummy" assert_no_file "test" end @@ -185,13 +192,11 @@ class PluginGeneratorTest < Rails::Generators::TestCase def test_generation_runs_bundle_install_with_full_and_mountable result = run_generator [destination_root, "--mountable", "--full", "--dev"] + assert_match(/run bundle install/, result) + assert $?.success?, "Command failed: #{result}" assert_file "#{destination_root}/Gemfile.lock" do |contents| assert_match(/bukkits/, contents) end - assert_match(/run bundle install/, result) - assert_match(/Using bukkits \(?0\.0\.1\)?/, result) - assert_match(/Your bundle is complete/, result) - assert_equal 1, result.scan("Your bundle is complete").size end def test_skipping_javascripts_without_mountable_option @@ -252,6 +257,40 @@ class PluginGeneratorTest < Rails::Generators::TestCase assert_file "lib/bukkits.rb", /require "bukkits\/engine"/ end + def test_creating_engine_with_hyphenated_name_in_full_mode + run_generator [File.join(destination_root, "hyphenated-name"), "--full"] + assert_file "hyphenated-name/app/assets/javascripts/hyphenated/name" + assert_file "hyphenated-name/app/assets/stylesheets/hyphenated/name" + assert_file "hyphenated-name/app/assets/images/hyphenated/name" + assert_file "hyphenated-name/app/models" + assert_file "hyphenated-name/app/controllers" + assert_file "hyphenated-name/app/views" + assert_file "hyphenated-name/app/helpers" + assert_file "hyphenated-name/app/mailers" + assert_file "hyphenated-name/bin/rails" + assert_file "hyphenated-name/config/routes.rb", /Rails.application.routes.draw do/ + assert_file "hyphenated-name/lib/hyphenated/name/engine.rb", /module Hyphenated\n module Name\n class Engine < ::Rails::Engine\n end\n end\nend/ + assert_file "hyphenated-name/lib/hyphenated/name.rb", /require "hyphenated\/name\/engine"/ + assert_file "hyphenated-name/bin/rails", /\.\.\/\.\.\/lib\/hyphenated\/name\/engine/ + end + + def test_creating_engine_with_hyphenated_and_underscored_name_in_full_mode + run_generator [File.join(destination_root, "my_hyphenated-name"), "--full"] + assert_file "my_hyphenated-name/app/assets/javascripts/my_hyphenated/name" + assert_file "my_hyphenated-name/app/assets/stylesheets/my_hyphenated/name" + assert_file "my_hyphenated-name/app/assets/images/my_hyphenated/name" + assert_file "my_hyphenated-name/app/models" + assert_file "my_hyphenated-name/app/controllers" + assert_file "my_hyphenated-name/app/views" + assert_file "my_hyphenated-name/app/helpers" + assert_file "my_hyphenated-name/app/mailers" + assert_file "my_hyphenated-name/bin/rails" + assert_file "my_hyphenated-name/config/routes.rb", /Rails.application.routes.draw do/ + assert_file "my_hyphenated-name/lib/my_hyphenated/name/engine.rb", /module MyHyphenated\n module Name\n class Engine < ::Rails::Engine\n end\n end\nend/ + assert_file "my_hyphenated-name/lib/my_hyphenated/name.rb", /require "my_hyphenated\/name\/engine"/ + assert_file "my_hyphenated-name/bin/rails", /\.\.\/\.\.\/lib\/my_hyphenated\/name\/engine/ + end + def test_being_quiet_while_creating_dummy_application assert_no_match(/create\s+config\/application.rb/, run_generator) end @@ -277,6 +316,63 @@ class PluginGeneratorTest < Rails::Generators::TestCase end end + def test_create_mountable_application_with_mountable_option_and_hypenated_name + run_generator [File.join(destination_root, "hyphenated-name"), "--mountable"] + assert_file "hyphenated-name/app/assets/javascripts/hyphenated/name" + assert_file "hyphenated-name/app/assets/stylesheets/hyphenated/name" + assert_file "hyphenated-name/app/assets/images/hyphenated/name" + assert_file "hyphenated-name/config/routes.rb", /Hyphenated::Name::Engine.routes.draw do/ + assert_file "hyphenated-name/lib/hyphenated/name/version.rb", /module Hyphenated\n module Name\n VERSION = "0.0.1"\n end\nend/ + assert_file "hyphenated-name/lib/hyphenated/name/engine.rb", /module Hyphenated\n module Name\n class Engine < ::Rails::Engine\n isolate_namespace Hyphenated::Name\n end\n end\nend/ + assert_file "hyphenated-name/lib/hyphenated/name.rb", /require "hyphenated\/name\/engine"/ + assert_file "hyphenated-name/test/dummy/config/routes.rb", /mount Hyphenated::Name::Engine => "\/hyphenated-name"/ + assert_file "hyphenated-name/app/controllers/hyphenated/name/application_controller.rb", /module Hyphenated\n module Name\n class ApplicationController < ActionController::Base\n end\n end\nend/ + assert_file "hyphenated-name/app/helpers/hyphenated/name/application_helper.rb", /module Hyphenated\n module Name\n module ApplicationHelper\n end\n end\nend/ + assert_file "hyphenated-name/app/views/layouts/hyphenated/name/application.html.erb" do |contents| + assert_match "<title>Hyphenated name</title>", contents + assert_match(/stylesheet_link_tag\s+['"]hyphenated\/name\/application['"]/, contents) + assert_match(/javascript_include_tag\s+['"]hyphenated\/name\/application['"]/, contents) + end + end + + def test_create_mountable_application_with_mountable_option_and_hypenated_and_underscored_name + run_generator [File.join(destination_root, "my_hyphenated-name"), "--mountable"] + assert_file "my_hyphenated-name/app/assets/javascripts/my_hyphenated/name" + assert_file "my_hyphenated-name/app/assets/stylesheets/my_hyphenated/name" + assert_file "my_hyphenated-name/app/assets/images/my_hyphenated/name" + assert_file "my_hyphenated-name/config/routes.rb", /MyHyphenated::Name::Engine.routes.draw do/ + assert_file "my_hyphenated-name/lib/my_hyphenated/name/version.rb", /module MyHyphenated\n module Name\n VERSION = "0.0.1"\n end\nend/ + assert_file "my_hyphenated-name/lib/my_hyphenated/name/engine.rb", /module MyHyphenated\n module Name\n class Engine < ::Rails::Engine\n isolate_namespace MyHyphenated::Name\n end\n end\nend/ + assert_file "my_hyphenated-name/lib/my_hyphenated/name.rb", /require "my_hyphenated\/name\/engine"/ + assert_file "my_hyphenated-name/test/dummy/config/routes.rb", /mount MyHyphenated::Name::Engine => "\/my_hyphenated-name"/ + assert_file "my_hyphenated-name/app/controllers/my_hyphenated/name/application_controller.rb", /module MyHyphenated\n module Name\n class ApplicationController < ActionController::Base\n end\n end\nend/ + assert_file "my_hyphenated-name/app/helpers/my_hyphenated/name/application_helper.rb", /module MyHyphenated\n module Name\n module ApplicationHelper\n end\n end\nend/ + assert_file "my_hyphenated-name/app/views/layouts/my_hyphenated/name/application.html.erb" do |contents| + assert_match "<title>My hyphenated name</title>", contents + assert_match(/stylesheet_link_tag\s+['"]my_hyphenated\/name\/application['"]/, contents) + assert_match(/javascript_include_tag\s+['"]my_hyphenated\/name\/application['"]/, contents) + end + end + + def test_create_mountable_application_with_mountable_option_and_multiple_hypenates_in_name + run_generator [File.join(destination_root, "deep-hyphenated-name"), "--mountable"] + assert_file "deep-hyphenated-name/app/assets/javascripts/deep/hyphenated/name" + assert_file "deep-hyphenated-name/app/assets/stylesheets/deep/hyphenated/name" + assert_file "deep-hyphenated-name/app/assets/images/deep/hyphenated/name" + assert_file "deep-hyphenated-name/config/routes.rb", /Deep::Hyphenated::Name::Engine.routes.draw do/ + assert_file "deep-hyphenated-name/lib/deep/hyphenated/name/version.rb", /module Deep\n module Hyphenated\n module Name\n VERSION = "0.0.1"\n end\n end\nend/ + assert_file "deep-hyphenated-name/lib/deep/hyphenated/name/engine.rb", /module Deep\n module Hyphenated\n module Name\n class Engine < ::Rails::Engine\n isolate_namespace Deep::Hyphenated::Name\n end\n end\n end\nend/ + assert_file "deep-hyphenated-name/lib/deep/hyphenated/name.rb", /require "deep\/hyphenated\/name\/engine"/ + assert_file "deep-hyphenated-name/test/dummy/config/routes.rb", /mount Deep::Hyphenated::Name::Engine => "\/deep-hyphenated-name"/ + assert_file "deep-hyphenated-name/app/controllers/deep/hyphenated/name/application_controller.rb", /module Deep\n module Hyphenated\n module Name\n class ApplicationController < ActionController::Base\n end\n end\n end\nend/ + assert_file "deep-hyphenated-name/app/helpers/deep/hyphenated/name/application_helper.rb", /module Deep\n module Hyphenated\n module Name\n module ApplicationHelper\n end\n end\n end\nend/ + assert_file "deep-hyphenated-name/app/views/layouts/deep/hyphenated/name/application.html.erb" do |contents| + assert_match "<title>Deep hyphenated name</title>", contents + assert_match(/stylesheet_link_tag\s+['"]deep\/hyphenated\/name\/application['"]/, contents) + assert_match(/javascript_include_tag\s+['"]deep\/hyphenated\/name\/application['"]/, contents) + end + end + def test_creating_gemspec run_generator assert_file "bukkits.gemspec", /s.name\s+= "bukkits"/ @@ -321,7 +417,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase end def test_creating_dummy_without_tests_but_with_dummy_path - run_generator [destination_root, "--dummy_path", "spec/dummy", "--skip-test-unit"] + run_generator [destination_root, "--dummy_path", "spec/dummy", "--skip-test"] assert_file "spec/dummy" assert_file "spec/dummy/config/application.rb" assert_no_file "test" @@ -333,14 +429,14 @@ class PluginGeneratorTest < Rails::Generators::TestCase def test_ensure_that_gitignore_can_be_generated_from_a_template_for_dummy_path FileUtils.cd(Rails.root) - run_generator([destination_root, "--dummy_path", "spec/dummy", "--skip-test-unit"]) + run_generator([destination_root, "--dummy_path", "spec/dummy", "--skip-test"]) assert_file ".gitignore" do |contents| assert_match(/spec\/dummy/, contents) end end - def test_skipping_test_unit - run_generator [destination_root, "--skip-test-unit"] + def test_skipping_test_files + run_generator [destination_root, "--skip-test"] assert_no_file "test" assert_file "bukkits.gemspec" do |contents| assert_no_match(/s.test_files = Dir\["test\/\*\*\/\*"\]/, contents) diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb index ca972a3bdd..7c282377d7 100644 --- a/railties/test/generators/scaffold_controller_generator_test.rb +++ b/railties/test/generators/scaffold_controller_generator_test.rb @@ -106,8 +106,8 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase 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, user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \}/, content) - assert_match(/patch :update, id: @user, user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \}/, 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) end end @@ -117,8 +117,8 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase 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, user: \{ \}/, content) - assert_match(/patch :update, id: @user, user: \{ \}/, content) + assert_match(/post :create, params: \{ user: \{ \} \}/, content) + assert_match(/patch :update, params: \{ id: @user, user: \{ \} \}/, content) end end @@ -174,4 +174,15 @@ 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 end diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb index 3b545328b5..8f43747b9e 100644 --- a/railties/test/generators/scaffold_generator_test.rb +++ b/railties/test/generators/scaffold_generator_test.rb @@ -58,8 +58,8 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase assert_file "test/controllers/product_lines_controller_test.rb" do |test| assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, test) - assert_match(/post :create, product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \}/, test) - assert_match(/patch :update, id: @product_line, product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \}/, 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) end # Views @@ -93,8 +93,8 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase assert_file "test/controllers/product_lines_controller_test.rb" do |content| assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, content) assert_match(/test "should get index"/, content) - assert_match(/post :create, product_line: \{ \}/, content) - assert_match(/patch :update, id: @product_line, product_line: \{ \}/, content) + assert_match(/post :create, params: \{ product_line: \{ \} \}/, content) + assert_match(/patch :update, params: \{ id: @product_line, product_line: \{ \} \}/, content) end end @@ -245,6 +245,29 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase assert_file "config/routes.rb", /\.routes\.draw do\s*\|map\|\s*$/ end + def test_scaffold_generator_on_revoke_does_not_mutilate_routes + run_generator + + route_path = File.expand_path("config/routes.rb", destination_root) + content = File.read(route_path) + + # Remove all of the comments and blank lines from the routes file + content.gsub!(/^ \#.*\n/, '') + content.gsub!(/^\n/, '') + + File.open(route_path, "wb") { |file| file.write(content) } + assert_file "config/routes.rb", /\.routes\.draw do\n resources :product_lines\nend\n\z/ + + run_generator ["product_line"], :behavior => :revoke + + assert_file "config/routes.rb", /\.routes\.draw do\nend\n\z/ + end + + def test_scaffold_generator_ignores_commented_routes + run_generator ["product"] + assert_file "config/routes.rb", /\.routes\.draw do\n resources :products\n/ + end + def test_scaffold_generator_no_assets_with_switch_no_assets run_generator [ "posts", "--no-assets" ] assert_no_file "app/assets/stylesheets/scaffold.css" @@ -370,4 +393,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 b998fef42e..3a2195035f 100644 --- a/railties/test/generators/shared_generator_tests.rb +++ b/railties/test/generators/shared_generator_tests.rb @@ -47,8 +47,8 @@ module SharedGeneratorTests assert_match(/Invalid value for \-\-database option/, content) end - def test_test_unit_is_skipped_if_required - run_generator [destination_root, "--skip-test-unit"] + def test_test_files_are_skipped_if_required + run_generator [destination_root, "--skip-test"] assert_no_file "test" end @@ -56,7 +56,7 @@ module SharedGeneratorTests reserved_words = %w[application destroy plugin runner test] reserved_words.each do |reserved| content = capture(:stderr){ run_generator [File.join(destination_root, reserved)] } - assert_match(/Invalid \w+ name #{reserved}. Please give a name which does not match one of the reserved rails words.\n/, content) + assert_match(/Invalid \w+ name #{reserved}. Please give a name which does not match one of the reserved rails words: \["application", "destroy", "plugin", "runner", "test"\]\n/, content) end end @@ -138,7 +138,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 127e059bf1..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 @@ -34,6 +38,12 @@ class GeneratorsTest < Rails::Generators::TestCase assert_match "Maybe you meant 'migration'", output 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) @@ -41,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 @@ -97,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 @@ -167,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 @@ -176,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/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index 2c4d9c5995..65d8a55421 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -11,6 +11,7 @@ require 'fileutils' require 'bundler/setup' unless defined?(Bundler) require 'active_support' require 'active_support/testing/autorun' +require 'active_support/testing/stream' require 'active_support/test_case' RAILS_FRAMEWORK_ROOT = File.expand_path("#{File.dirname(__FILE__)}/../../..") @@ -269,19 +270,13 @@ module TestHelpers File.open(file, "w+") { |f| f.puts contents } end - def app_file(path, contents) + def app_file(path, contents, mode = 'w') FileUtils.mkdir_p File.dirname("#{app_path}/#{path}") - File.open("#{app_path}/#{path}", 'w') do |f| + File.open("#{app_path}/#{path}", mode) do |f| f.puts contents end end - def gsub_app_file(path, regexp, *args, &block) - path = "#{app_path}/#{path}" - content = File.read(path).gsub(regexp, *args, &block) - File.open(path, 'wb') { |f| f.write(content) } - end - def remove_file(path) FileUtils.rm_rf "#{app_path}/#{path}" end @@ -310,45 +305,10 @@ class ActiveSupport::TestCase include TestHelpers::Paths include TestHelpers::Rack include TestHelpers::Generation + include ActiveSupport::Testing::Stream self.test_order = :sorted - private - - def capture(stream) - stream = stream.to_s - captured_stream = Tempfile.new(stream) - stream_io = eval("$#{stream}") - origin_stream = stream_io.dup - stream_io.reopen(captured_stream) - - yield - - stream_io.rewind - return captured_stream.read - ensure - captured_stream.close - captured_stream.unlink - stream_io.reopen(origin_stream) - end - - def quietly - silence_stream(STDOUT) do - silence_stream(STDERR) do - yield - end - end - end - - def silence_stream(stream) - old_stream = stream.dup - stream.reopen(IO::NULL) - stream.sync = true - yield - ensure - stream.reopen(old_stream) - old_stream.close - end end # Create a scope and build a fixture rails app @@ -362,7 +322,7 @@ Module.new do environment = File.expand_path('../../../../load_paths', __FILE__) require_environment = "-r #{environment}" - `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails new #{app_template_path} --skip-gemfile --no-rc` + `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/exe/rails new #{app_template_path} --skip-gemfile --no-rc` File.open("#{app_template_path}/config/boot.rb", 'w') do |f| f.puts "require '#{environment}'" f.puts "require 'rails/all'" diff --git a/railties/test/path_generation_test.rb b/railties/test/path_generation_test.rb index 13bf29d3c3..27e64b97b7 100644 --- a/railties/test/path_generation_test.rb +++ b/railties/test/path_generation_test.rb @@ -1,22 +1,17 @@ -# encoding: utf-8 require 'abstract_unit' require 'active_support/core_ext/object/with_options' require 'active_support/core_ext/object/json' -require 'rails' -require 'rails/application' - -ROUTING = ActionDispatch::Routing class PathGenerationTest < ActiveSupport::TestCase attr_reader :app - class TestSet < ROUTING::RouteSet + class TestSet < ActionDispatch::Routing::RouteSet def initialize(block) @block = block super() end - class Dispatcher < ROUTING::RouteSet::Dispatcher + class Dispatcher < ActionDispatch::Routing::RouteSet::Dispatcher def initialize(defaults, set, block) super(defaults) @block = block 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/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb index d336a2e6c0..c51503c2b7 100644 --- a/railties/test/rails_info_controller_test.rb +++ b/railties/test/rails_info_controller_test.rb @@ -16,7 +16,7 @@ class InfoControllerTest < ActionController::TestCase end @routes = Rails.application.routes - Rails::InfoController.send(:include, @routes.url_helpers) + Rails::InfoController.include(@routes.url_helpers) @request.env["REMOTE_ADDR"] = "127.0.0.1" end @@ -53,4 +53,29 @@ class InfoControllerTest < ActionController::TestCase assert_response :success end + test "info controller returns exact matches" do + exact_count = -> { JSON(response.body)['exact'].size } + + get :routes, params: { path: 'rails/info/route' } + assert exact_count.call == 0, 'should not match incomplete routes' + + get :routes, params: { path: 'rails/info/routes' } + assert exact_count.call == 1, 'should match complete routes' + + get :routes, params: { path: 'rails/info/routes.html' } + assert exact_count.call == 1, 'should match complete routes with optional parts' + end + + test "info controller returns fuzzy matches" do + fuzzy_count = -> { JSON(response.body)['fuzzy'].size } + + get :routes, params: { path: 'rails/info' } + assert fuzzy_count.call == 2, 'should match incomplete routes' + + get :routes, params: { path: 'rails/info/routes' } + assert fuzzy_count.call == 1, 'should match complete routes' + + get :routes, params: { path: 'rails/info/routes.html' } + assert fuzzy_count.call == 0, 'should match optional parts of route literally' + end end diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb index 6185742cc1..79bd7a8241 100644 --- a/railties/test/railties/engine_test.rb +++ b/railties/test/railties/engine_test.rb @@ -1155,10 +1155,10 @@ YAML assert_equal "App's bar partial", last_response.body.strip get("/assets/foo.js") - assert_equal "// Bukkit's foo js\n;", last_response.body.strip + assert_equal "// Bukkit's foo js", last_response.body.strip get("/assets/bar.js") - assert_equal "// App's bar js\n;", last_response.body.strip + assert_equal "// App's bar js", last_response.body.strip # ensure that railties are not added twice railties = Rails.application.send(:ordered_railties).map(&:class) diff --git a/railties/test/railties/generators_test.rb b/railties/test/railties/generators_test.rb index 7348d70c56..423ece277e 100644 --- a/railties/test/railties/generators_test.rb +++ b/railties/test/railties/generators_test.rb @@ -30,7 +30,7 @@ module RailtiesTests if File.exist?("#{environment}.rb") require_environment = "-r #{environment}" end - `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails #{cmd}` + `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/exe/rails #{cmd}` end def build_engine(is_mountable=false) diff --git a/railties/test/test_info_test.rb b/railties/test/test_info_test.rb deleted file mode 100644 index b9c3a9c0c7..0000000000 --- a/railties/test/test_info_test.rb +++ /dev/null @@ -1,60 +0,0 @@ -require 'abstract_unit' -require 'rails/test_unit/sub_test_task' - -module Rails - class TestInfoTest < ActiveSupport::TestCase - def test_test_files - info = new_test_info ['test'] - assert_predicate info.files, :empty? - assert_nil info.opts - assert_equal ['test'], info.tasks - end - - def test_with_file - info = new_test_info ['test', __FILE__] - assert_equal [__FILE__], info.files - assert_nil info.opts - assert_equal ['test'], info.tasks - end - - def test_with_opts - info = new_test_info ['test', __FILE__, '/foo/'] - assert_equal [__FILE__], info.files - assert_equal '-n /foo/', info.opts - assert_equal ['test'], info.tasks - end - - def test_with_model_shorthand - info = new_test_info ['test', 'models/foo', '/foo/'] - - def info.test_file?(file) - file == "test/models/foo_test.rb" || super - end - - assert_equal ['test/models/foo_test.rb'], info.files - assert_equal '-n /foo/', info.opts - assert_equal ['test'], info.tasks - end - - def test_with_model_path - info = new_test_info ['test', 'app/models/foo.rb', '/foo/'] - - def info.test_file?(file) - file == "test/models/foo_test.rb" || super - end - - assert_equal ['test/models/foo_test.rb'], info.files - assert_equal '-n /foo/', info.opts - assert_equal ['test'], info.tasks - end - - private - def new_test_info(tasks) - Class.new(TestTask::TestInfo) { - def task_defined?(task) - task == "test" - end - }.new tasks - end - end -end diff --git a/railties/test/test_unit/reporter_test.rb b/railties/test/test_unit/reporter_test.rb new file mode 100644 index 0000000000..77883612f5 --- /dev/null +++ b/railties/test/test_unit/reporter_test.rb @@ -0,0 +1,74 @@ +require 'abstract_unit' +require 'rails/test_unit/reporter' + +class TestUnitReporterTest < ActiveSupport::TestCase + class ExampleTest < Minitest::Test + def woot; end + end + + setup do + @output = StringIO.new + @reporter = Rails::TestUnitReporter.new @output + end + + test "prints rerun snippet to run a single failed test" do + @reporter.record(failed_test) + @reporter.report + + assert_match %r{^bin/rails test .*test/test_unit/reporter_test.rb:6$}, @output.string + assert_rerun_snippet_count 1 + end + + test "prints rerun snippet for every failed test" do + @reporter.record(failed_test) + @reporter.record(failed_test) + @reporter.record(failed_test) + @reporter.report + + assert_rerun_snippet_count 3 + end + + test "does not print snippet for successful and skipped tests" do + @reporter.record(passing_test) + @reporter.record(skipped_test) + @reporter.report + assert_rerun_snippet_count 0 + end + + test "prints rerun snippet for skipped tests if run in verbose mode" do + verbose = Rails::TestUnitReporter.new @output, verbose: true + verbose.record(skipped_test) + verbose.report + + assert_rerun_snippet_count 1 + end + + private + def assert_rerun_snippet_count(snippet_count) + assert_equal snippet_count, @output.string.scan(%r{^bin/rails test }).size + end + + def failed_test + ft = ExampleTest.new(:woot) + ft.failures << begin + raise Minitest::Assertion, "boo" + rescue Minitest::Assertion => e + e + end + ft + end + + def passing_test + ExampleTest.new(:woot) + end + + def skipped_test + st = ExampleTest.new(:woot) + st.failures << begin + raise Minitest::Skip + rescue Minitest::Assertion => e + e + end + st + end +end diff --git a/railties/test/test_unit/runner_test.rb b/railties/test/test_unit/runner_test.rb new file mode 100644 index 0000000000..9ea8b2c114 --- /dev/null +++ b/railties/test/test_unit/runner_test.rb @@ -0,0 +1,111 @@ +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 |