diff options
author | Pratik Naik <pratiknaik@gmail.com> | 2009-07-30 14:18:53 +0100 |
---|---|---|
committer | Pratik Naik <pratiknaik@gmail.com> | 2009-07-30 14:18:53 +0100 |
commit | 915cf5747a78f28f2b25c48574031db60c3a18ae (patch) | |
tree | 048746387ddaaed418670c86451856675b8d369f /railties/test | |
parent | 23f5e7e966defaaa1511eca57bd8de47f95cb7d9 (diff) | |
parent | d83b1828577c268de56e1b3942e16002c9efdd57 (diff) | |
download | rails-915cf5747a78f28f2b25c48574031db60c3a18ae.tar.gz rails-915cf5747a78f28f2b25c48574031db60c3a18ae.tar.bz2 rails-915cf5747a78f28f2b25c48574031db60c3a18ae.zip |
Merge commit 'mainstream/master'
Conflicts:
railties/guides/source/active_support_overview.textile
Diffstat (limited to 'railties/test')
46 files changed, 1727 insertions, 1105 deletions
diff --git a/railties/test/boot_test.rb b/railties/test/boot_test.rb index 2dd68857c3..7bf420d4f2 100644 --- a/railties/test/boot_test.rb +++ b/railties/test/boot_test.rb @@ -1,6 +1,6 @@ require 'abstract_unit' require 'initializer' -require "#{File.dirname(__FILE__)}/../environments/boot" +require "#{File.dirname(__FILE__)}/../lib/generators/rails/app/templates/config/boot" require 'rails/gem_dependency' class BootTest < Test::Unit::TestCase diff --git a/railties/test/fixtures/lib/generators/active_record/fixjour/fixjour_generator.rb b/railties/test/fixtures/lib/generators/active_record/fixjour/fixjour_generator.rb new file mode 100644 index 0000000000..7a4edb8bcb --- /dev/null +++ b/railties/test/fixtures/lib/generators/active_record/fixjour/fixjour_generator.rb @@ -0,0 +1,8 @@ +require 'generators/active_record' + +module ActiveRecord + module Generators + class FixjourGenerator < Base + end + end +end diff --git a/railties/test/fixtures/lib/generators/fixjour_generator.rb b/railties/test/fixtures/lib/generators/fixjour_generator.rb new file mode 100644 index 0000000000..ef3e9edbed --- /dev/null +++ b/railties/test/fixtures/lib/generators/fixjour_generator.rb @@ -0,0 +1,2 @@ +class FixjourGenerator < Rails::Generators::NamedBase +end diff --git a/railties/test/fixtures/lib/generators/missing_class/missing_class_generator.rb b/railties/test/fixtures/lib/generators/missing_class/missing_class_generator.rb deleted file mode 100644 index e69de29bb2..0000000000 --- a/railties/test/fixtures/lib/generators/missing_class/missing_class_generator.rb +++ /dev/null diff --git a/railties/test/fixtures/lib/generators/missing_class/templates/.gitignore b/railties/test/fixtures/lib/generators/missing_class/templates/.gitignore deleted file mode 100644 index e69de29bb2..0000000000 --- a/railties/test/fixtures/lib/generators/missing_class/templates/.gitignore +++ /dev/null diff --git a/railties/test/fixtures/lib/generators/missing_generator/templates/.gitignore b/railties/test/fixtures/lib/generators/missing_generator/templates/.gitignore deleted file mode 100644 index e69de29bb2..0000000000 --- a/railties/test/fixtures/lib/generators/missing_generator/templates/.gitignore +++ /dev/null diff --git a/railties/test/fixtures/lib/generators/missing_templates/.gitignore b/railties/test/fixtures/lib/generators/missing_templates/.gitignore deleted file mode 100644 index e69de29bb2..0000000000 --- a/railties/test/fixtures/lib/generators/missing_templates/.gitignore +++ /dev/null diff --git a/railties/test/fixtures/lib/generators/rails/javascripts_generator.rb b/railties/test/fixtures/lib/generators/rails/javascripts_generator.rb new file mode 100644 index 0000000000..cad5e96784 --- /dev/null +++ b/railties/test/fixtures/lib/generators/rails/javascripts_generator.rb @@ -0,0 +1,4 @@ +module Rails::Generators + class JavascriptsGenerator < Rails::Generators::NamedBase + end +end diff --git a/railties/test/fixtures/lib/generators/working/working_generator.rb b/railties/test/fixtures/lib/generators/working/working_generator.rb deleted file mode 100644 index 465b34319a..0000000000 --- a/railties/test/fixtures/lib/generators/working/working_generator.rb +++ /dev/null @@ -1,2 +0,0 @@ -class WorkingGenerator < Rails::Generator::NamedBase -end diff --git a/railties/test/fixtures/plugins/default/stubby/generators/stubby_generator/stubby_generator.rb b/railties/test/fixtures/plugins/default/stubby/generators/stubby_generator/stubby_generator.rb deleted file mode 100644 index 8fda8197d1..0000000000 --- a/railties/test/fixtures/plugins/default/stubby/generators/stubby_generator/stubby_generator.rb +++ /dev/null @@ -1,4 +0,0 @@ -class StubbyGenerator < Rails::Generator::Base - def manifest - end -end diff --git a/railties/test/fixtures/vendor/gems/mspec/lib/generators/mspec_generator.rb b/railties/test/fixtures/vendor/gems/mspec/lib/generators/mspec_generator.rb new file mode 100644 index 0000000000..191bdbf2fc --- /dev/null +++ b/railties/test/fixtures/vendor/gems/mspec/lib/generators/mspec_generator.rb @@ -0,0 +1,2 @@ +class MspecGenerator < Rails::Generators::NamedBase +end diff --git a/railties/test/fixtures/vendor/gems/wrong/lib/generators/wrong_generator.rb b/railties/test/fixtures/vendor/gems/wrong/lib/generators/wrong_generator.rb new file mode 100644 index 0000000000..6aa7cb052e --- /dev/null +++ b/railties/test/fixtures/vendor/gems/wrong/lib/generators/wrong_generator.rb @@ -0,0 +1,3 @@ +# Old generator version +class WrongGenerator < Rails::Generator::NamedBase +end diff --git a/railties/test/generator_lookup_test.rb b/railties/test/generator_lookup_test.rb deleted file mode 100644 index b67087e5ea..0000000000 --- a/railties/test/generator_lookup_test.rb +++ /dev/null @@ -1,42 +0,0 @@ -require 'plugin_test_helper' - -class GeneratorLookupTest < Test::Unit::TestCase - def setup - @fixture_dirs = %w{alternate default} - @configuration = Rails.configuration = Rails::Configuration.new - # We need to add our testing plugin directory to the plugin paths so - # the locator knows where to look for our plugins - @configuration.plugin_paths += @fixture_dirs.map{|fd| plugin_fixture_path(fd)} - @initializer = Rails::Initializer.default - @initializer.config = @configuration - @initializer.run(:add_plugin_load_paths) - @initializer.run(:load_plugins) - @initializer.run(:set_root_path) - load 'rails_generator.rb' - require 'rails_generator/scripts' - end - - def test_should_load_from_all_plugin_paths - assert Rails::Generator::Base.lookup('a_generator') - assert Rails::Generator::Base.lookup('stubby_generator') - end - - def test_should_create_generator_source_for_each_directory_in_plugin_paths - sources = Rails::Generator::Base.sources - @fixture_dirs.each do |gen_dir| - expected_label = "plugins (fixtures/plugins/#{gen_dir})".to_sym - assert sources.any? {|source| source.label == expected_label } - end - end - - def test_should_preserve_order_in_usage_message - msg = Rails::Generator::Scripts::Base.new.send(:usage_message) - positions = @fixture_dirs.map do |gen_dir| - pos = msg.index("Plugins (fixtures/plugins/#{gen_dir})") - assert_not_nil pos - pos - end - assert_equal positions.sort, positions - end - -end diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb new file mode 100644 index 0000000000..0cda49702b --- /dev/null +++ b/railties/test/generators/actions_test.rb @@ -0,0 +1,177 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/app/app_generator' + +class ActionsTest < GeneratorsTestCase + def setup + super + @git_plugin_uri = 'git://github.com/technoweenie/restful-authentication.git' + @svn_plugin_uri = 'svn://svnhub.com/technoweenie/restful-authentication/trunk' + end + + def test_create_file_should_write_data_to_file_path + action :create_file, 'lib/test_file.rb', 'heres test data' + assert_file 'lib/test_file.rb', 'heres test data' + end + + def test_create_file_should_write_block_contents_to_file_path + action(:create_file, 'lib/test_file.rb'){ 'heres block data' } + assert_file 'lib/test_file.rb', 'heres block data' + end + + def test_plugin_with_git_option_should_run_plugin_install + generator.expects(:run_ruby_script).once.with("script/plugin install #{@git_plugin_uri}", :verbose => false) + action :plugin, 'restful-authentication', :git => @git_plugin_uri + end + + def test_plugin_with_svn_option_should_run_plugin_install + generator.expects(:run_ruby_script).once.with("script/plugin install #{@svn_plugin_uri}", :verbose => false) + action :plugin, 'restful-authentication', :svn => @svn_plugin_uri + end + + def test_plugin_with_git_option_and_submodule_should_use_git_scm + generator.expects(:run).with("git submodule add #{@git_plugin_uri} vendor/plugins/rest_auth", :verbose => false) + action :plugin, 'rest_auth', :git => @git_plugin_uri, :submodule => true + end + + def test_plugin_with_no_options_should_skip_method + generator.expects(:run).never + action :plugin, 'rest_auth', {} + end + + def test_gem_should_put_gem_dependency_in_enviroment + run_generator + action :gem, 'will-paginate' + assert_file 'config/environment.rb', /config\.gem 'will\-paginate'/ + end + + def test_gem_with_options_should_include_options_in_gem_dependency_in_environment + run_generator + action :gem, 'mislav-will-paginate', :lib => 'will-paginate', :source => 'http://gems.github.com' + + regexp = /#{Regexp.escape("config.gem 'mislav-will-paginate', :lib => 'will-paginate', :source => 'http://gems.github.com'")}/ + assert_file 'config/environment.rb', regexp + end + + def test_gem_with_env_string_should_put_gem_dependency_in_specified_environment + run_generator + action :gem, 'rspec', :env => 'test' + assert_file 'config/environments/test.rb', /config\.gem 'rspec'/ + end + + def test_gem_with_env_array_should_put_gem_dependency_in_specified_environments + run_generator + action :gem, 'quietbacktrace', :env => %w[ development test ] + assert_file 'config/environments/development.rb', /config\.gem 'quietbacktrace'/ + assert_file 'config/environments/test.rb', /config\.gem 'quietbacktrace'/ + end + + def test_gem_with_lib_option_set_to_false_should_put_gem_dependency_in_enviroment_correctly + run_generator + action :gem, 'mislav-will-paginate', :lib => false + assert_file 'config/environment.rb', /config\.gem 'mislav\-will\-paginate'\, :lib => false/ + end + + def test_environment_should_include_data_in_environment_initializer_block + run_generator + load_paths = 'config.load_paths += %w["#{RAILS_ROOT}/app/extras"]' + action :environment, load_paths + assert_file 'config/environment.rb', /#{Regexp.escape(load_paths)}/ + end + + def test_environment_with_block_should_include_block_contents_in_environment_initializer_block + run_generator + + action :environment do + '# This wont be added' + '# This will be added' + end + + assert_file 'config/environment.rb' do |content| + assert_match /# This will be added/, content + assert_no_match /# This wont be added/, content + end + end + + def test_git_with_symbol_should_run_command_using_git_scm + generator.expects(:run).once.with('git init') + action :git, :init + end + + def test_git_with_hash_should_run_each_command_using_git_scm + generator.expects(:run).times(2) + action :git, :rm => 'README', :add => '.' + end + + def test_vendor_should_write_data_to_file_in_vendor + action :vendor, 'vendor_file.rb', '# vendor data' + assert_file 'vendor/vendor_file.rb', '# vendor data' + end + + def test_lib_should_write_data_to_file_in_lib + action :lib, 'my_library.rb', 'class MyLibrary' + assert_file 'lib/my_library.rb', 'class MyLibrary' + end + + def test_rakefile_should_write_date_to_file_in_lib_tasks + action :rakefile, 'myapp.rake', 'task :run => [:environment]' + assert_file 'lib/tasks/myapp.rake', 'task :run => [:environment]' + end + + def test_initializer_should_write_date_to_file_in_config_initializers + action :initializer, 'constants.rb', 'MY_CONSTANT = 42' + assert_file 'config/initializers/constants.rb', 'MY_CONSTANT = 42' + end + + def test_generate_should_run_script_generate_with_argument_and_options + generator.expects(:run_ruby_script).once.with('script/generate model MyModel', :verbose => false) + action :generate, 'model', 'MyModel' + end + + def test_rake_should_run_rake_command_with_development_env + generator.expects(:run).once.with('rake log:clear RAILS_ENV=development', :verbose => false) + action :rake, 'log:clear' + 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' + 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) + action :rake, 'log:clear', :sudo => true + end + + def test_capify_should_run_the_capify_command + generator.expects(:run).once.with('capify .', :verbose => false) + action :capify! + end + + def test_freeze_should_freeze_rails_edge + generator.expects(:run).once.with('rake rails:freeze:edge', :verbose => false) + action :freeze! + end + + def test_route_should_add_data_to_the_routes_block_in_config_routes + run_generator + route_command = "map.route '/login', :controller => 'sessions', :action => 'new'" + action :route, route_command + assert_file 'config/routes.rb', /#{Regexp.escape(route_command)}/ + end + + protected + + def run_generator + silence(:stdout) { Rails::Generators::AppGenerator.start [destination_root] } + end + + def generator(config={}) + @generator ||= Rails::Generators::Base.new([], {}, { :destination_root => destination_root }.merge!(config)) + end + + def action(*args, &block) + silence(:stdout){ generator.send(*args, &block) } + end + +end diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb new file mode 100644 index 0000000000..c794a2ade6 --- /dev/null +++ b/railties/test/generators/app_generator_test.rb @@ -0,0 +1,182 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/app/app_generator' + +class AppGeneratorTest < GeneratorsTestCase + + def setup + super + Rails::Generators::AppGenerator.instance_variable_set('@desc', nil) + end + + def teardown + super + Rails::Generators::AppGenerator.instance_variable_set('@desc', nil) + end + + def test_application_skeleton_is_created + run_generator + + %w( + app/controllers + app/helpers + app/models + app/views/layouts + config/environments + config/initializers + config/locales + db + doc + lib + lib/tasks + log + public/images + public/javascripts + public/stylesheets + script/performance + test/fixtures + test/functional + test/integration + test/performance + test/unit + vendor + vendor/plugins + tmp/sessions + tmp/sockets + tmp/cache + tmp/pids + ).each{ |path| assert_file path } + end + + def test_invalid_database_option_raises_an_error + content = capture(:stderr){ run_generator(["-d", "unknown"]) } + assert_match /Invalid value for \-\-database option/, content + end + + def test_dispatchers_are_not_added_by_default + run_generator + assert_no_file "config.ru" + assert_no_file "public/dispatch.cgi" + assert_no_file "public/dispatch.fcgi" + end + + def test_dispatchers_are_added_if_required + run_generator ["--with-dispatchers"] + assert_file "config.ru" + assert_file "public/dispatch.cgi" + assert_file "public/dispatch.fcgi" + end + + def test_config_database_is_added_by_default + run_generator + assert_file "config/database.yml", /sqlite3/ + end + + def test_config_database_is_not_added_if_skip_activerecord_is_given + run_generator ["--skip-activerecord"] + assert_no_file "config/database.yml" + end + + def test_activerecord_is_removed_from_frameworks_if_skip_activerecord_is_given + run_generator ["--skip-activerecord"] + assert_file "config/environment.rb", /config\.frameworks \-= \[ :active_record \]/ + end + + def test_prototype_and_test_unit_are_added_by_default + run_generator + assert_file "public/javascripts/prototype.js" + assert_file "test" + end + + def test_prototype_and_test_unit_are_skipped_if_required + run_generator ["--skip-prototype", "--skip-testunit"] + assert_no_file "public/javascripts/prototype.js" + assert_no_file "test" + end + + def test_shebang_is_added_to_files + run_generator ["--ruby", "foo/bar/baz"] + + %w( + about + console + dbconsole + destroy + generate + plugin + runner + server + ).each { |path| assert_file "script/#{path}", /#!foo\/bar\/baz/ } + end + + def test_shebang_when_is_the_same_as_default_use_env + run_generator ["--ruby", Thor::Util.ruby_command] + + %w( + about + console + dbconsole + destroy + generate + plugin + runner + server + ).each { |path| assert_file "script/#{path}", /#!\/usr\/bin\/env/ } + end + + def test_rails_is_frozen + generator(:freeze => true, :database => "sqlite3").expects(:run). + with("rake rails:freeze:edge", :verbose => false) + silence(:stdout){ generator.invoke } + assert_file 'config/environment.rb', /# RAILS_GEM_VERSION/ + end + + def test_template_raises_an_error_with_invalid_path + content = capture(:stderr){ run_generator(["-m", "non/existant/path"]) } + assert_match /The template \[.*\] could not be loaded/, content + assert_match /non\/existant\/path/, content + end + + def test_template_is_executed_when_supplied + path = "http://gist.github.com/103208.txt" + template = %{ say "It works!" } + template.instance_eval "def read; self; end" # Make the string respond to read + + generator(:template => path, :database => "sqlite3").expects(:open).with(path).returns(template) + assert_match /It works!/, silence(:stdout){ generator.invoke } + end + + def test_usage_read_from_file + File.expects(:read).returns("USAGE FROM FILE") + assert_equal "USAGE FROM FILE", Rails::Generators::AppGenerator.desc + end + + def test_default_usage + File.expects(:exist?).returns(false) + assert_match /Create rails files for app generator/, Rails::Generators::AppGenerator.desc + end + + def test_default_namespace + assert_match "rails:generators:app", Rails::Generators::AppGenerator.namespace + end + + def test_file_is_added_for_backwards_compatibility + action :file, 'lib/test_file.rb', 'heres test data' + assert_file 'lib/test_file.rb', 'heres test data' + end + + protected + + def run_generator(args=[]) + silence(:stdout) { Rails::Generators::AppGenerator.start [destination_root].concat(args) } + end + + def generator(options={}) + @generator ||= Rails::Generators::AppGenerator.new([destination_root], options, :destination_root => destination_root) + end + + def action(*args, &block) + silence(:stdout){ generator.send(*args, &block) } + end + +end diff --git a/railties/test/generators/controller_generator_test.rb b/railties/test/generators/controller_generator_test.rb new file mode 100644 index 0000000000..850b9e632d --- /dev/null +++ b/railties/test/generators/controller_generator_test.rb @@ -0,0 +1,80 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/controller/controller_generator' + +class ControllerGeneratorTest < GeneratorsTestCase + + def test_help_does_not_show_invoked_generators_options_if_they_already_exist + content = run_generator ["--help"] + assert_no_match /Helper options:/, content + end + + def test_controller_skeleton_is_created + run_generator + assert_file "app/controllers/account_controller.rb", /class AccountController < ApplicationController/ + end + + def test_check_class_collision + Object.send :const_set, :ObjectController, Class.new + content = capture(:stderr){ run_generator ["object"] } + assert_match /The name 'ObjectController' is either already used in your application or reserved/, content + ensure + Object.send :remove_const, :ObjectController + end + + # No need to spec content since it's already spec'ed on helper generator. + # + def test_invokes_helper + run_generator + assert_file "app/helpers/account_helper.rb" + assert_file "test/unit/helpers/account_helper_test.rb" + end + + def test_does_not_invoke_helper_if_required + run_generator ["account", "--skip-helper"] + assert_no_file "app/helpers/account_helper.rb" + assert_no_file "test/unit/helpers/account_helper_test.rb" + end + + def test_invokes_default_test_framework + run_generator + assert_file "test/functional/account_controller_test.rb" + end + + def test_does_not_invoke_test_framework_if_required + run_generator ["account", "--no-test-framework"] + assert_no_file "test/functional/account_controller_test.rb" + end + + def test_invokes_default_template_engine + run_generator + assert_file "app/views/account/foo.html.erb", /app\/views\/account\/foo/ + assert_file "app/views/account/bar.html.erb", /app\/views\/account\/bar/ + end + + def test_invokes_default_template_engine_even_with_no_action + run_generator ["account"] + assert_file "app/views/account" + end + + def test_template_engine_with_class_path + run_generator ["admin/account"] + assert_file "app/views/admin/account" + end + + def test_actions_are_turned_into_methods + run_generator + + assert_file "app/controllers/account_controller.rb" do |controller| + assert_instance_method controller, :foo + assert_instance_method controller, :bar + end + end + + protected + + def run_generator(args=["Account", "foo", "bar"]) + silence(:stdout) { Rails::Generators::ControllerGenerator.start args, :destination_root => destination_root } + end + +end diff --git a/railties/test/generators/generator_generator_test.rb b/railties/test/generators/generator_generator_test.rb new file mode 100644 index 0000000000..b1ebe5f1b5 --- /dev/null +++ b/railties/test/generators/generator_generator_test.rb @@ -0,0 +1,26 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/generator/generator_generator' + +class GeneratorGeneratorTest < GeneratorsTestCase + + def test_generator_skeleton_is_created + run_generator + + %w( + lib/generators/awesome + lib/generators/awesome/USAGE + lib/generators/awesome/templates + ).each{ |path| assert_file path } + + assert_file "lib/generators/awesome/awesome_generator.rb", + /class AwesomeGenerator < Rails::Generators::NamedBase/ + end + + protected + + def run_generator(args=["awesome"], config={}) + silence(:stdout) { Rails::Generators::GeneratorGenerator.start args, config.merge(:destination_root => destination_root) } + end + +end diff --git a/railties/test/generators/generator_test_helper.rb b/railties/test/generators/generator_test_helper.rb deleted file mode 100644 index 01bf1c90bd..0000000000 --- a/railties/test/generators/generator_test_helper.rb +++ /dev/null @@ -1,303 +0,0 @@ -require 'test/unit' -require 'fileutils' - -# Mock out what we need from AR::Base -module ActiveRecord - class Base - class << self - attr_accessor :pluralize_table_names, :timestamped_migrations - end - self.pluralize_table_names = true - self.timestamped_migrations = true - end - - module ConnectionAdapters - class Column - attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale - - def initialize(name, default, sql_type = nil) - @name = name - @default = default - @type = @sql_type = sql_type - end - - def human_name - @name.humanize - end - end - end -end - -# Mock up necessities from ActionView -module ActionView - module Helpers - module ActionRecordHelper; end - class InstanceTag; end - end -end - -# Set RAILS_ROOT appropriately fixture generation -tmp_dir = "#{File.dirname(__FILE__)}/../fixtures/tmp" - -if defined? RAILS_ROOT - RAILS_ROOT.replace tmp_dir -else - RAILS_ROOT = tmp_dir -end -FileUtils.mkdir_p RAILS_ROOT - -$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../../lib" -require 'initializer' - -# Mocks out the configuration -module Rails - def self.configuration - Rails::Configuration.new - end -end - -require 'rails_generator' - -class GeneratorTestCase < Test::Unit::TestCase - include FileUtils - - def setup - ActiveRecord::Base.pluralize_table_names = true - - mkdir_p "#{RAILS_ROOT}/app/views/layouts" - mkdir_p "#{RAILS_ROOT}/config" - mkdir_p "#{RAILS_ROOT}/db" - mkdir_p "#{RAILS_ROOT}/test/fixtures" - mkdir_p "#{RAILS_ROOT}/public/stylesheets" - - File.open("#{RAILS_ROOT}/config/routes.rb", 'w') do |f| - f << "ActionController::Routing::Routes.draw do |map|\n\nend" - end - end - - def teardown - rm_rf "#{RAILS_ROOT}/app" - rm_rf "#{RAILS_ROOT}/test" - rm_rf "#{RAILS_ROOT}/config" - rm_rf "#{RAILS_ROOT}/db" - rm_rf "#{RAILS_ROOT}/public" - end - - def test_truth - # don't complain, test/unit - end - - # Instantiates the Generator. - def build_generator(name, params) - Rails::Generator::Base.instance(name, params) - end - - # Runs the +create+ command (like the command line does). - def run_generator(name, params) - silence_generator do - build_generator(name, params).command(:create).invoke! - end - end - - # Silences the logger temporarily and returns the output as a String. - def silence_generator - logger_original = Rails::Generator::Base.logger - myout = StringIO.new - Rails::Generator::Base.logger = Rails::Generator::SimpleLogger.new(myout) - yield if block_given? - Rails::Generator::Base.logger = logger_original - myout.string - end - - # Asserts that the given controller was generated. - # It takes a name or symbol without the <tt>_controller</tt> part and an optional super class. - # The contents of the class source file is passed to a block. - def assert_generated_controller_for(name, parent = "ApplicationController") - assert_generated_class "app/controllers/#{name.to_s.underscore}_controller", parent do |body| - yield body if block_given? - end - end - - # Asserts that the given model was generated. - # It takes a name or symbol and an optional super class. - # The contents of the class source file is passed to a block. - def assert_generated_model_for(name, parent = "ActiveRecord::Base") - assert_generated_class "app/models/#{name.to_s.underscore}", parent do |body| - yield body if block_given? - end - end - - # Asserts that the given helper was generated. - # It takes a name or symbol without the <tt>_helper</tt> part. - # The contents of the module source file is passed to a block. - def assert_generated_helper_for(name) - assert_generated_module "app/helpers/#{name.to_s.underscore}_helper" do |body| - yield body if block_given? - end - end - - # Asserts that the given functional test was generated. - # It takes a name or symbol without the <tt>_controller_test</tt> part and an optional super class. - # The contents of the class source file is passed to a block. - def assert_generated_functional_test_for(name, parent = "ActionController::TestCase") - assert_generated_class "test/functional/#{name.to_s.underscore}_controller_test",parent do |body| - yield body if block_given? - end - end - - # Asserts that the given helper test test was generated. - # It takes a name or symbol without the <tt>_helper_test</tt> part and an optional super class. - # The contents of the class source file is passed to a block. - def assert_generated_helper_test_for(name, parent = "ActionView::TestCase") - path = "test/unit/helpers/#{name.to_s.underscore}_helper_test" - # Have to pass the path without the "test/" part so that class_name_from_path will return a correct result - class_name = class_name_from_path(path.gsub(/^test\//, '')) - - assert_generated_class path,parent,class_name do |body| - yield body if block_given? - end - end - - # Asserts that the given unit test was generated. - # It takes a name or symbol without the <tt>_test</tt> part and an optional super class. - # The contents of the class source file is passed to a block. - def assert_generated_unit_test_for(name, parent = "ActiveSupport::TestCase") - assert_generated_class "test/unit/#{name.to_s.underscore}_test", parent do |body| - yield body if block_given? - end - end - - # Asserts that the given file was generated. - # The contents of the file is passed to a block. - def assert_generated_file(path) - assert_file_exists(path) - File.open("#{RAILS_ROOT}/#{path}") do |f| - yield f.read if block_given? - end - end - - # asserts that the given file exists - def assert_file_exists(path) - assert File.exist?("#{RAILS_ROOT}/#{path}"), - "The file '#{RAILS_ROOT}/#{path}' should exist" - end - - # Asserts that the given class source file was generated. - # It takes a path without the <tt>.rb</tt> part and an optional super class. - # The contents of the class source file is passed to a block. - def assert_generated_class(path, parent = nil, class_name = class_name_from_path(path)) - assert_generated_file("#{path}.rb") do |body| - assert_match /class #{class_name}#{parent.nil? ? '':" < #{parent}"}/, body, "the file '#{path}.rb' should be a class" - yield body if block_given? - end - end - - def class_name_from_path(path) - # FIXME: Sucky way to detect namespaced classes - if path.split('/').size > 3 - path =~ /\/?(\d+_)?(\w+)\/(\w+)$/ - "#{$2.camelize}::#{$3.camelize}" - else - path =~ /\/?(\d+_)?(\w+)$/ - $2.camelize - end - end - - # Asserts that the given module source file was generated. - # It takes a path without the <tt>.rb</tt> part. - # The contents of the class source file is passed to a block. - def assert_generated_module(path) - # FIXME: Sucky way to detect namespaced modules - if path.split('/').size > 3 - path =~ /\/?(\w+)\/(\w+)$/ - module_name = "#{$1.camelize}::#{$2.camelize}" - else - path =~ /\/?(\w+)$/ - module_name = $1.camelize - end - - assert_generated_file("#{path}.rb") do |body| - assert_match /module #{module_name}/, body, "the file '#{path}.rb' should be a module" - yield body if block_given? - end - end - - # Asserts that the given CSS stylesheet file was generated. - # It takes a path without the <tt>.css</tt> part. - # The contents of the stylesheet source file is passed to a block. - def assert_generated_stylesheet(path) - assert_generated_file("public/stylesheets/#{path}.css") do |body| - yield body if block_given? - end - end - - # Asserts that the given YAML file was generated. - # It takes a path without the <tt>.yml</tt> part. - # The parsed YAML tree is passed to a block. - def assert_generated_yaml(path) - assert_generated_file("#{path}.yml") do |body| - yaml = YAML.load(body) - assert yaml, 'YAML data missing' - yield yaml if block_given? - end - end - - # Asserts that the given fixtures YAML file was generated. - # It takes a fixture name without the <tt>.yml</tt> part. - # The parsed YAML tree is passed to a block. - def assert_generated_fixtures_for(name) - assert_generated_yaml "test/fixtures/#{name.to_s.underscore}" do |yaml| - yield yaml if block_given? - end - end - - # Asserts that the given views were generated. - # It takes a controller name and a list of views (including extensions). - # The body of each view is passed to a block. - def assert_generated_views_for(name, *actions) - actions.each do |action| - assert_generated_file("app/views/#{name.to_s.underscore}/#{action}") do |body| - yield body if block_given? - end - end - end - - def assert_generated_migration(name, parent = "ActiveRecord::Migration") - file = Dir.glob("#{RAILS_ROOT}/db/migrate/*_#{name.to_s.underscore}.rb").first - file = file.match(/db\/migrate\/[0-9]+_\w+/).to_s - assert_generated_class file, parent do |body| - assert_match /timestamps/, body, "should have timestamps defined" - yield body if block_given? - end - end - - # Asserts that the given migration file was not generated. - # It takes the name of the migration as a parameter. - def assert_skipped_migration(name) - migration_file = "#{RAILS_ROOT}/db/migrate/001_#{name.to_s.underscore}.rb" - assert !File.exist?(migration_file), "should not create migration #{migration_file}" - end - - # Asserts that the given resource was added to the routes. - def assert_added_route_for(name) - assert_generated_file("config/routes.rb") do |body| - assert_match /map.resources :#{name.to_s.underscore}/, body, - "should add route for :#{name.to_s.underscore}" - end - end - - # Asserts that the given methods are defined in the body. - # This does assume standard rails code conventions with regards to the source code. - # The body of each individual method is passed to a block. - def assert_has_method(body, *methods) - methods.each do |name| - assert body =~ /^ def #{name}(\(.+\))?\n((\n| .*\n)*) end/, "should have method #{name}" - yield(name, $2) if block_given? - end - end - - # Asserts that the given column is defined in the migration. - def assert_generated_column(body, name, type) - assert_match /t\.#{type.to_s} :#{name.to_s}/, body, "should have column #{name.to_s} defined" - end -end diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb new file mode 100644 index 0000000000..011bd518f8 --- /dev/null +++ b/railties/test/generators/generators_test_helper.rb @@ -0,0 +1,101 @@ +require 'test/unit' +require 'fileutils' + +fixtures = File.expand_path(File.join(File.dirname(__FILE__), '..', 'fixtures')) +if defined?(RAILS_ROOT) + RAILS_ROOT.replace fixtures +else + RAILS_ROOT = fixtures +end + +$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../../../activerecord/lib" +$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../../lib" +require 'generators' + +CURRENT_PATH = File.expand_path(Dir.pwd) +Rails::Generators.no_color! + +class GeneratorsTestCase < Test::Unit::TestCase + include FileUtils + + def destination_root + @destination_root ||= File.expand_path(File.join(File.dirname(__FILE__), + '..', '..', 'fixtures', 'tmp')) + end + + def setup + cd CURRENT_PATH + rm_rf(destination_root) + mkdir_p(destination_root) + end + + def test_truth + # don't complain, test/unit + end + + def capture(stream) + begin + stream = stream.to_s + eval "$#{stream} = StringIO.new" + yield + result = eval("$#{stream}").string + ensure + eval("$#{stream} = #{stream.upcase}") + end + + result + end + alias :silence :capture + + def assert_file(relative, *contents) + absolute = File.join(destination_root, relative) + assert File.exists?(absolute), "Expected file #{relative.inspect} to exist, but does not" + + read = File.read(absolute) if block_given? || !contents.empty? + yield read if block_given? + + contents.each do |content| + case content + when String + assert_equal content, read + when Regexp + assert_match content, read + end + end + end + + def assert_no_file(relative) + absolute = File.join(destination_root, relative) + assert !File.exists?(absolute), "Expected file #{relative.inspect} to not exist, but does" + end + + def assert_migration(relative, *contents, &block) + file_name = migration_file_name(relative) + assert file_name, "Expected migration #{relative} to exist, but was not found" + assert_file File.join(File.dirname(relative), file_name), *contents, &block + end + + def assert_no_migration(relative) + file_name = migration_file_name(relative) + assert_nil file_name, "Expected migration #{relative} to not exist, but found #{file_name}" + end + + def assert_class_method(content, method, &block) + assert_instance_method content, "self.#{method}", &block + end + + def assert_instance_method(content, method) + assert content =~ /def #{method}(\(.+\))?(.*?)\n end/m, "Expected to have method #{method}" + yield $2.strip if block_given? + end + + protected + + def migration_file_name(relative) + absolute = File.join(destination_root, relative) + dirname, file_name = File.dirname(absolute), File.basename(absolute).sub(/\.rb$/, '') + + migration = Dir.glob("#{dirname}/[0-9]*_*.rb").grep(/\d+_#{file_name}.rb$/).first + File.basename(migration) if migration + end +end diff --git a/railties/test/generators/helper_generator_test.rb b/railties/test/generators/helper_generator_test.rb new file mode 100644 index 0000000000..3d655016f1 --- /dev/null +++ b/railties/test/generators/helper_generator_test.rb @@ -0,0 +1,60 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/helper/helper_generator' + +ObjectHelper = Class.new +AnotherObjectHelperTest = Class.new + +class HelperGeneratorTest < GeneratorsTestCase + + def test_helper_skeleton_is_created + run_generator + assert_file "app/helpers/admin_helper.rb", /module AdminHelper/ + end + + def test_invokes_default_test_framework + run_generator + assert_file "test/unit/helpers/admin_helper_test.rb", /class AdminHelperTest < ActionView::TestCase/ + end + + def test_logs_if_the_test_framework_cannot_be_found + content = run_generator ["admin", "--test-framework=rspec"] + assert_match /rspec \[not found\]/, content + end + + def test_check_class_collision + content = capture(:stderr){ run_generator ["object"] } + assert_match /The name 'ObjectHelper' is either already used in your application or reserved/, content + end + + def test_check_class_collision_on_tests + content = capture(:stderr){ run_generator ["another_object"] } + assert_match /The name 'AnotherObjectHelperTest' is either already used in your application or reserved/, content + end + + def test_namespaced_and_not_namespaced_helpers + run_generator ["products"] + + # We have to require the generated helper to show the problem because + # the test helpers just check for generated files and contents but + # do not actually load them. But they have to be loaded (as in a real environment) + # to make the second generator run fail + require "#{destination_root}/app/helpers/products_helper" + + assert_nothing_raised do + begin + run_generator ["admin::products"] + ensure + # cleanup + Object.send(:remove_const, :ProductsHelper) + end + end + end + + protected + + def run_generator(args=["admin"]) + silence(:stdout) { Rails::Generators::HelperGenerator.start args, :destination_root => destination_root } + end + +end diff --git a/railties/test/generators/integration_test_generator_test.rb b/railties/test/generators/integration_test_generator_test.rb new file mode 100644 index 0000000000..190b28012c --- /dev/null +++ b/railties/test/generators/integration_test_generator_test.rb @@ -0,0 +1,18 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/integration_test/integration_test_generator' + +class IntegrationTestGeneratorTest < GeneratorsTestCase + + def test_integration_test_skeleton_is_created + run_generator + assert_file "test/integration/integration_test.rb", /class IntegrationTest < ActionController::IntegrationTest/ + end + + protected + + def run_generator(args=["integration"]) + silence(:stdout) { Rails::Generators::IntegrationTestGenerator.start args, :destination_root => destination_root } + end + +end diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb new file mode 100644 index 0000000000..9e74859c3a --- /dev/null +++ b/railties/test/generators/mailer_generator_test.rb @@ -0,0 +1,52 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/mailer/mailer_generator' + +class MailerGeneratorTest < GeneratorsTestCase + + def test_mailer_skeleton_is_created + run_generator + assert_file "app/models/notifier.rb", /class Notifier < ActionMailer::Base/ + 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 + end + + def test_invokes_default_test_framework + run_generator + assert_file "test/unit/notifier_test.rb", /class NotifierTest < ActionMailer::TestCase/ + assert_file "test/fixtures/notifier/foo", /app\/views\/notifier\/foo/ + assert_file "test/fixtures/notifier/bar", /app\/views\/notifier\/bar/ + end + + def test_invokes_default_template_engine + run_generator + assert_file "app/views/notifier/foo.erb", /app\/views\/notifier\/foo/ + assert_file "app/views/notifier/bar.erb", /app\/views\/notifier\/bar/ + end + + def test_invokes_default_template_engine_even_with_no_action + run_generator ["notifier"] + assert_file "app/views/notifier" + end + + def test_logs_if_the_template_engine_cannot_be_found + content = run_generator ["notifier", "foo", "bar", "--template-engine=haml"] + assert_match /haml \[not found\]/, content + end + + def test_actions_are_turned_into_methods + run_generator + assert_file "app/models/notifier.rb", /def foo/ + assert_file "app/models/notifier.rb", /def bar/ + end + + protected + + def run_generator(args=["notifier", "foo", "bar"]) + silence(:stdout) { Rails::Generators::MailerGenerator.start args, :destination_root => destination_root } + end + +end diff --git a/railties/test/generators/metal_generator_test.rb b/railties/test/generators/metal_generator_test.rb new file mode 100644 index 0000000000..97e892cefb --- /dev/null +++ b/railties/test/generators/metal_generator_test.rb @@ -0,0 +1,23 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/metal/metal_generator' + +class MetalGeneratorTest < GeneratorsTestCase + + def test_metal_skeleton_is_created + run_generator + assert_file "app/metal/foo.rb", /class Foo/ + 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 + end + + protected + + def run_generator(args=["foo"]) + silence(:stdout) { Rails::Generators::MetalGenerator.start args, :destination_root => destination_root } + end + +end diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb new file mode 100644 index 0000000000..a4335068e6 --- /dev/null +++ b/railties/test/generators/migration_generator_test.rb @@ -0,0 +1,59 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/migration/migration_generator' + +class MigrationGeneratorTest < GeneratorsTestCase + + def test_migration + @migration = "change_title_body_from_posts" + run_generator + assert_migration "db/migrate/#{@migration}.rb", /class ChangeTitleBodyFromPosts < ActiveRecord::Migration/ + end + + def test_migration_with_class_name + @migration = "ChangeTitleBodyFromPosts" + run_generator + assert_migration "db/migrate/change_title_body_from_posts.rb", /class #{@migration} < ActiveRecord::Migration/ + end + + def test_add_migration_with_attributes + @migration = "add_title_body_to_posts" + run_generator [@migration, "title:string", "body:text"] + + assert_migration "db/migrate/#{@migration}.rb" do |content| + assert_class_method content, :up do |up| + assert_match /add_column :posts, :title, :string/, up + assert_match /add_column :posts, :body, :text/, up + end + + assert_class_method content, :down do |down| + assert_match /remove_column :posts, :title/, down + assert_match /remove_column :posts, :body/, down + end + end + end + + def test_remove_migration_with_attributes + @migration = "remove_title_body_from_posts" + run_generator [@migration, "title:string", "body:text"] + + assert_migration "db/migrate/#{@migration}.rb" do |content| + assert_class_method content, :up do |up| + assert_match /remove_column :posts, :title/, up + assert_match /remove_column :posts, :body/, up + end + + assert_class_method content, :down do |down| + assert_match /add_column :posts, :title, :string/, down + assert_match /add_column :posts, :body, :text/, down + end + end + end + + protected + + def run_generator(args=[@migration]) + silence(:stdout) { Rails::Generators::MigrationGenerator.start args, :destination_root => destination_root } + end + +end diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb new file mode 100644 index 0000000000..a9b772d67b --- /dev/null +++ b/railties/test/generators/model_generator_test.rb @@ -0,0 +1,137 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/model/model_generator' + +class ModelGeneratorTest < GeneratorsTestCase + + def test_help_shows_invoked_generators_options + content = run_generator ["--help"] + assert_match /ActiveRecord options:/, content + assert_match /TestUnit options:/, content + end + + def test_invokes_default_orm + run_generator + assert_file "app/models/account.rb", /class Account < ActiveRecord::Base/ + end + + def test_model_with_parent_option + run_generator ["account", "--parent", "Admin::Account"] + assert_file "app/models/account.rb", /class Account < Admin::Account/ + assert_no_migration "db/migrate/create_accounts.rb" + end + + def test_model_with_underscored_parent_option + run_generator ["account", "--parent", "admin/account"] + assert_file "app/models/account.rb", /class Account < Admin::Account/ + end + + def test_migration + run_generator + assert_migration "db/migrate/create_accounts.rb", /class CreateAccounts < ActiveRecord::Migration/ + end + + def test_migration_is_skipped + run_generator ["account", "--no-migration"] + assert_no_migration "db/migrate/create_accounts.rb" + end + + def test_migration_with_attributes + run_generator ["product", "name:string", "supplier_id:integer"] + + assert_migration "db/migrate/create_products.rb" do |m| + assert_class_method m, :up do |up| + assert_match /create_table :products/, up + assert_match /t\.string :name/, up + assert_match /t\.integer :supplier_id/, up + end + + assert_class_method m, :down do |down| + assert_match /drop_table :products/, down + end + end + end + + def test_migration_without_timestamps + ActiveRecord::Base.timestamped_migrations = false + run_generator ["account"] + assert_file "db/migrate/001_create_accounts.rb", /class CreateAccounts < ActiveRecord::Migration/ + + run_generator ["project"] + assert_file "db/migrate/002_create_projects.rb", /class CreateProjects < ActiveRecord::Migration/ + ensure + ActiveRecord::Base.timestamped_migrations = true + end + + def test_model_with_references_attribute_generates_belongs_to_associations + run_generator ["product", "name:string", "supplier_id:references"] + assert_file "app/models/product.rb", /belongs_to :supplier/ + end + + def test_model_with_belongs_to_attribute_generates_belongs_to_associations + run_generator ["product", "name:string", "supplier_id:belongs_to"] + assert_file "app/models/product.rb", /belongs_to :supplier/ + end + + def test_migration_with_timestamps + run_generator + assert_migration "db/migrate/create_accounts.rb", /t.timestamps/ + end + + def test_migration_timestamps_are_skipped + run_generator ["account", "--no-timestamps"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_class_method m, :up do |up| + assert_no_match /t.timestamps/, up + end + end + end + + def test_migration_already_exists_error_message + run_generator + error = capture(:stderr){ run_generator ["Account"], :behavior => :skip } + assert_match /Another migration is already named create_accounts/, error + end + + def test_migration_error_is_not_shown_on_revoke + run_generator + error = capture(:stderr){ run_generator ["Account"], :behavior => :revoke } + assert_no_match /Another migration is already named create_accounts/, error + end + + def test_migration_is_removed_on_revoke + run_generator + run_generator ["Account"], :behavior => :revoke + assert_no_migration "db/migrate/create_accounts.rb" + end + + def test_invokes_default_test_framework + run_generator + assert_file "test/unit/account_test.rb", /class AccountTest < ActiveSupport::TestCase/ + assert_file "test/fixtures/accounts.yml", /name: MyString/, /age: 1/ + end + + def test_fixture_is_skipped + run_generator ["account", "--skip-fixture"] + assert_no_file "test/fixtures/accounts.yml" + end + + def test_fixture_is_skipped_if_fixture_replacement_is_given + content = run_generator ["account", "-r", "factory_girl"] + assert_match /factory_girl \[not found\]/, content + assert_no_file "test/fixtures/accounts.yml" + 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 + end + + protected + + def run_generator(args=["Account", "name:string", "age:integer"], config={}) + silence(:stdout) { Rails::Generators::ModelGenerator.start args, config.merge(:destination_root => destination_root) } + end + +end diff --git a/railties/test/generators/named_base_test.rb b/railties/test/generators/named_base_test.rb new file mode 100644 index 0000000000..3a5c58ab32 --- /dev/null +++ b/railties/test/generators/named_base_test.rb @@ -0,0 +1,42 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/scaffold_controller/scaffold_controller_generator' + +# 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 + +class NamedBaseTest < GeneratorsTestCase + + def test_named_generator_attributes + g = Rails::Generators::ScaffoldControllerGenerator.new ["admin/foo"] + assert_equal 'admin/foo', g.name + assert_equal %w(admin), g.class_path + assert_equal 1, g.class_nesting_depth + assert_equal 'Admin::Foo', g.class_name + assert_equal 'foo', g.singular_name + assert_equal 'foos', g.plural_name + assert_equal g.singular_name, g.file_name + assert_equal "admin_#{g.plural_name}", g.table_name + end + + def test_named_generator_attributes_without_pluralized + ActiveRecord::Base.pluralize_table_names = false + g = Rails::Generators::ScaffoldControllerGenerator.new ["admin/foo"] + assert_equal "admin_#{g.singular_name}", g.table_name + end + + def test_scaffold_plural_names + g = Rails::Generators::ScaffoldControllerGenerator.new ["ProductLine"] + assert_equal "ProductLines", g.controller_name + assert_equal "ProductLines", g.controller_class_name + assert_equal "product_lines", g.controller_file_name + end + +end diff --git a/railties/test/generators/observer_generator_test.rb b/railties/test/generators/observer_generator_test.rb new file mode 100644 index 0000000000..a556731e16 --- /dev/null +++ b/railties/test/generators/observer_generator_test.rb @@ -0,0 +1,33 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/observer/observer_generator' + +class ObserverGeneratorTest < GeneratorsTestCase + + def test_invokes_default_orm + run_generator + assert_file "app/models/account_observer.rb", /class AccountObserver < ActiveRecord::Observer/ + end + + def test_invokes_default_orm_with_class_path + run_generator ["admin/account"] + assert_file "app/models/admin/account_observer.rb", /class Admin::AccountObserver < ActiveRecord::Observer/ + end + + def test_invokes_default_test_framework + run_generator + assert_file "test/unit/account_observer_test.rb", /class AccountObserverTest < ActiveSupport::TestCase/ + end + + def test_logs_if_the_test_framework_cannot_be_found + content = run_generator ["account", "--test-framework=rspec"] + assert_match /rspec \[not found\]/, content + end + + protected + + def run_generator(args=["account"]) + silence(:stdout) { Rails::Generators::ObserverGenerator.start args, :destination_root => destination_root } + end + +end diff --git a/railties/test/generators/performance_test_generator_test.rb b/railties/test/generators/performance_test_generator_test.rb new file mode 100644 index 0000000000..74c9c20c4c --- /dev/null +++ b/railties/test/generators/performance_test_generator_test.rb @@ -0,0 +1,18 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/performance_test/performance_test_generator' + +class PerformanceTestGeneratorTest < GeneratorsTestCase + + def test_performance_test_skeleton_is_created + run_generator + assert_file "test/performance/performance_test.rb", /class PerformanceTest < ActionController::PerformanceTest/ + end + + protected + + def run_generator(args=["performance"]) + silence(:stdout) { Rails::Generators::PerformanceTestGenerator.start args, :destination_root => destination_root } + end + +end diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb new file mode 100644 index 0000000000..3982586bc3 --- /dev/null +++ b/railties/test/generators/plugin_generator_test.rb @@ -0,0 +1,56 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/plugin/plugin_generator' + +class PluginGeneratorTest < GeneratorsTestCase + + def test_plugin_skeleton_is_created + run_generator + + %w( + vendor/plugins + vendor/plugins/plugin_fu + vendor/plugins/plugin_fu/lib + ).each{ |path| assert_file path } + 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 + end + + def test_invokes_default_test_framework + run_generator + assert_file "vendor/plugins/plugin_fu/test/plugin_fu_test.rb", /class PluginFuTest < ActiveSupport::TestCase/ + assert_file "vendor/plugins/plugin_fu/test/test_helper.rb" + end + + def test_logs_if_the_test_framework_cannot_be_found + content = run_generator ["plugin_fu", "--test-framework=rspec"] + assert_match /rspec \[not found\]/, content + end + + def test_creates_tasks_if_required + run_generator ["plugin_fu", "--tasks"] + assert_file "vendor/plugins/plugin_fu/tasks/plugin_fu_tasks.rake" + end + + def test_creates_generator_if_required + run_generator ["plugin_fu", "--generator"] + assert_file "vendor/plugins/plugin_fu/lib/generators/templates" + assert_file "vendor/plugins/plugin_fu/lib/generators/plugin_fu_generator.rb", + /class PluginFuGenerator < Rails::Generators::NamedBase/ + end + + def test_plugin_generator_on_revoke + run_generator + run_generator ["plugin_fu"], :behavior => :revoke + end + + protected + + def run_generator(args=["plugin_fu"], config={}) + silence(:stdout) { Rails::Generators::PluginGenerator.start args, config.merge(:destination_root => destination_root) } + end + +end diff --git a/railties/test/generators/rails_controller_generator_test.rb b/railties/test/generators/rails_controller_generator_test.rb deleted file mode 100644 index 43fbe972e2..0000000000 --- a/railties/test/generators/rails_controller_generator_test.rb +++ /dev/null @@ -1,44 +0,0 @@ -require 'generators/generator_test_helper' - -module Admin -end - -class RailsControllerGeneratorTest < GeneratorTestCase - - def test_controller_generates_controller - run_generator('controller', %w(products)) - - assert_generated_controller_for :products - assert_generated_functional_test_for :products - assert_generated_helper_for :products - assert_generated_helper_test_for :products - end - - def test_controller_generates_namespaced_controller - run_generator('controller', %w(admin::products)) - - assert_generated_controller_for "admin::products" - assert_generated_functional_test_for "admin::products" - assert_generated_helper_for "admin::products" - assert_generated_helper_test_for "admin::products" - end - - def test_controller_generates_namespaced_and_not_namespaced_controllers - run_generator('controller', %w(products)) - - # We have to require the generated helper to show the problem because - # the test helpers just check for generated files and contents but - # do not actually load them. But they have to be loaded (as in a real environment) - # to make the second generator run fail - require "#{RAILS_ROOT}/app/helpers/products_helper" - - assert_nothing_raised do - begin - run_generator('controller', %w(admin::products)) - ensure - # cleanup - Object.send(:remove_const, :ProductsHelper) - end - end - end -end diff --git a/railties/test/generators/rails_helper_generator_test.rb b/railties/test/generators/rails_helper_generator_test.rb deleted file mode 100644 index 8d05f555e6..0000000000 --- a/railties/test/generators/rails_helper_generator_test.rb +++ /dev/null @@ -1,36 +0,0 @@ -require File.dirname(__FILE__) + '/generator_test_helper' - -class RailsHelperGeneratorTest < GeneratorTestCase - def test_helper_generates_helper - run_generator('helper', %w(products)) - - assert_generated_helper_for :products - assert_generated_helper_test_for :products - end - - def test_helper_generates_namespaced_helper - run_generator('helper', %w(admin::products)) - - assert_generated_helper_for "admin::products" - assert_generated_helper_test_for "admin::products" - end - - def test_helper_generates_namespaced_and_not_namespaced_helpers - run_generator('helper', %w(products)) - - # We have to require the generated helper to show the problem because - # the test helpers just check for generated files and contents but - # do not actually load them. But they have to be loaded (as in a real environment) - # to make the second generator run fail - require "#{RAILS_ROOT}/app/helpers/products_helper" - - assert_nothing_raised do - begin - run_generator('helper', %w(admin::products)) - ensure - # cleanup - Object.send(:remove_const, :ProductsHelper) - end - end - end -end diff --git a/railties/test/generators/rails_mailer_generator_test.rb b/railties/test/generators/rails_mailer_generator_test.rb deleted file mode 100644 index de61e6736d..0000000000 --- a/railties/test/generators/rails_mailer_generator_test.rb +++ /dev/null @@ -1,29 +0,0 @@ -require 'generators/generator_test_helper' - -class RailsMailerGeneratorTest < GeneratorTestCase - - def test_generates_mailer - run_generator('mailer', %w(Notifier reset_password)) - - assert_generated_model_for :notifier, 'ActionMailer::Base' do |model| - assert_has_method model, :reset_password do |name, body| - assert_equal [ - "subject 'Notifier#reset_password'", - "recipients ''", - "from ''", - "sent_on sent_at", - "", - "body :greeting => 'Hi,'" - ], - body.split("\n").map{|line| line.sub(' '*4, '') } - end - - assert_no_match /(self.default_url_options =|default_url_options\[.*\] =)/, model, - 'individual mailer models should not set default_url_options because the options are shared by all mailers' - end - - assert_generated_views_for :notifier, 'reset_password.erb' - assert_generated_unit_test_for :notifier, 'ActionMailer::TestCase' - assert_generated_file "test/fixtures/notifier/reset_password" - end -end diff --git a/railties/test/generators/rails_model_generator_test.rb b/railties/test/generators/rails_model_generator_test.rb deleted file mode 100644 index aea2abafba..0000000000 --- a/railties/test/generators/rails_model_generator_test.rb +++ /dev/null @@ -1,48 +0,0 @@ -require 'generators/generator_test_helper' - -class RailsModelGeneratorTest < GeneratorTestCase - - def test_model_generates_resources - run_generator('model', %w(Product name:string)) - - assert_generated_model_for :product - assert_generated_fixtures_for :products - assert_generated_migration :create_products - end - - def test_model_skip_migration_skips_migration - run_generator('model', %w(Product name:string --skip-migration)) - - assert_generated_model_for :product - assert_generated_fixtures_for :products - assert_skipped_migration :create_products - end - - def test_model_with_attributes_generates_resources_with_attributes - run_generator('model', %w(Product name:string supplier_id:integer created_at:timestamp)) - - assert_generated_model_for :product - assert_generated_fixtures_for :products - assert_generated_migration :create_products do |t| - assert_generated_column t, :name, :string - assert_generated_column t, :supplier_id, :integer - assert_generated_column t, :created_at, :timestamp - end - end - - def test_model_with_reference_attributes_generates_belongs_to_associations - run_generator('model', %w(Product name:string supplier:references)) - - assert_generated_model_for :product do |body| - assert body =~ /^\s+belongs_to :supplier/, "#{body.inspect} should contain 'belongs_to :supplier'" - end - end - - def test_model_with_belongs_to_attributes_generates_belongs_to_associations - run_generator('model', %w(Product name:string supplier:belongs_to)) - - assert_generated_model_for :product do |body| - assert body =~ /^\s+belongs_to :supplier/, "#{body.inspect} should contain 'belongs_to :supplier'" - end - end -end diff --git a/railties/test/generators/rails_model_subclass_generator_test.rb b/railties/test/generators/rails_model_subclass_generator_test.rb deleted file mode 100644 index 30066b5a3c..0000000000 --- a/railties/test/generators/rails_model_subclass_generator_test.rb +++ /dev/null @@ -1,15 +0,0 @@ -require 'generators/generator_test_helper' - -class RailsModelSubclassGeneratorTest < GeneratorTestCase - - def test_model_subclass_generates_resources - run_generator('model_subclass', %w(Car Product)) - - assert_generated_model_for :car, "Product" - assert_generated_unit_test_for :car - end - - def test_model_subclass_must_have_a_parent_class_name - assert_raise(Rails::Generator::UsageError) { run_generator('model_subclass', %w(Car)) } - end -end
\ No newline at end of file diff --git a/railties/test/generators/rails_resource_generator_test.rb b/railties/test/generators/rails_resource_generator_test.rb deleted file mode 100644 index 1f5bd0ef1e..0000000000 --- a/railties/test/generators/rails_resource_generator_test.rb +++ /dev/null @@ -1,29 +0,0 @@ -require 'generators/generator_test_helper' - -class RailsResourceGeneratorTest < GeneratorTestCase - def test_resource_generates_resources - run_generator('resource', %w(Product name:string)) - - assert_generated_controller_for :products - assert_generated_model_for :product - assert_generated_fixtures_for :products - assert_generated_functional_test_for :products - assert_generated_helper_for :products - assert_generated_helper_test_for :products - assert_generated_migration :create_products - assert_added_route_for :products - end - - def test_resource_skip_migration_skips_migration - run_generator('resource', %w(Product name:string --skip-migration)) - - assert_generated_controller_for :products - assert_generated_model_for :product - assert_generated_fixtures_for :products - assert_generated_functional_test_for :products - assert_generated_helper_for :products - assert_generated_helper_test_for :products - assert_skipped_migration :create_products - assert_added_route_for :products - end -end diff --git a/railties/test/generators/rails_scaffold_generator_test.rb b/railties/test/generators/rails_scaffold_generator_test.rb deleted file mode 100644 index 70829a77fd..0000000000 --- a/railties/test/generators/rails_scaffold_generator_test.rb +++ /dev/null @@ -1,150 +0,0 @@ -require 'generators/generator_test_helper' -require 'abstract_unit' - -class RailsScaffoldGeneratorTest < GeneratorTestCase - def test_scaffolded_names - g = Rails::Generator::Base.instance('scaffold', %w(ProductLine)) - assert_equal "ProductLines", g.controller_name - assert_equal "ProductLines", g.controller_class_name - assert_equal "ProductLine", g.controller_singular_name - assert_equal "product_lines", g.controller_plural_name - assert_equal "product_lines", g.controller_file_name - assert_equal "product_lines", g.controller_table_name - end - - def test_scaffold_generates_resources - - run_generator('scaffold', %w(Product name:string)) - - assert_generated_controller_for :products do |f| - - assert_has_method f, :index do |name, m| - assert_match /@products = Product\.all/, m, "#{name} should query products table" - end - - assert_has_method f, :show, :edit, :update, :destroy do |name, m| - assert_match /@product = Product\.find\(params\[:id\]\)/, m, "#{name.to_s} should query products table" - end - - assert_has_method f, :new do |name, m| - assert_match /@product = Product\.new/, m, "#{name.to_s} should instantiate a product" - end - - assert_has_method f, :create do |name, m| - assert_match /@product = Product\.new\(params\[:product\]\)/, m, "#{name.to_s} should instantiate a product" - assert_match /format.xml \{ render :xml => @product.errors, :status => :unprocessable_entity \}/, m, "#{name.to_s} should set status to :unprocessable_entity code for xml" - end - - end - - assert_generated_model_for :product - assert_generated_functional_test_for :products - assert_generated_unit_test_for :product - assert_generated_fixtures_for :products - assert_generated_helper_for :products - assert_generated_helper_test_for :products - assert_generated_stylesheet :scaffold - assert_generated_views_for :products, "index.html.erb", "new.html.erb", "edit.html.erb", "show.html.erb" - - assert_generated_migration :create_products - assert_added_route_for :products - end - - def test_scaffold_skip_migration_skips_migration - run_generator('scaffold', %w(Product name:string --skip-migration)) - - assert_generated_model_for :product - assert_generated_functional_test_for :products - assert_generated_unit_test_for :product - assert_generated_fixtures_for :products - assert_generated_helper_for :products - assert_generated_helper_test_for :products - assert_generated_stylesheet :scaffold - assert_generated_views_for :products, "index.html.erb","new.html.erb","edit.html.erb","show.html.erb" - assert_skipped_migration :create_products - assert_added_route_for :products - end - - def test_scaffold_generates_resources_with_attributes - run_generator('scaffold', %w(Product name:string supplier_id:integer created_at:timestamp)) - - assert_generated_controller_for :products do |f| - - assert_has_method f, :index do |name, m| - assert_match /@products = Product\.all/, m, "#{name} should query products table" - end - - assert_has_method f, :show, :edit, :update, :destroy do |name, m| - assert_match /@product = Product\.find\(params\[:id\]\)/, m, "#{name.to_s} should query products table" - end - - assert_has_method f, :new do |name, m| - assert_match /@product = Product\.new/, m, "#{name.to_s} should instantiate a product" - end - - assert_has_method f, :create do |name, m| - assert_match /@product = Product\.new\(params\[:product\]\)/, m, "#{name.to_s} should instantiate a product" - assert_match /format.xml \{ render :xml => @product.errors, :status => :unprocessable_entity \}/, m, "#{name.to_s} should set status to :unprocessable_entity code for xml" - end - - end - - assert_generated_model_for :product - assert_generated_functional_test_for :products - assert_generated_unit_test_for :product - assert_generated_fixtures_for :products - assert_generated_helper_for :products - assert_generated_helper_test_for :products - assert_generated_stylesheet :scaffold - assert_generated_views_for :products, "index.html.erb", "new.html.erb", "edit.html.erb", "show.html.erb" - - assert_generated_migration :create_products do |t| - assert_generated_column t, :name, :string - assert_generated_column t, :supplier_id, :integer - assert_generated_column t, :created_at, :timestamp - end - - assert_added_route_for :products - end - - def test_scaffolded_plural_names - Rails::Generator::Base.logger.expects(:warning) - g = Rails::Generator::Base.instance('scaffold', %w(ProductLines)) - assert_equal "ProductLines", g.controller_name - assert_equal "ProductLines", g.controller_class_name - assert_equal "ProductLine", g.controller_singular_name - assert_equal "product_lines", g.controller_plural_name - assert_equal "product_lines", g.controller_file_name - assert_equal "product_lines", g.controller_table_name - end - - def test_scaffold_plural_model_name_without_force_plural_generates_singular_model - run_generator('scaffold', %w(Products name:string)) - - assert_generated_model_for :product - assert_generated_functional_test_for :products - assert_generated_unit_test_for :product - assert_generated_fixtures_for :products - assert_generated_helper_for :products - assert_generated_helper_test_for :products - assert_generated_stylesheet :scaffold - assert_generated_views_for :products, "index.html.erb","new.html.erb","edit.html.erb","show.html.erb" - assert_skipped_migration :create_products - assert_added_route_for :products - end - - def test_scaffold_plural_model_name_with_force_plural_forces_plural_model - run_generator('scaffold', %w(Products name:string --force-plural)) - - assert_generated_model_for :products - assert_generated_functional_test_for :products - assert_generated_unit_test_for :products - assert_generated_fixtures_for :products - assert_generated_helper_for :products - assert_generated_helper_test_for :products - assert_generated_stylesheet :scaffold - assert_generated_views_for :products, "index.html.erb","new.html.erb","edit.html.erb","show.html.erb" - assert_skipped_migration :create_products - assert_added_route_for :products - end -end diff --git a/railties/test/generators/rails_template_runner_test.rb b/railties/test/generators/rails_template_runner_test.rb deleted file mode 100644 index 2da6bd59b5..0000000000 --- a/railties/test/generators/rails_template_runner_test.rb +++ /dev/null @@ -1,216 +0,0 @@ -require 'abstract_unit' -require 'generators/generator_test_helper' - -class RailsTemplateRunnerTest < GeneratorTestCase - def setup - Rails::Generator::Base.use_application_sources! - run_generator('app', [RAILS_ROOT]) - # generate empty template - @template_path = File.join(RAILS_ROOT, 'template.rb') - File.open(File.join(@template_path), 'w') {|f| f << '' } - - @git_plugin_uri = 'git://github.com/technoweenie/restful-authentication.git' - @svn_plugin_uri = 'svn://svnhub.com/technoweenie/restful-authentication/trunk' - end - - def teardown - super - rm_rf "#{RAILS_ROOT}/README" - rm_rf "#{RAILS_ROOT}/Rakefile" - rm_rf "#{RAILS_ROOT}/doc" - rm_rf "#{RAILS_ROOT}/lib" - rm_rf "#{RAILS_ROOT}/log" - rm_rf "#{RAILS_ROOT}/script" - rm_rf "#{RAILS_ROOT}/vendor" - rm_rf "#{RAILS_ROOT}/tmp" - rm_rf "#{RAILS_ROOT}/Capfile" - rm_rf @template_path - end - - def test_initialize_should_load_template - Rails::TemplateRunner.any_instance.expects(:load_template).with(@template_path) - silence_generator do - Rails::TemplateRunner.new(@template_path, RAILS_ROOT) - end - end - - def test_initialize_should_raise_error_on_missing_template_file - assert_raise(RuntimeError) do - silence_generator do - Rails::TemplateRunner.new('non/existent/path/to/template.rb', RAILS_ROOT) - end - end - end - - def test_file_should_write_data_to_file_path - run_template_method(:file, 'lib/test_file.rb', 'heres test data') - assert_generated_file_with_data 'lib/test_file.rb', 'heres test data' - end - - def test_file_should_write_block_contents_to_file_path - run_template_method(:file, 'lib/test_file.rb') { 'heres block data' } - assert_generated_file_with_data 'lib/test_file.rb', 'heres block data' - end - - def test_plugin_with_git_option_should_run_plugin_install - expects_run_ruby_script_with_command("script/plugin install #{@git_plugin_uri}") - run_template_method(:plugin, 'restful-authentication', :git => @git_plugin_uri) - end - - def test_plugin_with_svn_option_should_run_plugin_install - expects_run_ruby_script_with_command("script/plugin install #{@svn_plugin_uri}") - run_template_method(:plugin, 'restful-authentication', :svn => @svn_plugin_uri) - end - - def test_plugin_with_git_option_and_submodule_should_use_git_scm - Rails::Git.expects(:run).with("submodule add #{@git_plugin_uri} vendor/plugins/rest_auth") - run_template_method(:plugin, 'rest_auth', :git => @git_plugin_uri, :submodule => true) - end - - def test_plugin_with_no_options_should_skip_method - Rails::TemplateRunner.any_instance.expects(:run).never - run_template_method(:plugin, 'rest_auth', {}) - end - - def test_gem_should_put_gem_dependency_in_enviroment - run_template_method(:gem, 'will-paginate') - assert_rails_initializer_includes("config.gem 'will-paginate'") - end - - def test_gem_with_options_should_include_options_in_gem_dependency_in_environment - run_template_method(:gem, 'mislav-will-paginate', :lib => 'will-paginate', :source => 'http://gems.github.com') - assert_rails_initializer_includes("config.gem 'mislav-will-paginate', :lib => 'will-paginate', :source => 'http://gems.github.com'") - end - - def test_gem_with_env_string_should_put_gem_dependency_in_specified_environment - run_template_method(:gem, 'rspec', :env => 'test') - assert_generated_file_with_data('config/environments/test.rb', "config.gem 'rspec'", 'test') - end - - def test_gem_with_env_array_should_put_gem_dependency_in_specified_environments - run_template_method(:gem, 'quietbacktrace', :env => %w[ development test ]) - assert_generated_file_with_data('config/environments/development.rb', "config.gem 'quietbacktrace'") - assert_generated_file_with_data('config/environments/test.rb', "config.gem 'quietbacktrace'") - end - - def test_gem_with_lib_option_set_to_false_should_put_gem_dependency_in_enviroment_correctly - run_template_method(:gem, 'mislav-will-paginate', :lib => false, :source => 'http://gems.github.com') - assert_rails_initializer_includes("config.gem 'mislav-will-paginate', :lib => false, :source => 'http://gems.github.com'") - end - - def test_environment_should_include_data_in_environment_initializer_block - load_paths = 'config.load_paths += %w["#{RAILS_ROOT}/app/extras"]' - run_template_method(:environment, load_paths) - assert_rails_initializer_includes(load_paths) - end - - def test_environment_with_block_should_include_block_contents_in_environment_initializer_block - run_template_method(:environment) do - '# This wont be added' - '# This will be added' - end - assert_rails_initializer_includes('# This will be added') - end - - def test_git_with_symbol_should_run_command_using_git_scm - Rails::Git.expects(:run).once.with('init') - run_template_method(:git, :init) - end - - def test_git_with_hash_should_run_each_command_using_git_scm - Rails::Git.expects(:run).times(2) - run_template_method(:git, {:init => '', :add => '.'}) - end - - def test_vendor_should_write_data_to_file_in_vendor - run_template_method(:vendor, 'vendor_file.rb', '# vendor data') - assert_generated_file_with_data('vendor/vendor_file.rb', '# vendor data') - end - - def test_lib_should_write_data_to_file_in_lib - run_template_method(:lib, 'my_library.rb', 'class MyLibrary') - assert_generated_file_with_data('lib/my_library.rb', 'class MyLibrary') - end - - def test_rakefile_should_write_date_to_file_in_lib_tasks - run_template_method(:rakefile, 'myapp.rake', 'task :run => [:environment]') - assert_generated_file_with_data('lib/tasks/myapp.rake', 'task :run => [:environment]') - end - - def test_initializer_should_write_date_to_file_in_config_initializers - run_template_method(:initializer, 'constants.rb', 'MY_CONSTANT = 42') - assert_generated_file_with_data('config/initializers/constants.rb', 'MY_CONSTANT = 42') - end - - def test_generate_should_run_script_generate_with_argument_and_options - expects_run_ruby_script_with_command('script/generate model MyModel') - run_template_method(:generate, 'model', 'MyModel') - end - - def test_rake_should_run_rake_command_with_development_env - expects_run_with_command('rake log:clear RAILS_ENV=development') - run_template_method(:rake, 'log:clear') - end - - def test_rake_with_env_option_should_run_rake_command_in_env - expects_run_with_command('rake log:clear RAILS_ENV=production') - run_template_method(:rake, 'log:clear', :env => 'production') - end - - def test_rake_with_sudo_option_should_run_rake_command_with_sudo - expects_run_with_command('sudo rake log:clear RAILS_ENV=development') - run_template_method(:rake, 'log:clear', :sudo => true) - end - - def test_capify_should_run_the_capify_command - expects_run_with_command('capify .') - run_template_method(:capify!) - end - - def test_freeze_should_freeze_rails_edge - expects_run_with_command('rake rails:freeze:edge') - run_template_method(:freeze!) - end - - def test_route_should_add_data_to_the_routes_block_in_config_routes - route_command = "map.route '/login', :controller => 'sessions', :action => 'new'" - run_template_method(:route, route_command) - assert_generated_file_with_data 'config/routes.rb', route_command - end - - def test_run_ruby_script_should_add_ruby_to_command_in_win32_environment - ruby_command = RUBY_PLATFORM =~ /win32/ ? 'ruby ' : '' - expects_run_with_command("#{ruby_command}script/generate model MyModel") - run_template_method(:generate, 'model', 'MyModel') - end - - protected - def run_template_method(method_name, *args, &block) - silence_generator do - @template_runner = Rails::TemplateRunner.new(@template_path, RAILS_ROOT) - @template_runner.send(method_name, *args, &block) - end - end - - def expects_run_with_command(command) - Rails::TemplateRunner.any_instance.stubs(:run).once.with(command, false) - end - - def expects_run_ruby_script_with_command(command) - Rails::TemplateRunner.any_instance.stubs(:run_ruby_script).once.with(command,false) - end - - def assert_rails_initializer_includes(data, message = nil) - message ||= "Rails::Initializer should include #{data}" - assert_generated_file 'config/environment.rb' do |body| - assert_match(/#{Regexp.escape("Rails::Initializer.run do |config|")}.+#{Regexp.escape(data)}.+end/m, body, message) - end - end - - def assert_generated_file_with_data(file, data, message = nil) - message ||= "#{file} should include '#{data}'" - assert_generated_file(file) do |file| - assert_match(/#{Regexp.escape(data)}/,file, message) - end - end -end
\ No newline at end of file diff --git a/railties/test/generators/resource_generator_test.rb b/railties/test/generators/resource_generator_test.rb new file mode 100644 index 0000000000..876ddbf84e --- /dev/null +++ b/railties/test/generators/resource_generator_test.rb @@ -0,0 +1,106 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/resource/resource_generator' + +class ResourceGeneratorTest < GeneratorsTestCase + + def setup + super + routes = Rails::Generators::ResourceGenerator.source_root + routes = File.join(routes, "..", "..", "app", "templates", "config", "routes.rb") + destination = File.join(destination_root, "config") + + FileUtils.mkdir_p(destination) + FileUtils.cp File.expand_path(routes), destination + end + + def test_help_with_inherited_options + content = run_generator ["--help"] + assert_match /ActiveRecord options:/, content + assert_match /TestUnit options:/, content + end + + def test_files_from_inherited_invocation + run_generator + + %w( + app/models/account.rb + test/unit/account_test.rb + test/fixtures/accounts.yml + ).each { |path| assert_file path } + + assert_migration "db/migrate/create_accounts.rb" + end + + def test_inherited_invocations_with_attributes + run_generator ["account", "name:string"] + assert_migration "db/migrate/create_accounts.rb", /t.string :name/ + end + + def test_resource_controller_with_pluralized_class_name + run_generator + assert_file "app/controllers/accounts_controller.rb", /class AccountsController < ApplicationController/ + assert_file "test/functional/accounts_controller_test.rb", /class AccountsControllerTest < ActionController::TestCase/ + + assert_file "app/helpers/accounts_helper.rb", /module AccountsHelper/ + assert_file "test/unit/helpers/accounts_helper_test.rb", /class AccountsHelperTest < ActionView::TestCase/ + end + + def test_resource_controller_with_actions + run_generator ["account", "--actions", "index", "new"] + + assert_file "app/controllers/accounts_controller.rb" do |controller| + assert_instance_method controller, :index + assert_instance_method controller, :new + end + + assert_file "app/views/accounts/index.html.erb" + assert_file "app/views/accounts/new.html.erb" + end + + def test_resource_routes_are_added + run_generator + + assert_file "config/routes.rb" do |route| + assert_match /map\.resources :accounts$/, route + end + end + + def test_singleton_resource + run_generator ["account", "--singleton"] + + assert_file "config/routes.rb" do |route| + assert_match /map\.resource :account$/, route + end + end + + def test_plural_names_are_singularized + content = run_generator ["accounts"] + assert_file "app/models/account.rb", /class Account < ActiveRecord::Base/ + assert_file "test/unit/account_test.rb", /class AccountTest/ + assert_match /Plural version of the model detected, using singularized version. Override with --force-plural./, content + end + + def test_plural_names_can_be_forced + content = run_generator ["accounts", "--force-plural"] + assert_file "app/models/accounts.rb", /class Accounts < ActiveRecord::Base/ + assert_file "test/unit/accounts_test.rb", /class AccountsTest/ + assert_no_match /Plural version of the model detected/, content + end + + def test_route_is_removed_on_revoke + run_generator + run_generator ["account"], :behavior => :revoke + + assert_file "config/routes.rb" do |route| + assert_no_match /map\.resources :accounts$/, route + end + end + + protected + + def run_generator(args=["account"], config={}) + silence(:stdout) { Rails::Generators::ResourceGenerator.start args, config.merge(:destination_root => destination_root) } + end + +end diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb new file mode 100644 index 0000000000..024ea439ef --- /dev/null +++ b/railties/test/generators/scaffold_controller_generator_test.rb @@ -0,0 +1,112 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/scaffold_controller/scaffold_controller_generator' + +class ScaffoldControllerGeneratorTest < GeneratorsTestCase + + def test_controller_skeleton_is_created + run_generator + + assert_file "app/controllers/users_controller.rb" do |content| + assert_match /class UsersController < ApplicationController/, content + + assert_instance_method content, :index do |m| + assert_match /@users = User\.all/, m + end + + assert_instance_method content, :show do |m| + assert_match /@user = User\.find\(params\[:id\]\)/, m + end + + assert_instance_method content, :new do |m| + assert_match /@user = User\.new/, m + end + + assert_instance_method content, :edit do |m| + assert_match /@user = User\.find\(params\[:id\]\)/, m + end + + assert_instance_method content, :create do |m| + assert_match /@user = User\.new\(params\[:user\]\)/, m + assert_match /@user\.save/, m + assert_match /@user\.errors/, m + end + + assert_instance_method content, :update do |m| + assert_match /@user = User\.find\(params\[:id\]\)/, m + assert_match /@user\.update_attributes\(params\[:user\]\)/, m + assert_match /@user\.errors/, m + end + + assert_instance_method content, :destroy do |m| + assert_match /@user = User\.find\(params\[:id\]\)/, m + assert_match /@user\.destroy/, m + end + end + end + + def test_helper_are_invoked_with_a_pluralized_name + run_generator + assert_file "app/helpers/users_helper.rb", /module UsersHelper/ + assert_file "test/unit/helpers/users_helper_test.rb", /class UsersHelperTest < ActionView::TestCase/ + end + + def test_views_are_generated + run_generator + + %w( + index + edit + new + show + ).each { |view| assert_file "app/views/users/#{view}.html.erb" } + assert_file "app/views/layouts/users.html.erb" + end + + def test_functional_tests + run_generator + + assert_file "test/functional/users_controller_test.rb" do |content| + assert_match /class UsersControllerTest < ActionController::TestCase/, content + assert_match /test "should get index"/, content + end + end + + def test_generates_singleton_controller + run_generator ["User", "name:string", "age:integer", "--singleton"] + + assert_file "app/controllers/users_controller.rb" do |content| + assert_no_match /def index/, content + end + + assert_file "test/functional/users_controller_test.rb" do |content| + assert_no_match /test "should get index"/, content + end + + assert_no_file "app/views/users/index.html.erb" + end + + def test_skip_helper_if_required + run_generator ["User", "name:string", "age:integer", "--no-helper"] + assert_no_file "app/helpers/users_helper.rb" + assert_no_file "test/unit/helpers/users_helper_test.rb" + end + + def test_skip_layout_if_required + run_generator ["User", "name:string", "age:integer", "--no-layout"] + assert_no_file "app/views/layouts/users.html.erb" + end + + def test_error_is_shown_if_orm_does_not_provide_interface + error = capture(:stderr){ run_generator ["User", "--orm=unknown"] } + assert_equal "Could not load Unknown::Generators::ActionORM, skipping controller. " << + "Error: no such file to load -- generators/unknown.\n", error + end + + protected + + def run_generator(args=["User", "name:string", "age:integer"]) + silence(:stdout) { Rails::Generators::ScaffoldControllerGenerator.start args, :destination_root => destination_root } + end + +end diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb new file mode 100644 index 0000000000..05eadd3460 --- /dev/null +++ b/railties/test/generators/scaffold_generator_test.rb @@ -0,0 +1,129 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/scaffold/scaffold_generator' + +class ScaffoldGeneratorTest < GeneratorsTestCase + + def setup + super + routes = Rails::Generators::ResourceGenerator.source_root + routes = File.join(routes, "..", "..", "app", "templates", "config", "routes.rb") + destination = File.join(destination_root, "config") + + FileUtils.mkdir_p(destination) + FileUtils.cp File.expand_path(routes), destination + end + + def test_scaffold_on_invoke + run_generator + + # Model + assert_file "app/models/product_line.rb", /class ProductLine < ActiveRecord::Base/ + assert_file "test/unit/product_line_test.rb", /class ProductLineTest < ActiveSupport::TestCase/ + assert_file "test/fixtures/product_lines.yml" + assert_migration "db/migrate/create_product_lines.rb" + + # Route + assert_file "config/routes.rb" do |route| + assert_match /map\.resources :product_lines$/, route + end + + # Controller + assert_file "app/controllers/product_lines_controller.rb" do |content| + assert_match /class ProductLinesController < ApplicationController/, content + + assert_instance_method content, :index do |m| + assert_match /@product_lines = ProductLine\.all/, m + end + + assert_instance_method content, :show do |m| + assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m + end + + assert_instance_method content, :new do |m| + assert_match /@product_line = ProductLine\.new/, m + end + + assert_instance_method content, :edit do |m| + assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m + end + + assert_instance_method content, :create do |m| + assert_match /@product_line = ProductLine\.new\(params\[:product_line\]\)/, m + assert_match /@product_line\.save/, m + assert_match /@product_line\.errors/, m + end + + assert_instance_method content, :update do |m| + assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m + assert_match /@product_line\.update_attributes\(params\[:product_line\]\)/, m + assert_match /@product_line\.errors/, m + end + + assert_instance_method content, :destroy do |m| + assert_match /@product_line = ProductLine\.find\(params\[:id\]\)/, m + assert_match /@product_line\.destroy/, m + end + end + + assert_file "test/functional/product_lines_controller_test.rb", + /class ProductLinesControllerTest < ActionController::TestCase/ + + # Views + %w( + index + edit + new + show + ).each { |view| assert_file "app/views/product_lines/#{view}.html.erb" } + assert_file "app/views/layouts/product_lines.html.erb" + + # Helpers + assert_file "app/helpers/product_lines_helper.rb" + assert_file "test/unit/helpers/product_lines_helper_test.rb" + + # Stylesheets + assert_file "public/stylesheets/scaffold.css" + end + + def test_scaffold_on_revoke + run_generator + run_generator :behavior => :revoke + + # Model + assert_no_file "app/models/product_line.rb" + assert_no_file "test/unit/product_line_test.rb" + assert_no_file "test/fixtures/product_lines.yml" + assert_no_migration "db/migrate/create_product_lines.rb" + + # Route + assert_file "config/routes.rb" do |route| + assert_no_match /map\.resources :product_lines$/, route + end + + # Controller + assert_no_file "app/controllers/product_lines_controller.rb" + assert_no_file "test/functional/product_lines_controller_test.rb" + + # Views + assert_no_file "app/views/product_lines" + assert_no_file "app/views/layouts/product_lines.html.erb" + + # Helpers + assert_no_file "app/helpers/product_lines_helper.rb" + assert_no_file "test/unit/helpers/product_lines_helper_test.rb" + + # Stylesheets (should not be removed) + assert_file "public/stylesheets/scaffold.css" + end + + protected + + def run_generator(config={}) + silence(:stdout) do + Rails::Generators::ScaffoldGenerator.start ["product_line", "title:string", "price:integer"], + config.merge(:destination_root => destination_root) + end + end + +end diff --git a/railties/test/generators/session_migration_generator_test.rb b/railties/test/generators/session_migration_generator_test.rb new file mode 100644 index 0000000000..f83109800b --- /dev/null +++ b/railties/test/generators/session_migration_generator_test.rb @@ -0,0 +1,23 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/session_migration/session_migration_generator' + +class SessionMigrationGeneratorTest < GeneratorsTestCase + + def test_session_migration_with_default_name + run_generator + assert_migration "db/migrate/add_sessions_table.rb", /class AddSessionsTable < ActiveRecord::Migration/ + end + + def test_session_migration_with_given_name + run_generator ["create_session_table"] + assert_migration "db/migrate/create_session_table.rb", /class CreateSessionTable < ActiveRecord::Migration/ + end + + protected + + def run_generator(args=[]) + silence(:stdout) { Rails::Generators::SessionMigrationGenerator.start args, :destination_root => destination_root } + end + +end diff --git a/railties/test/generators/stylesheets_generator_test.rb b/railties/test/generators/stylesheets_generator_test.rb new file mode 100644 index 0000000000..02082d5cc8 --- /dev/null +++ b/railties/test/generators/stylesheets_generator_test.rb @@ -0,0 +1,24 @@ +require 'abstract_unit' +require 'generators/generators_test_helper' +require 'generators/rails/stylesheets/stylesheets_generator' + +class StylesheetsGeneratorTest < GeneratorsTestCase + + def test_copy_stylesheets + run_generator + assert_file "public/stylesheets/scaffold.css" + end + + def test_stylesheets_are_not_deleted_on_revoke + run_generator + run_generator :behavior => :revoke + assert_file "public/stylesheets/scaffold.css" + end + + protected + + def run_generator(config={}) + silence(:stdout) { Rails::Generators::StylesheetsGenerator.start [], config.merge(:destination_root => destination_root) } + end + +end diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb new file mode 100644 index 0000000000..89d52dd170 --- /dev/null +++ b/railties/test/generators_test.rb @@ -0,0 +1,156 @@ +require File.join(File.dirname(__FILE__), 'generators', 'generators_test_helper') +require 'generators/rails/model/model_generator' +require 'generators/test_unit/model/model_generator' +require 'mocha' + +class GeneratorsTest < GeneratorsTestCase + def test_invoke_when_generator_is_not_found + output = capture(:stdout){ Rails::Generators.invoke :unknown } + assert_equal "Could not find generator unknown.\n", 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 + end + + def test_invoke_with_default_values + Rails::Generators::ModelGenerator.expects(:start).with(["Account"], {}) + Rails::Generators.invoke :model, ["Account"] + end + + def test_invoke_with_config_values + Rails::Generators::ModelGenerator.expects(:start).with(["Account"], :behavior => :skip) + Rails::Generators.invoke :model, ["Account"], :behavior => :skip + end + + def test_find_by_namespace_without_base_or_context + assert_nil Rails::Generators.find_by_namespace(:model) + end + + def test_find_by_namespace_with_base + klass = Rails::Generators.find_by_namespace(:model, :rails) + assert klass + assert_equal "rails:generators:model", klass.namespace + end + + def test_find_by_namespace_with_context + klass = Rails::Generators.find_by_namespace(:test_unit, nil, :model) + assert klass + assert_equal "test_unit:generators:model", klass.namespace + end + + def test_find_by_namespace_add_generators_to_raw_lookups + klass = Rails::Generators.find_by_namespace("test_unit:model") + assert klass + assert_equal "test_unit:generators:model", klass.namespace + end + + def test_find_by_namespace_lookup_to_the_rails_root_folder + klass = Rails::Generators.find_by_namespace(:fixjour) + assert klass + assert_equal "fixjour", klass.namespace + end + + def test_find_by_namespace_lookup_to_deep_rails_root_folders + klass = Rails::Generators.find_by_namespace(:fixjour, :active_record) + assert klass + assert_equal "active_record:generators:fixjour", klass.namespace + end + + def test_find_by_namespace_lookup_traverse_folders + klass = Rails::Generators.find_by_namespace(:javascripts, :rails) + assert klass + assert_equal "rails:generators:javascripts", klass.namespace + end + + def test_find_by_namespace_lookup_to_vendor_folders + klass = Rails::Generators.find_by_namespace(:mspec) + assert klass + assert_equal "mspec", klass.namespace + end + + def test_builtin_generators + assert Rails::Generators.builtin.include? %w(rails model) + end + + def test_rails_generators_help_with_builtin_information + output = capture(:stdout){ Rails::Generators.help } + assert_match /model/, output + assert_match /scaffold_controller/, output + end + + def test_rails_generators_with_others_information + output = capture(:stdout){ Rails::Generators.help }.split("\n").last + assert_equal "Others: active_record:fixjour, fixjour, mspec, rails:javascripts, wrong.", output + end + + def test_warning_is_shown_if_generator_cant_be_loaded + output = capture(:stderr){ Rails::Generators.find_by_namespace(:wrong) } + assert_match /\[WARNING\] Could not load generator at/, output + assert_match /Error: uninitialized constant Rails::Generator/, output + end + + def test_no_color_sets_proper_shell + Rails::Generators.no_color! + assert_equal Thor::Shell::Basic, Thor::Base.shell + ensure + Thor::Base.shell = Thor::Shell::Color + end + + def test_rails_root_templates + template = File.join(RAILS_ROOT, "lib", "templates", "active_record", "model", "model.rb") + + # Create template + mkdir_p(File.dirname(template)) + File.open(template, 'w'){ |f| f.write "empty" } + + output = capture(:stdout) do + Rails::Generators.invoke :model, ["user"], :destination_root => destination_root + end + + assert_file "app/models/user.rb" do |content| + assert_equal "empty", content + end + ensure + rm_rf File.dirname(template) + end + + def test_fallbacks_for_generators_on_find_by_namespace + Rails::Generators.fallbacks[:remarkable] = :test_unit + klass = Rails::Generators.find_by_namespace(:plugin, :remarkable) + assert klass + assert_equal "test_unit:generators:plugin", klass.namespace + end + + def test_fallbacks_for_generators_on_invoke + Rails::Generators.fallbacks[:shoulda] = :test_unit + TestUnit::Generators::ModelGenerator.expects(:start).with(["Account"], {}) + Rails::Generators.invoke "shoulda:model", ["Account"] + end + + def test_nested_fallbacks_for_generators + Rails::Generators.fallbacks[:super_shoulda] = :shoulda + TestUnit::Generators::ModelGenerator.expects(:start).with(["Account"], {}) + Rails::Generators.invoke "super_shoulda:model", ["Account"] + end + + def test_developer_options_are_overwriten_by_user_options + Rails::Generators.options[:new_generator] = { :generate => false } + + klass = Class.new(Rails::Generators::Base) do + def self.name + "NewGenerator" + end + + class_option :generate, :default => true + end + + assert_equal false, klass.class_options[:generate].default + end + + def test_source_paths_for_not_namespaced_generators + mspec = Rails::Generators.find_by_namespace :mspec + assert mspec.source_paths.include?(File.join(RAILS_ROOT, "lib", "templates", "mspec")) + end +end diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb index 550cb7de76..1fecd62995 100644 --- a/railties/test/initializer_test.rb +++ b/railties/test/initializer_test.rb @@ -1,5 +1,6 @@ require 'abstract_unit' require 'initializer' +require 'generators' require 'action_view' require 'action_mailer' @@ -10,8 +11,19 @@ module Rails def self.configuration Rails::Configuration.new end + + module Generators + def self.clear_aliases! + @aliases = nil + end + + def self.clear_options! + @@options = nil + end + end end + class ConfigurationMock < Rails::Configuration attr_reader :environment_path @@ -278,6 +290,87 @@ class InitializerPluginLoadingTests < Test::Unit::TestCase end end +class InitializerGeneratorsTests < Test::Unit::TestCase + + def setup + @configuration = Rails::Configuration.new + @initializer = Rails::Initializer.default + @initializer.config = @configuration + end + + def test_generators_default_values + assert_equal(true, @configuration.generators.colorize_logging) + assert_equal({}, @configuration.generators.aliases) + assert_equal({}, @configuration.generators.options) + end + + def test_generators_set_rails_options + @configuration.generators.orm = :datamapper + @configuration.generators.test_framework = :rspec + expected = { :rails => { :orm => :datamapper, :test_framework => :rspec } } + assert_equal expected, @configuration.generators.options + end + + def test_generators_set_rails_aliases + @configuration.generators.aliases = { :rails => { :test_framework => "-w" } } + expected = { :rails => { :test_framework => "-w" } } + assert_equal expected, @configuration.generators.aliases + end + + def test_generators_aliases_and_options_on_initialization + @configuration.generators.rails :aliases => { :test_framework => "-w" } + @configuration.generators.orm :datamapper + @configuration.generators.test_framework :rspec + + @initializer.run(:initialize_generators) + + assert_equal :rspec, Rails::Generators.options[:rails][:test_framework] + assert_equal "-w", Rails::Generators.aliases[:rails][:test_framework] + end + + def test_generators_no_color_on_initialization + @configuration.generators.colorize_logging = false + @initializer.run(:initialize_generators) + assert_equal Thor::Base.shell, Thor::Shell::Basic + end + + def test_generators_with_hashes_for_options_and_aliases + @configuration.generators do |g| + g.orm :datamapper, :migration => false + g.plugin :aliases => { :generator => "-g" }, + :generator => true + end + + expected = { + :rails => { :orm => :datamapper }, + :plugin => { :generator => true }, + :datamapper => { :migration => false } + } + + assert_equal expected, @configuration.generators.options + assert_equal({ :plugin => { :generator => "-g" } }, @configuration.generators.aliases) + end + + def test_generators_with_hashes_are_deep_merged + @configuration.generators do |g| + g.orm :datamapper, :migration => false + g.plugin :aliases => { :generator => "-g" }, + :generator => true + end + @initializer.run(:initialize_generators) + + assert Rails::Generators.aliases.size >= 1 + assert Rails::Generators.options.size >= 1 + end + + protected + + def teardown + Rails::Generators.clear_aliases! + Rails::Generators.clear_options! + end +end + class InitializerSetupI18nTests < Test::Unit::TestCase def test_no_config_locales_dir_present_should_return_empty_load_path File.stubs(:exist?).returns(false) diff --git a/railties/test/rails_generator_test.rb b/railties/test/rails_generator_test.rb deleted file mode 100644 index 38bd90dcc1..0000000000 --- a/railties/test/rails_generator_test.rb +++ /dev/null @@ -1,148 +0,0 @@ -require 'test/unit' - -# Optionally load RubyGems. -begin - require 'rubygems' -rescue LoadError -end - -# 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 - -# And what we need from ActionView -module ActionView - module Helpers - module ActiveRecordHelper; end - class InstanceTag; end - end -end - - -# Must set before requiring generator libs. -if defined?(RAILS_ROOT) - RAILS_ROOT.replace "#{File.dirname(__FILE__)}/fixtures" -else - RAILS_ROOT = "#{File.dirname(__FILE__)}/fixtures" -end - -$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../lib" -require 'initializer' - -# Mocks out the configuration -module Rails - def self.configuration - Rails::Configuration.new - end -end - -require 'rails_generator' - -class RailsGeneratorTest < Test::Unit::TestCase - BUILTINS = %w(controller integration_test mailer migration model observer plugin resource scaffold session_migration) - CAPITALIZED_BUILTINS = BUILTINS.map { |b| b.capitalize } - - def setup - ActiveRecord::Base.pluralize_table_names = true - @initializer = Rails::Initializer.default - @initializer.config = Rails.configuration - @initializer.run(:set_root_path) - end - - def test_sources - expected = [:lib, :vendor, - "plugins (vendor/plugins)".to_sym, # <plugin>/generators and <plugin>/rails_generators - :user, - :RubyGems, :RubyGems, # gems named <x>_generator, gems containing /rails_generator/ folder - :builtin] - expected.delete(:RubyGems) unless Object.const_defined?(:Gem) - assert_equal expected, Rails::Generator::Base.sources.map { |s| s.label } - end - - def test_lookup_builtins - (BUILTINS + CAPITALIZED_BUILTINS).each do |name| - assert_nothing_raised do - spec = Rails::Generator::Base.lookup(name) - assert_not_nil spec - assert_kind_of Rails::Generator::Spec, spec - - klass = spec.klass - assert klass < Rails::Generator::Base - assert_equal spec, klass.spec - end - end - end - - def test_autolookup - assert_nothing_raised { ControllerGenerator } - assert_nothing_raised { ModelGenerator } - end - - def test_lookup_missing_generator - assert_raise Rails::Generator::GeneratorError do - Rails::Generator::Base.lookup('missing').klass - end - end - - def test_lookup_missing_class - spec = nil - assert_nothing_raised { spec = Rails::Generator::Base.lookup('missing_class') } - assert_not_nil spec - assert_kind_of Rails::Generator::Spec, spec - assert_raise(NameError) { spec.klass } - end - - def test_generator_usage - (BUILTINS - ["session_migration"]).each do |name| - assert_raise(Rails::Generator::UsageError, "Generator '#{name}' should raise an error without arguments") { - Rails::Generator::Base.instance(name) - } - end - end - - def test_generator_spec - spec = Rails::Generator::Base.lookup('working') - assert_equal 'working', spec.name - assert_match(/#{spec.path}$/, "#{RAILS_ROOT}/lib/generators/working") - assert_equal :lib, spec.source - assert_nothing_raised { assert_match(/WorkingGenerator$/, spec.klass.name) } - end - - def test_named_generator_attributes - g = Rails::Generator::Base.instance('working', %w(admin/foo bar baz)) - assert_equal 'admin/foo', g.name - assert_equal %w(admin), g.class_path - assert_equal 'Admin', g.class_nesting - assert_equal 'Admin::Foo', g.class_name - assert_equal 'foo', g.singular_name - assert_equal 'foos', g.plural_name - assert_equal g.singular_name, g.file_name - assert_equal "admin_#{g.plural_name}", g.table_name - assert_equal %w(bar baz), g.args - end - - def test_named_generator_attributes_without_pluralized - ActiveRecord::Base.pluralize_table_names = false - g = Rails::Generator::Base.instance('working', %w(admin/foo bar baz)) - assert_equal "admin_#{g.singular_name}", g.table_name - end - - def test_session_migration_generator_with_pluralization - g = Rails::Generator::Base.instance('session_migration') - assert_equal 'session'.pluralize, g.send(:default_session_table_name) - ActiveRecord::Base.pluralize_table_names = false - assert_equal 'session', g.send(:default_session_table_name) - end - - def test_scaffold_controller_name - # Default behaviour is use the model name - g = Rails::Generator::Base.instance('scaffold', %w(Product)) - assert_equal "Products", g.controller_name - end -end diff --git a/railties/test/secret_key_generation_test.rb b/railties/test/secret_key_generation_test.rb deleted file mode 100644 index 2c7c3d5dfe..0000000000 --- a/railties/test/secret_key_generation_test.rb +++ /dev/null @@ -1,38 +0,0 @@ -require 'abstract_unit' - -# Must set before requiring generator libs. -if defined?(RAILS_ROOT) - RAILS_ROOT.replace "#{File.dirname(__FILE__)}/fixtures" -else - RAILS_ROOT = "#{File.dirname(__FILE__)}/fixtures" -end - -$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../lib" - -require 'initializer' - -# Mocks out the configuration -module Rails - def self.configuration - Rails::Configuration.new - end -end - -require 'rails_generator' -require 'rails_generator/secret_key_generator' -require 'rails_generator/generators/applications/app/app_generator' - -class SecretKeyGenerationTest < ActiveSupport::TestCase - SECRET_KEY_MIN_LENGTH = 128 - APP_NAME = "foo" - - def setup - @generator = Rails::SecretKeyGenerator.new(APP_NAME) - end - - def test_secret_key_generation - assert_deprecated /ActiveSupport::SecureRandom\.hex\(64\)/ do - assert @generator.generate_secret.length >= SECRET_KEY_MIN_LENGTH - end - end -end |