diff options
Diffstat (limited to 'railties')
46 files changed, 498 insertions, 332 deletions
diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile index 2958d1b053..fbe3d46367 100644 --- a/railties/guides/source/configuring.textile +++ b/railties/guides/source/configuring.textile @@ -60,7 +60,7 @@ config.asset_path = proc { |path| "/blog/public#{path}" } * +config.autoload_once_paths+ accepts an array of paths from which Rails will autoload constants that won't be wiped per request. Relevant if +config.cache_classes+ is false, which is the case in development mode by default. Otherwise, all autoloading happens only once. All elements of this array must also be in +autoload_paths+. Default is an empty array. -* +config.autoload_paths+ accepts an array of paths from which Rails will autoload constants. By default that's the abolute paths of +app/mailers+, +app/assets+, +app/controllers+, +app/models+, and +app/helpers+. Please use <tt>+=</tt> to extend the default list. +* +config.autoload_paths+ accepts an array of paths from which Rails will autoload constants. Default is all directories under +app+. * +config.cache_classes+ controls whether or not application classes and modules should be reloaded on each request. Defaults to true in development mode, and false in test and production modes. Can also be enabled with +threadsafe!+. @@ -68,51 +68,43 @@ config.asset_path = proc { |path| "/blog/public#{path}" } * +config.cache_store+ configures which cache store to use for Rails caching. Options include one of the symbols +:memory_store+, +:file_store+, +:mem_cache_store+, or an object that implements the cache API. Defaults to +:file_store+ if the directory +tmp/cache+ exists, and to +:memory_store+ otherwise. -* +config.colorize_logging+ specifies whether or not to use ANSI color codes when logging information. Defaults to _true_. +* +config.colorize_logging+ specifies whether or not to use ANSI color codes when logging information. Defaults to true. -* +config.consider_all_requests_local+ is generally set to +true+ during development and +false+ during production; if it is set to +true+, then any error will cause detailed debugging information to be dumped in the HTTP response. For finer-grained control, set this to +false+ and implement +local_request?+ in controllers to specify which requests should provide debugging information on errors. +* +config.consider_all_requests_local+ is a flag. If true then any error will cause detailed debugging information to be dumped in the HTTP response, and the +Rails::Info+ controller will show the application runtime context in +/rails/info/properties+. True by default in development and test environments, and false in production mode. For finer-grained control, set this to false and implement +local_request?+ in controllers to specify which requests should provide debugging information on errors. -* +config.controller_paths+ configures where Rails can find controllers for this application. +* +config.dependency_loading+ is a flag that allows you to disable constant autoloading setting it to false. It only has effect if +config.cache_classes+ is true, which it is by default in production mode. This flag is set to false by +config.threadsafe!+. -* +config.dependency_loading+ enables or disables dependency loading during the request cycle. Setting dependency_loading to _true_ will allow new classes to be loaded during a request and setting it to _false_ will disable this behavior. Can also be enabled with +threadsafe!+. - -* +config.eager_load_paths+ accepts an array of paths from which Rails will eager load on boot if cache classes is enabled. Defaults to every folder in the +app+ directory of the application. All elements of this array must also be in +load_paths+. +* +config.eager_load_paths+ accepts an array of paths from which Rails will eager load on boot if cache classes is enabled. Defaults to every folder in the +app+ directory of the application. * +config.encoding+ sets up the application-wide encoding. Defaults to UTF-8. * +config.filter_parameters+ used for filtering out the parameters that you don't want shown in the logs, such as passwords or credit card numbers. -* +config.force_ssl+ forcing all requests to be under HTTPS protocol by using +Rack::SSL+ middleware. This will secure your application from a session hijack attempt. - -* +config.helper_paths+ configures where Rails can find helpers for this application. - -* +config.log_level+ defines the verbosity of the Rails logger. In production mode, this defaults to +:info+. In development mode, it defaults to +:debug+. +* +config.force_ssl+ forces all requests to be under HTTPS protocol by using +Rack::SSL+ middleware. -* +config.log_path+ overrides the path to the log file to use. Defaults to +log/#{environment}.log+ (e.g. log/development.log or log/production.log). +* +config.log_level+ defines the verbosity of the Rails logger. This option defaults to +:debug+ for all modes except production, where it defaults to +:info+. -* +config.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Controller. Set to nil to disable logging. +* +config.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ +Logger+ class. Defaults to an instance of +ActiveSupport::BufferedLogger+, with auto flushing off in production mode. -* +config.middleware+ allows you to configure the application's middleware. This is covered in depth in the "Configuring Middleware" section below. +* +config.middleware+ allows you to configure the application's middleware. This is covered in depth in the "Configuring Middleware":configuring-middleware section below. -* +config.plugins+ accepts the list of plugins to load. If this is set to nil, all plugins will be loaded. If this is set to [], no plugins will be loaded. Otherwise, plugins will be loaded in the order specified. +* +config.plugins+ accepts the list of plugins to load. If this is set to +nil+, default, all plugins will be loaded. If this is set to +[]+, no plugins will be loaded. Otherwise, plugins will be loaded in the order specified. This option let's you enforce some particular loading order, useful when dependencies between plugins require it. For that use case, put first the plugins you want to be loaded in a certain order, and then the special symbol +:all+ to have the rest loaded without the need to specify them. -* +config.preload_frameworks+ enables or disables preloading all frameworks at startup. Can also be enabled with +threadsafe!+. Defaults to +nil+, so is disabled. +* +config.preload_frameworks+ enables or disables preloading all frameworks at startup. Enabled by +config.threadsafe!+. Defaults to +nil+, so is disabled. -* +config.reload_plugins+ enables or disables plugin reloading. +* +config.reload_plugins+ enables or disables plugin reloading. Defaults to false. -* +config.root+ configures the root path of the application. +* +config.secret_token+ used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. Applications get +config.secret_token+ initialized to a random key in +config/initializers/secret_token.rb+. -* +config.secret_token+ used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. +* +config.serve_static_assets+ configures Rails to serve static assets. Defaults to true, but in the production environment is turned off. The server software used to run the application should be used to serve the assets instead. -* +config.serve_static_assets+ configures Rails to serve static assets. Defaults to _true_, but in the production environment is turned off. The server software used to run the application should be used to serve the assets instead. - -* +config.session_store+ is usually set up in +config/initializers/session_store.rb+ and specifies what class to use to store the session. Custom session stores can be specified like so: +* +config.session_store+ is usually set up in +config/initializers/session_store.rb+ and specifies what class to use to store the session. Possible values are +:cookie_store+, default, +:mem_cache_store+, and +:disabled+. The last one tells Rails not to deal with sessions. Custom session stores can also be specified like so: <ruby> - config.session_store = :my_custom_store +config.session_store :my_custom_store </ruby> -This custom store must be defined as +ActionDispatch::Session::MyCustomStore+. +This custom store must be defined as +ActionDispatch::Session::MyCustomStore+. In addition to symbols, they can also be objects implementing a certain API, like +ActiveRecord::SessionStore+, in which case no special namespace is required. * +config.threadsafe!+ enables +allow_concurrency+, +cache_classes+, +dependency_loading+ and +preload_frameworks+ to make the application threadsafe. @@ -120,7 +112,9 @@ WARNING: Threadsafe operation is incompatible with the normal workings of develo * +config.time_zone+ sets the default time zone for the application and enables time zone awareness for Active Record. -* +config.whiny_nils+ enables or disables warnings when any methods of nil are invoked. Defaults to _true_ in development and test environments. +* +config.whiny_nils+ enables or disables warnings when a certain set of methods are invoked on +nil+ and it does not respond to them. Defaults to true in development and test environments. + +* +config.assets.enabled+ a flag that controls whether the asset pipeline is enabled. It is explicitly initialized in +config/application.rb+. h4. Configuring Generators diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile index 5679bae531..2b79237c59 100644 --- a/railties/guides/source/performance_testing.textile +++ b/railties/guides/source/performance_testing.textile @@ -4,7 +4,7 @@ This guide covers the various ways of performance testing a Ruby on Rails applic * Understand the various types of benchmarking and profiling metrics * Generate performance and benchmarking tests -* Use a GC-patched Ruby binary to measure memory usage and object allocation +* Install and use a GC-patched Ruby binary to measure memory usage and object allocation * Understand the benchmarking information provided by Rails inside the log files * Learn about various tools facilitating benchmarking and profiling @@ -23,7 +23,7 @@ require 'test_helper' require 'rails/performance_test_help' # Profiling results for each test method are written to tmp/performance. -class BrowsingTest < ActionController::PerformanceTest +class BrowsingTest < ActionDispatch::PerformanceTest def test_homepage get '/' end @@ -34,10 +34,10 @@ This example is a simple performance test case for profiling a GET request to th h4. Generating Performance Tests -Rails provides a generator called +test_unit:performance+ for creating new performance tests: +Rails provides a generator called +performance_test+ for creating new performance tests: <shell> -$ rails generate test_unit:performance homepage +$ rails generate performance_test homepage </shell> This generates +homepage_test.rb+ in the +test/performance+ directory: @@ -46,7 +46,7 @@ This generates +homepage_test.rb+ in the +test/performance+ directory: require 'test_helper' require 'rails/performance_test_help' -class HomepageTest < ActionController::PerformanceTest +class HomepageTest < ActionDispatch::PerformanceTest # Replace this with your real tests. def test_homepage get '/' @@ -105,7 +105,7 @@ Here's the performance test for +HomeController#dashboard+ and +PostsController# require 'test_helper' require 'rails/performance_test_help' -class PostPerformanceTest < ActionController::PerformanceTest +class PostPerformanceTest < ActionDispatch::PerformanceTest def setup # Application requires logged-in user login_as(:lifo) @@ -133,7 +133,7 @@ Performance test for +Post+ model: require 'test_helper' require 'rails/performance_test_help' -class PostModelTest < ActionController::PerformanceTest +class PostModelTest < ActionDispatch::PerformanceTest def test_creation Post.create :body => 'still fooling you', :cost => '100' end @@ -151,7 +151,7 @@ Performance tests can be run in two modes: Benchmarking and Profiling. h5. Benchmarking -Benchmarking helps find out how fast each performance test runs. Each test case is run +4 times+ in benchmarking mode. +Benchmarking makes it easy to quickly gather a few metrics about each test tun. By default, each test case is run +4 times+ in benchmarking mode. To run performance tests in benchmarking mode: @@ -161,7 +161,7 @@ $ rake test:benchmark h5. Profiling -Profiling helps you see the details of a performance test and provide an in-depth picture of the slow and memory hungry parts. Each test case is run +1 time+ in profiling mode. +Profiling allows you to make an in-depth analysis of each of your tests by using an external profiler. Depending on your Ruby interpreter, this profiler can be native (Rubinius, JRuby) or not (MRI, which uses RubyProf). By default, each test case is run +1 time+ in profiling mode. To run performance tests in profiling mode: @@ -171,43 +171,59 @@ $ rake test:profile h4. Metrics -Benchmarking and profiling run performance tests in various modes described below. +Benchmarking and profiling run performance tests and give you multiple metrics. The availability of each metric is determined by the interpreter being used—none of them support all metrics—and by the mode in use. A brief description of each metric and their availability across interpreters/modes is given below. h5. Wall Time Wall time measures the real world time elapsed during the test run. It is affected by any other processes concurrently running on the system. -Mode: Benchmarking - h5. Process Time Process time measures the time taken by the process. It is unaffected by any other processes running concurrently on the same system. Hence, process time is likely to be constant for any given performance test, irrespective of the machine load. -Mode: Profiling +h5. CPU Time + +Similar to process time, but leverages the more accurate CPU clock counter available on the Pentium and PowerPC platforms. + +h5. User Time + +User time measures the amount of time the CPU spent in user-mode, i.e. within the process. This is not affected by other processes and by the time it possibly spends blocked. h5. Memory Memory measures the amount of memory used for the performance test case. -Mode: Benchmarking, Profiling "Requires GC Patched Ruby":#installing-gc-patched-ruby - h5. Objects Objects measures the number of objects allocated for the performance test case. -Mode: Benchmarking, Profiling "Requires GC Patched Ruby":#installing-gc-patched-ruby - h5. GC Runs GC Runs measures the number of times GC was invoked for the performance test case. -Mode: Benchmarking "Requires GC Patched Ruby":#installing-gc-patched-ruby - h5. GC Time GC Time measures the amount of time spent in GC for the performance test case. -Mode: Benchmarking "Requires GC Patched Ruby":#installing-gc-patched-ruby +h5. Metric Availability + +h6. Benchmarking + +|_.Interpreter|_.Wall Time|_.Process Time|_.CPU Time|_.User Time|_.Memory|_.Objects|_.GC Runs|_.GC Time| +|_.MRI | yes | yes | yes | no | yes | yes | yes | yes | +|_.REE | yes | yes | yes | no | yes | yes | yes | yes | +|_.Rubinius | yes | no | no | no | yes | yes | yes | yes | +|_.JRuby | yes | no | no | yes | yes | yes | yes | yes | + +h6. Profiling + +|_.Interpreter|_.Wall Time|_.Process Time|_.CPU Time|_.User Time|_.Memory|_.Objects|_.GC Runs|_.GC Time| +|_.MRI | yes | yes | no | no | yes | yes | yes | yes | +|_.REE | yes | yes | no | no | yes | yes | yes | yes | +|_.Rubinius | yes | no | no | no | no | no | no | no | +|_.JRuby | yes | no | no | no | no | no | no | no | + +NOTE: To profile under JRuby you'll need to run +export JRUBY_OPTS="-Xlaunch.inproc=false --profile.api"+ *before* the performance tests. h4. Understanding the Output @@ -215,7 +231,7 @@ Performance tests generate different outputs inside +tmp/performance+ directory h5(#output-benchmarking). Benchmarking -In benchmarking mode, performance tests generate two types of outputs: +In benchmarking mode, performance tests generate two types of outputs. h6(#output-command-line). Command Line @@ -225,7 +241,7 @@ This is the primary form of output in benchmarking mode. Example: BrowsingTest#test_homepage (31 ms warmup) wall_time: 6 ms memory: 437.27 KB - objects: 5514 + objects: 5,514 gc_runs: 0 gc_time: 19 ms </shell> @@ -260,7 +276,7 @@ measurement,created_at,app,rails,ruby,platform h5(#output-profiling). Profiling -In profiling mode, you can choose from four types of output. +In profiling mode, performance tests can generate multiple types of outputs. The command line output is always presented but support for the others is dependant on the interpreter in use. A brief description of each type and their availability across interpreters is given below. h6. Command Line @@ -270,26 +286,67 @@ This is a very basic form of output in profiling mode: BrowsingTest#test_homepage (58 ms warmup) process_time: 63 ms memory: 832.13 KB - objects: 7882 + objects: 7,882 </shell> h6. Flat -Flat output shows the total amount of time spent in each method. "Check ruby prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/flat_txt.html. +Flat output shows the metric—time, memory, etc—measure in each method. "Check Ruby-Prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/flat_txt.html. h6. Graph -Graph output shows how long each method takes to run, which methods call it and which methods it calls. "Check ruby prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/graph_txt.html. +Graph output shows the metric measure in each method, which methods call it and which methods it calls. "Check Ruby-Prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/graph_txt.html. h6. Tree Tree output is profiling information in calltree format for use by "kcachegrind":http://kcachegrind.sourceforge.net/html/Home.html and similar tools. +h6. Output Availability + +|_. |_.Flat|_.Graph|_.Tree| +|_.MRI | yes | yes | yes | +|_.REE | yes | yes | yes | +|_.Rubinius | yes | yes | no | +|_.JRuby | yes | yes | no | + h4. Tuning Test Runs -By default, each performance test is run +4 times+ in benchmarking mode and +1 time+ in profiling. However, test runs can easily be configured. +Test runs can be tuned by setting the +profile_options+ class variable on your test class. -WARNING: Performance test configurability is not yet enabled in Rails. But it will be soon. +<ruby> +require 'test_helper' +require 'rails/performance_test_help' + +# Profiling results for each test method are written to tmp/performance. +class BrowsingTest < ActionDispatch::PerformanceTest + self.profile_options = { :runs => 5, + :metrics => [:wall_time, :memory] } + + def test_homepage + get '/' + end +end +</ruby> + +In this example, the test would run 5 times and measure wall time and memory. There are a few configurable options: + +|_.Option |_.Description|_.Default|_.Mode| +|+:runs+ |Number of runs.|Benchmarking: 4, Profiling: 1|Both| +|+:output+ |Directory to use when writing the results.|+tmp/performance+|Both| +|+:metrics+ |Metrics to use.|See below.|Both| +|+:formats+ |Formats to output to.|See below.|Profiling| + +Metrics and formats have different defaults depending on the interpreter in use. + +|_.Interpreter|_.Mode|_.Default metrics|_.Default formats| +|/2.MRI/REE |Benchmarking|+[:wall_time, :memory, :objects, :gc_runs, :gc_time]+|N/A| +|Profiling |+[:process_time, :memory, :objects]+|+[:flat, :graph_html, :call_tree, :call_stack]+| +|/2.Rubinius|Benchmarking|+[:wall_time, :memory, :objects, :gc_runs, :gc_time]+|N/A| +|Profiling |+[:wall_time]+|+[:flat, :graph]+| +|/2.JRuby |Benchmarking|+[:wall_time, :user_time, :memory, :gc_runs, :gc_time]+|N/A| +|Profiling |+[:wall_time]+|+[:flat, :graph]+| + +As you've probably noticed by now, metrics and formats are specified using a symbol array with each name "underscored.":http://api.rubyonrails.org/classes/String.html#method-i-underscore h4. Performance Test Environment @@ -303,41 +360,71 @@ Rails.logger.level = ActiveSupport::BufferedLogger::INFO As +ActionController::Base.perform_caching+ is set to +true+, performance tests will behave much as they do in the +production+ environment. -h4. Installing GC-Patched Ruby +h4. Installing GC-Patched MRI + +To get the best from Rails' performance tests under MRI, you'll need to build a special Ruby binary with some super powers. -To get the best from Rails performance tests, you need to build a special Ruby binary with some super powers - "GC patch":http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch for measuring GC Runs/Time and memory/object allocation. +The recommended patches for each MRI version are: -The process is fairly straightforward. If you've never compiled a Ruby binary before, follow these steps to build a ruby binary inside your home directory: +|_.Version|_.Patch| +|1.8.6|ruby186gc| +|1.8.7|ruby187gc| +|1.9.2 and above|gcdata| -h5. Installation +All of these can be found on "RVM's _patches_ directory":https://github.com/wayneeseguin/rvm/tree/master/patches/ruby under each specific interpreter version. -Compile Ruby and apply this "GC Patch":http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch. +Concerning the installation itself, you can either do this easily by using "RVM":http://rvm.beginrescueend.com or you can build everything from source, which is a little bit harder. -h5. Download and Extract +h5. Install Using RVM + +The process of installing a patched Ruby interpreter is very easy if you let RVM do the hard work. All of the following RVM commands will provide you with a patched Ruby interpreter: + +<shell> +$ rvm install 1.9.2-p180 --patch gcdata +$ rvm install 1.8.7 --patch ruby187gc +$ rvm install 1.9.2-p180 --patch ~/Downloads/downloaded_gcdata_patch.patch +</shell> + +You can even keep your regular interpreter by assigning a name to the patched one: + +<shell> +$ rvm install 1.9.2-p180 --patch gcdata --name gcdata +$ rvm use 1.9.2-p180 # your regular ruby +$ rvm use 1.9.2-p180-gcdata # your patched ruby +</shell> + +And it's done! You have installed a patched Ruby interpreter. + +h5. Install From Source + +This process is a bit more complicated, but straightforward nonetheless. If you've never compiled a Ruby binary before, follow these steps to build a Ruby binary inside your home directory. + +h6. Download and Extract <shell> $ mkdir rubygc -$ wget <download the latest stable ruby from ftp://ftp.ruby-lang.org/pub/ruby> +$ wget <the version you want from ftp://ftp.ruby-lang.org/pub/ruby> $ tar -xzvf <ruby-version.tar.gz> $ cd <ruby-version> </shell> -h5. Apply the Patch +h6. Apply the Patch <shell> -$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0 +$ curl http://github.com/wayneeseguin/rvm/raw/master/patches/ruby/1.9.2/p180/gcdata.patch | patch -p0 # if you're on 1.9.2! +$ curl http://github.com/wayneeseguin/rvm/raw/master/patches/ruby/1.8.7/ruby187gc.patch | patch -p0 # if you're on 1.8.7! </shell> -h5. Configure and Install +h6. Configure and Install -The following will install ruby in your home directory's +/rubygc+ directory. Make sure to replace +<homedir>+ with a full patch to your actual home directory. +The following will install Ruby in your home directory's +/rubygc+ directory. Make sure to replace +<homedir>+ with a full patch to your actual home directory. <shell> $ ./configure --prefix=/<homedir>/rubygc $ make && make install </shell> -h5. Prepare Aliases +h6. Prepare Aliases For convenience, add the following lines in your +~/.profile+: @@ -349,26 +436,21 @@ alias gcirb='~/rubygc/bin/irb' alias gcrails='~/rubygc/bin/rails' </shell> -h5. Install Rubygems and Dependency Gems +Don't forget to use your aliases from now on. -Download "Rubygems":http://rubyforge.org/projects/rubygems and install it from source. Rubygem's README file should have necessary installation instructions. +h6. Install Rubygems (1.8 only!) -Additionally, install the following gems: +Download "Rubygems":http://rubyforge.org/projects/rubygems and install it from source. Rubygem's README file should have necessary installation instructions. Please note that this step isn't necessary if you've installed Ruby 1.9 and above. -* +rake+ -* +rails+ -* +ruby-prof+ -* +rack+ -* +mysql+ +h4. Using Ruby-Prof on MRI and REE -If installing +mysql+ fails, you can try to install it manually: +Add Ruby-Prof to your applications' Gemfile if you want to benchmark/profile under MRI or REE: -<shell> -$ gcruby extconf.rb --with-mysql-config -$ make && make install -</shell> +<ruby> +gem 'ruby-prof', :path => 'git://github.com/wycats/ruby-prof.git' +</ruby> -And you're ready to go. Don't forget to use +gcruby+ and +gcrake+ aliases when running the performance tests. +Now run +bundle install+ and you're ready to go. h3. Command Line Tools @@ -376,55 +458,47 @@ Writing performance test cases could be an overkill when you are looking for one h4. +benchmarker+ -+benchmarker+ is a wrapper around Ruby's "Benchmark":http://ruby-doc.org/core/classes/Benchmark.html standard library. - Usage: <shell> -$ rails benchmarker [times] 'Person.expensive_way' 'Person.another_expensive_way' ... -</shell> - -Examples: - -<shell> -$ rails benchmarker 10 'Item.all' 'CouchItem.all' +Usage: rails benchmarker 'Ruby.code' 'Ruby.more_code' ... [OPTS] + -r, --runs N Number of runs. + Default: 4 + -o, --output PATH Directory to use when writing the results. + Default: tmp/performance + -m, --metrics a,b,c Metrics to use. + Default: wall_time,memory,objects,gc_runs,gc_time </shell> -If the +[times]+ argument is omitted, supplied methods are run just once: +Example: <shell> -$ rails benchmarker 'Item.first' 'Item.last' +$ rails benchmarker 'Item.all' 'CouchItem.all' --runs 3 --metrics wall_time,memory </shell> h4. +profiler+ -+profiler+ is a wrapper around the "ruby-prof":http://ruby-prof.rubyforge.org gem. - Usage: <shell> -$ rails profiler 'Person.expensive_method(10)' [times] [flat|graph|graph_html] +Usage: rails benchmarker 'Ruby.code' 'Ruby.more_code' ... [OPTS] + -r, --runs N Number of runs. + Default: 1 + -o, --output PATH Directory to use when writing the results. + Default: tmp/performance + --metrics a,b,c Metrics to use. + Default: process_time,memory,objects + -m, --formats x,y,z Formats to output to. + Default: flat,graph_html,call_tree </shell> -Examples: +Example: <shell> -$ rails profiler 'Item.all' +$ rails profiler 'Item.all' 'CouchItem.all' --runs 2 --metrics process_time --formats flat </shell> -This will profile +Item.all+ in +RubyProf::WALL_TIME+ measure mode. By default, it prints flat output to the shell. - -<shell> -$ rails profiler 'Item.all' 10 graph -</shell> - -This will profile +10.times { Item.all }+ with +RubyProf::WALL_TIME+ measure mode and print graph output to the shell. - -If you want to store the output in a file: - -<shell> -$ rails profiler 'Item.all' 10 graph 2> graph.txt -</shell> +NOTE: Metrics and formats vary from interpreter to interpreter. Pass +--help+ to each tool to see the defaults for your interpreter. h3. Helper Methods @@ -517,12 +591,13 @@ h4. Tutorials and Documentation h3. Commercial Products -Rails has been lucky to have two startups dedicated to Rails specific performance tools: +Rails has been lucky to have a few companies dedicated to Rails-specific performance tools. A couple of those are: * "New Relic":http://www.newrelic.com * "Scout":http://scoutapp.com h3. Changelog +* March 30, 2011: Documented the recent improvements (multiple interpreters, options, etc) and necessary adjustments. Other minor improvements. "Gonçalo Silva":http://goncalossilva.com. * January 9, 2009: Complete rewrite by "Pratik":credits.html#lifo * September 6, 2008: Initial version by Matthew Bergman diff --git a/railties/lib/rails/commands/benchmarker.rb b/railties/lib/rails/commands/benchmarker.rb index f230f405c0..b06c915ac3 100644 --- a/railties/lib/rails/commands/benchmarker.rb +++ b/railties/lib/rails/commands/benchmarker.rb @@ -1,25 +1,34 @@ -require 'active_support/core_ext/object/inclusion' +require 'optparse' +require 'rails/test_help' +require 'rails/performance_test_help' -if ARGV.first.in?([nil, "-h", "--help"]) - puts "Usage: rails benchmarker [times] 'Person.expensive_way' 'Person.another_expensive_way' ..." - exit 1 -end +ARGV.push('--benchmark') # HAX +require 'active_support/testing/performance' +ARGV.pop -begin - N = Integer(ARGV.first) - ARGV.shift -rescue ArgumentError - N = 1 +def options + options = {} + defaults = ActiveSupport::Testing::Performance::DEFAULTS + + OptionParser.new do |opt| + opt.banner = "Usage: rails benchmarker 'Ruby.code' 'Ruby.more_code' ... [OPTS]" + opt.on('-r', '--runs N', Numeric, 'Number of runs.', "Default: #{defaults[:runs]}") { |r| options[:runs] = r } + opt.on('-o', '--output PATH', String, 'Directory to use when writing the results.', "Default: #{defaults[:output]}") { |o| options[:output] = o } + opt.on('-m', '--metrics a,b,c', Array, 'Metrics to use.', "Default: #{defaults[:metrics].join(",")}") { |m| options[:metrics] = m.map(&:to_sym) } + opt.parse!(ARGV) + end + + options end -require 'benchmark' -include Benchmark - -# Don't include compilation in the benchmark -ARGV.each { |expression| eval(expression) } - -bm(6) do |x| - ARGV.each_with_index do |expression, idx| - x.report("##{idx + 1}") { N.times { eval(expression) } } +class BenchmarkerTest < ActionDispatch::PerformanceTest + self.profile_options = options + + ARGV.each do |expression| + eval <<-RUBY + def test_#{expression.parameterize('_')} + #{expression} + end + RUBY end end diff --git a/railties/lib/rails/commands/profiler.rb b/railties/lib/rails/commands/profiler.rb index 7959d8a981..94cf32d32d 100644 --- a/railties/lib/rails/commands/profiler.rb +++ b/railties/lib/rails/commands/profiler.rb @@ -1,48 +1,32 @@ -require 'active_support/core_ext/object/inclusion' +require 'optparse' +require 'rails/test_help' +require 'rails/performance_test_help' +require 'active_support/testing/performance' -if ARGV.first.in?([nil, "-h", "--help"]) - $stderr.puts "Usage: rails profiler 'Person.expensive_method(10)' [times] [flat|graph|graph_html]" - exit(1) -end - -# Define a method to profile. -if ARGV[1] and ARGV[1].to_i > 1 - eval "def profile_me() #{ARGV[1]}.times { #{ARGV[0]} } end" -else - eval "def profile_me() #{ARGV[0]} end" +def options + options = {} + defaults = ActiveSupport::Testing::Performance::DEFAULTS + + OptionParser.new do |opt| + opt.banner = "Usage: rails benchmarker 'Ruby.code' 'Ruby.more_code' ... [OPTS]" + opt.on('-r', '--runs N', Numeric, 'Number of runs.', "Default: #{defaults[:runs]}") { |r| options[:runs] = r } + opt.on('-o', '--output PATH', String, 'Directory to use when writing the results.', "Default: #{defaults[:output]}") { |o| options[:output] = o } + opt.on('-m', '--metrics a,b,c', Array, 'Metrics to use.', "Default: #{defaults[:metrics].join(",")}") { |m| options[:metrics] = m.map(&:to_sym) } + opt.on('-f', '--formats x,y,z', Array, 'Formats to output to.', "Default: #{defaults[:formats].join(",")}") { |m| options[:formats] = m.map(&:to_sym) } + opt.parse!(ARGV) + end + + options end -# Use the ruby-prof extension if available. Fall back to stdlib profiler. -begin - begin - require "ruby-prof" - $stderr.puts 'Using the ruby-prof extension.' - RubyProf.measure_mode = RubyProf::WALL_TIME - RubyProf.start - profile_me - results = RubyProf.stop - if ARGV[2] - printer_class = RubyProf.const_get((ARGV[2] + "_printer").classify) - else - printer_class = RubyProf::FlatPrinter - end - printer = printer_class.new(results) - printer.print($stderr) - rescue LoadError - require "prof" - $stderr.puts 'Using the old ruby-prof extension.' - Prof.clock_mode = Prof::GETTIMEOFDAY - Prof.start - profile_me - results = Prof.stop - require 'rubyprof_ext' - Prof.print_profile(results, $stderr) +class ProfilerTest < ActionDispatch::PerformanceTest + self.profile_options = options + + ARGV.each do |expression| + eval <<-RUBY + def test_#{expression.parameterize('_')} + #{expression} + end + RUBY end -rescue LoadError - require 'profiler' - $stderr.puts 'Using the standard Ruby profiler.' - Profiler__.start_profile - profile_me - Profiler__.stop_profile - Profiler__.print_profile($stderr) end diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index 6a125685d0..e26f73ed8d 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -522,9 +522,9 @@ module Rails end initializer :append_assets_path do |app| - app.config.assets.paths.unshift *paths["vendor/assets"].existent - app.config.assets.paths.unshift *paths["lib/assets"].existent - app.config.assets.paths.unshift *paths["app/assets"].existent + app.config.assets.paths.unshift(*paths["vendor/assets"].existent) + app.config.assets.paths.unshift(*paths["lib/assets"].existent) + app.config.assets.paths.unshift(*paths["app/assets"].existent) end initializer :prepend_helpers_path do |app| diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb index c323df3e95..d31a3262e3 100644 --- a/railties/lib/rails/generators/actions.rb +++ b/railties/lib/rails/generators/actions.rb @@ -278,7 +278,7 @@ module Rails say args.first.to_s unless options.quiet? else args << (self.behavior == :invoke ? :green : :red) - say_status *args + say_status(*args) end end diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index a5743762e5..8512b1ca4a 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -165,7 +165,7 @@ module Rails end def gem_for_ruby_debugger - if RUBY_VERSION < "1.9.2" + if RUBY_VERSION < "1.9" "gem 'ruby-debug'" else "gem 'ruby-debug19', :require => 'ruby-debug'" @@ -173,7 +173,7 @@ module Rails end def gem_for_turn - unless RUBY_VERSION < "1.9.2" + unless RUBY_VERSION < "1.9.2" || options[:skip_test_unit] <<-GEMFILE.strip_heredoc group :test do # Pretty printed test output diff --git a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb index d12b2ff0e5..32546936e3 100644 --- a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb +++ b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb @@ -11,7 +11,7 @@ </div> <%% end %> -<% for attribute in attributes -%> +<% attributes.each do |attribute| -%> <div class="field"> <%%= f.label :<%= attribute.name %> %><br /> <%%= f.<%= attribute.field_type %> :<%= attribute.name %> %> diff --git a/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb index a7393cfe18..7b1a2a1841 100644 --- a/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb +++ b/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb @@ -2,7 +2,7 @@ <table> <tr> -<% for attribute in attributes -%> +<% attributes.each do |attribute| -%> <th><%= attribute.human_name %></th> <% end -%> <th></th> @@ -12,7 +12,7 @@ <%% @<%= plural_table_name %>.each do |<%= singular_table_name %>| %> <tr> -<% for attribute in attributes -%> +<% attributes.each do |attribute| -%> <td><%%= <%= singular_table_name %>.<%= attribute.name %> %></td> <% end -%> <td><%%= link_to 'Show', <%= singular_table_name %> %></td> diff --git a/railties/lib/rails/generators/erb/scaffold/templates/show.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/show.html.erb index c0e5ccff1e..67f263efbb 100644 --- a/railties/lib/rails/generators/erb/scaffold/templates/show.html.erb +++ b/railties/lib/rails/generators/erb/scaffold/templates/show.html.erb @@ -1,6 +1,6 @@ <p id="notice"><%%= notice %></p> -<% for attribute in attributes -%> +<% attributes.each do |attribute| -%> <p> <b><%= attribute.human_name %>:</b> <%%= @<%= singular_table_name %>.<%= attribute.name %> %> diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb index b26161f1d0..9450894b05 100644 --- a/railties/lib/rails/generators/generated_attribute.rb +++ b/railties/lib/rails/generators/generated_attribute.rb @@ -13,12 +13,13 @@ module Rails def field_type @field_type ||= case type - when :integer, :float, :decimal then :text_field - when :time then :time_select - when :datetime, :timestamp then :datetime_select - when :date then :date_select - when :text then :text_area - when :boolean then :check_box + when :integer then :number_field + when :float, :decimal then :text_field + when :time then :time_select + when :datetime, :timestamp then :datetime_select + when :date then :date_select + when :text then :text_area + when :boolean then :check_box else :text_field end diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb index cf317eb21f..7e7f8d2d08 100644 --- a/railties/lib/rails/generators/named_base.rb +++ b/railties/lib/rails/generators/named_base.rb @@ -13,6 +13,7 @@ module Rails :desc => "Force using old style hash (:foo => 'bar') on Ruby >= 1.9" def initialize(args, *options) #:nodoc: + @inside_template = nil # Unfreeze name in case it's given as a frozen string args[0] = args[0].dup if args[0].is_a?(String) && args[0].frozen? super diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml index c0c3588be1..4807986333 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml @@ -2,7 +2,10 @@ # # Get the bindings: # gem install ruby-frontbase - +# +# Configure Using Gemfile +# gem 'ruby-frontbase' +# development: adapter: frontbase host: localhost diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml index df5ef33064..3d689a110a 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml @@ -28,6 +28,9 @@ # On Windows: # Issue the command: gem install ibm_db # +# Configure Using Gemfile +# gem 'ibm_db' +# # For more details on the installation and the connection parameters below, # please refer to the latest documents at http://rubyforge.org/docman/?group_id=2361 diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml index ca807c9f3f..6bf83e86a5 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml @@ -3,6 +3,9 @@ # Install the MySQL driver: # gem install activerecord-jdbcmysql-adapter # +# Configure Using Gemfile +# gem 'activerecord-jdbcmysql-adapter' +# # And be sure to use new-style password hashing: # http://dev.mysql.com/doc/refman/5.0/en/old-client.html development: diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml index a228aca5d2..0c7f45322b 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml @@ -8,6 +8,10 @@ # gem install pg # Choose the win32 build. # Install PostgreSQL and put its /bin directory on your path. +# +# Configure Using Gemfile +# gem 'activerecord-jdbcpostgresql-adapter' + development: adapter: jdbcpostgresql encoding: unicode diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml index 30776b3b4e..6d241d57ae 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml @@ -1,6 +1,9 @@ # SQLite version 3.x # gem 'activerecord-jdbcsqlite3-adapter' - +# +# Configure Using Gemfile +# gem 'activerecord-jdbcsqlite3-adapter' +# development: adapter: jdbcsqlite3 database: db/development.sqlite3 diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml index 5d28c7c312..cce166c7c3 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml @@ -1,8 +1,11 @@ # MySQL. Versions 4.1 and 5.0 are recommended. -# -# Install the MySQL driver: +# +# Install the MYSQL driver # gem install mysql2 # +# Ensure the MySQL gem is defined in your Gemfile +# gem 'mysql2' +# # And be sure to use new-style password hashing: # http://dev.mysql.com/doc/refman/5.0/en/old-client.html development: diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml index 4e6391e3d6..467dfc3956 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml @@ -8,6 +8,10 @@ # gem install pg # Choose the win32 build. # Install PostgreSQL and put its /bin directory on your path. +# +# Configure Using Gemfile +# gem 'pg' +# development: adapter: postgresql encoding: unicode diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml index 90d87cc295..51a4dd459d 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml @@ -1,5 +1,8 @@ # SQLite version 3.x # gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem 'sqlite3' development: adapter: sqlite3 database: db/development.sqlite3 diff --git a/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt b/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt index 9a2efa68a7..f75c5dd941 100644 --- a/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt @@ -4,4 +4,4 @@ # Examples: # # cities = City.create([{ <%= key_value :name, "'Chicago'" %> }, { <%= key_value :name, "'Copenhagen'" %> }]) -# Mayor.create(<%= key_value :name, "'Daley'" %>, <%= key_value :city, "cities.first" %>) +# Mayor.create(<%= key_value :name, "'Emanuel'" %>, <%= key_value :city, "cities.first" %>) diff --git a/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb b/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb index 867fc8c985..5d1be041a5 100644 --- a/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb +++ b/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb @@ -1,8 +1,11 @@ require 'test_helper' require 'rails/performance_test_help' -# Profiling results for each test method are written to tmp/performance. class BrowsingTest < ActionDispatch::PerformanceTest + # Refer to the documentation for all available options + # self.profile_options = { :runs => 5, :metrics => [:wall_time, :memory] + # :output => 'tmp/performance', :formats => [:flat] } + def test_homepage get '/' end diff --git a/railties/lib/rails/generators/rails/controller/templates/controller.rb b/railties/lib/rails/generators/rails/controller/templates/controller.rb index c61ea4b510..8f5f78556f 100644 --- a/railties/lib/rails/generators/rails/controller/templates/controller.rb +++ b/railties/lib/rails/generators/rails/controller/templates/controller.rb @@ -1,6 +1,6 @@ <% module_namespacing do -%> class <%= class_name %>Controller < ApplicationController -<% for action in actions -%> +<% actions.each do |action| -%> def <%= action %> end diff --git a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb index 939c0cd727..9ddb3cae33 100644 --- a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb +++ b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb @@ -75,6 +75,7 @@ task :default => :test def generate_test_dummy(force = false) opts = (options || {}).slice(*PASSTHROUGH_OPTIONS) opts[:force] = force + opts[:skip_bundle] = true invoke Rails::Generators::AppGenerator, [ File.expand_path(dummy_path, destination_root) ], opts diff --git a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb index 0bc5fd8ca2..509bd60564 100644 --- a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb +++ b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb @@ -7,7 +7,7 @@ class <%= class_name %>ControllerTest < ActionController::TestCase # assert true # end <% else -%> -<% for action in actions -%> +<% actions.each do |action| -%> test "should get <%= action %>" do get :<%= action %> assert_response :success diff --git a/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb index c05102290c..7e204105a3 100644 --- a/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb +++ b/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb @@ -2,7 +2,7 @@ require 'test_helper' <% module_namespacing do -%> class <%= class_name %>Test < ActionMailer::TestCase -<% for action in actions -%> +<% actions.each do |action| -%> test "<%= action %>" do mail = <%= class_name %>.<%= action %> assert_equal <%= action.to_s.humanize.inspect %>, mail.subject diff --git a/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml index 6465a6a6e2..d4138ca2f5 100644 --- a/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml +++ b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml @@ -2,12 +2,12 @@ <% unless attributes.empty? -%> one: -<% for attribute in attributes -%> +<% attributes.each do |attribute| -%> <%= attribute.name %>: <%= attribute.default %> <% end -%> two: -<% for attribute in attributes -%> +<% attributes.each do |attribute| -%> <%= attribute.name %>: <%= attribute.default %> <% end -%> <% else -%> @@ -20,4 +20,4 @@ one: {} # two: {} # column: value -<% end -%>
\ No newline at end of file +<% end -%> diff --git a/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb b/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb index e827aa918f..14a878328b 100644 --- a/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb +++ b/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb @@ -2,7 +2,10 @@ require 'test_helper' require 'rails/performance_test_help' class <%= class_name %>Test < ActionDispatch::PerformanceTest - # Replace this with your real tests. + # Refer to the documentation for all available options + # self.profile_options = { :runs => 5, :metrics => [:wall_time, :memory] + # :output => 'tmp/performance', :formats => [:flat] } + def test_homepage get '/' end diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index b03dc3132b..98a702f134 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -11,6 +11,10 @@ module ApplicationTests boot_rails end + def app + @app ||= Rails.application + end + test "assets routes have higher priority" do app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();" @@ -20,8 +24,36 @@ module ApplicationTests end RUBY + require "#{app_path}/config/environment" + + get "/assets/demo.js" + assert_match "alert()", last_response.body + end + + test "does not stream session cookies back" do + app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();" + + app_file "config/routes.rb", <<-RUBY + AppTemplate::Application.routes.draw do + match '/omg', :to => "omg#index" + end + RUBY + + require "#{app_path}/config/environment" + + class ::OmgController < ActionController::Base + def index + flash[:cool_story] = true + render :text => "ok" + end + end + + get "/omg" + assert_equal 'ok', last_response.body + get "/assets/demo.js" assert_match "alert()", last_response.body + assert_equal nil, last_response.headers["Set-Cookie"] end end end diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 43876c0a72..0e27c9606d 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -452,7 +452,7 @@ module ApplicationTests app_file 'app/models/post.rb', <<-RUBY class Post - def self.column_names + def self.attribute_names %w(title) end end diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb index 68d4c17623..597746c4aa 100644 --- a/railties/test/generators/actions_test.rb +++ b/railties/test/generators/actions_test.rb @@ -118,8 +118,8 @@ class ActionsTest < Rails::Generators::TestCase end assert_file 'config/application.rb' do |content| - assert_match /# This will be added/, content - assert_no_match /# This wont be added/, content + assert_match(/# This will be added/, content) + assert_no_match(/# This wont be added/, content) end end diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 9e1d47cd2f..42fe7a7fea 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -155,7 +155,7 @@ class AppGeneratorTest < Rails::Generators::TestCase run_generator [destination_root, "--skip-active-record"] assert_no_file "config/database.yml" assert_file "test/test_helper.rb" do |helper_content| - assert_no_match /fixtures :all/, helper_content + assert_no_match(/fixtures :all/, helper_content) end assert_file "test/performance/browsing_test.rb" end @@ -178,7 +178,7 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_match %r{^//= require jquery_ujs}, contents end assert_file 'Gemfile' do |contents| - assert_match /^gem 'jquery-rails'/, contents + assert_match(/^gem 'jquery-rails'/, contents) end end @@ -190,7 +190,7 @@ class AppGeneratorTest < Rails::Generators::TestCase assert_match %r{^//= require prototype_ujs}, contents end assert_file 'Gemfile' do |contents| - assert_match /^gem 'prototype-rails'/, contents + assert_match(/^gem 'prototype-rails'/, contents) end end @@ -202,9 +202,38 @@ class AppGeneratorTest < Rails::Generators::TestCase end end + def test_inclusion_of_turn_gem_in_gemfile + run_generator + assert_file "Gemfile" do |contents| + assert_match(/gem 'turn'/, contents) unless RUBY_VERSION < '1.9.2' + assert_no_match(/gem 'turn'/, contents) if RUBY_VERSION < '1.9.2' + end + end + + def test_turn_gem_is_not_included_in_gemfile_if_skipping_test_unit + run_generator [destination_root, "--skip-test-unit"] + assert_file "Gemfile" do |contents| + assert_no_match(/gem 'turn'/, contents) unless RUBY_VERSION < '1.9.2' + end + end + + def test_inclusion_of_ruby_debug + run_generator + assert_file "Gemfile" do |contents| + assert_match(/gem 'ruby-debug'/, contents) if RUBY_VERSION < '1.9' + end + end + + def test_inclusion_of_ruby_debug19_if_ruby19 + run_generator + assert_file "Gemfile" do |contents| + assert_match(/gem 'ruby-debug19', :require => 'ruby-debug'/, contents) unless RUBY_VERSION < '1.9' + end + end + def test_template_from_dir_pwd FileUtils.cd(Rails.root) - assert_match /It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"]) + assert_match(/It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"])) end def test_usage_read_from_file @@ -214,7 +243,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_default_usage File.expects(:exist?).returns(false) - assert_match /Create rails files for app generator/, Rails::Generators::AppGenerator.desc + assert_match(/Create rails files for app generator/, Rails::Generators::AppGenerator.desc) end def test_default_namespace @@ -241,9 +270,9 @@ class AppGeneratorTest < Rails::Generators::TestCase run_generator [destination_root] assert_file "config/initializers/session_store.rb" do |file| if RUBY_VERSION < "1.9" - assert_match /config.session_store :cookie_store, :key => '_.+_session'/, file + assert_match(/config.session_store :cookie_store, :key => '_.+_session'/, file) else - assert_match /config.session_store :cookie_store, key: '_.+_session'/, file + assert_match(/config.session_store :cookie_store, key: '_.+_session'/, file) end end end @@ -251,7 +280,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_force_old_style_hash run_generator [destination_root, "--old-style-hash"] assert_file "config/initializers/session_store.rb" do |file| - assert_match /config.session_store :cookie_store, :key => '_.+_session'/, file + assert_match(/config.session_store :cookie_store, :key => '_.+_session'/, file) end end diff --git a/railties/test/generators/controller_generator_test.rb b/railties/test/generators/controller_generator_test.rb index 2dfc91c683..46533b70be 100644 --- a/railties/test/generators/controller_generator_test.rb +++ b/railties/test/generators/controller_generator_test.rb @@ -9,7 +9,7 @@ class ControllerGeneratorTest < Rails::Generators::TestCase def test_help_does_not_show_invoked_generators_options_if_they_already_exist content = run_generator ["--help"] - assert_no_match /Helper options\:/, content + assert_no_match(/Helper options\:/, content) end def test_controller_skeleton_is_created @@ -20,7 +20,7 @@ class ControllerGeneratorTest < Rails::Generators::TestCase 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 + assert_match(/The name 'ObjectController' is either already used in your application or reserved/, content) ensure Object.send :remove_const, :ObjectController end diff --git a/railties/test/generators/generated_attribute_test.rb b/railties/test/generators/generated_attribute_test.rb index 064546a3f3..0d2e624f44 100644 --- a/railties/test/generators/generated_attribute_test.rb +++ b/railties/test/generators/generated_attribute_test.rb @@ -4,8 +4,12 @@ require 'rails/generators/generated_attribute' class GeneratedAttributeTest < Rails::Generators::TestCase include GeneratorsTestHelper + def test_field_type_returns_number_field + assert_field_type :integer, :number_field + end + def test_field_type_returns_text_field - %w(integer float decimal string).each do |attribute_type| + %w(float decimal string).each do |attribute_type| assert_field_type attribute_type, :text_field end end diff --git a/railties/test/generators/helper_generator_test.rb b/railties/test/generators/helper_generator_test.rb index f0bfebd57f..8da3aa61a4 100644 --- a/railties/test/generators/helper_generator_test.rb +++ b/railties/test/generators/helper_generator_test.rb @@ -20,17 +20,17 @@ class HelperGeneratorTest < Rails::Generators::TestCase def test_logs_if_the_test_framework_cannot_be_found content = run_generator ["admin", "--test-framework=rspec"] - assert_match /rspec \[not found\]/, content + 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 + 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 + assert_match(/The name 'AnotherObjectHelperTest' is either already used in your application or reserved/, content) end def test_namespaced_and_not_namespaced_helpers diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb index bf1cfe5305..139d6b1421 100644 --- a/railties/test/generators/mailer_generator_test.rb +++ b/railties/test/generators/mailer_generator_test.rb @@ -9,11 +9,11 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_mailer_skeleton_is_created run_generator assert_file "app/mailers/notifier.rb" do |mailer| - assert_match /class Notifier < ActionMailer::Base/, mailer + assert_match(/class Notifier < ActionMailer::Base/, mailer) if RUBY_VERSION < "1.9" - assert_match /default :from => "from@example.com"/, mailer + assert_match(/default :from => "from@example.com"/, mailer) else - assert_match /default from: "from@example.com"/, mailer + assert_match(/default from: "from@example.com"/, mailer) end end end @@ -21,35 +21,35 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_mailer_with_i18n_helper run_generator assert_file "app/mailers/notifier.rb" do |mailer| - assert_match /en\.notifier\.foo\.subject/, mailer - assert_match /en\.notifier\.bar\.subject/, mailer + assert_match(/en\.notifier\.foo\.subject/, mailer) + assert_match(/en\.notifier\.bar\.subject/, mailer) end 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 + 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/functional/notifier_test.rb" do |test| - assert_match /class NotifierTest < ActionMailer::TestCase/, test - assert_match /test "foo"/, test - assert_match /test "bar"/, test + assert_match(/class NotifierTest < ActionMailer::TestCase/, test) + assert_match(/test "foo"/, test) + assert_match(/test "bar"/, test) end end def test_invokes_default_template_engine run_generator assert_file "app/views/notifier/foo.text.erb" do |view| - assert_match %r(app/views/notifier/foo\.text\.erb), view - assert_match /<%= @greeting %>/, view + assert_match(%r(app/views/notifier/foo\.text\.erb), view) + assert_match(/<%= @greeting %>/, view) end assert_file "app/views/notifier/bar.text.erb" do |view| - assert_match %r(app/views/notifier/bar\.text\.erb), view - assert_match /<%= @greeting %>/, view + assert_match(%r(app/views/notifier/bar\.text\.erb), view) + assert_match(/<%= @greeting %>/, view) end end @@ -60,14 +60,14 @@ class MailerGeneratorTest < Rails::Generators::TestCase 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 + assert_match(/haml \[not found\]/, content) end def test_mailer_with_namedspaced_mailer run_generator ["Farm::Animal", "moos"] assert_file "app/mailers/farm/animal.rb" do |mailer| - assert_match /class Farm::Animal < ActionMailer::Base/, mailer - assert_match /en\.farm\.animal\.moos\.subject/, mailer + assert_match(/class Farm::Animal < ActionMailer::Base/, mailer) + assert_match(/en\.farm\.animal\.moos\.subject/, mailer) end assert_file "app/views/farm/animal/moos.text.erb" end @@ -78,20 +78,20 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_file "app/mailers/notifier.rb" do |mailer| assert_instance_method :foo, mailer do |foo| if RUBY_VERSION < "1.9" - assert_match /mail :to => "to@example.org"/, foo + assert_match(/mail :to => "to@example.org"/, foo) else - assert_match /mail to: "to@example.org"/, foo + assert_match(/mail to: "to@example.org"/, foo) end - assert_match /@greeting = "Hi"/, foo + assert_match(/@greeting = "Hi"/, foo) end assert_instance_method :bar, mailer do |bar| if RUBY_VERSION < "1.9" - assert_match /mail :to => "to@example.org"/, bar + assert_match(/mail :to => "to@example.org"/, bar) else - assert_match /mail to: "to@example.org"/, bar + assert_match(/mail to: "to@example.org"/, bar) end - assert_match /@greeting = "Hi"/, bar + assert_match(/@greeting = "Hi"/, bar) end end end @@ -99,10 +99,10 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_force_old_style_hash run_generator ["notifier", "foo", "--old-style-hash"] assert_file "app/mailers/notifier.rb" do |mailer| - assert_match /default :from => "from@example.com"/, mailer + assert_match(/default :from => "from@example.com"/, mailer) assert_instance_method :foo, mailer do |foo| - assert_match /mail :to => "to@example.org"/, foo + assert_match(/mail :to => "to@example.org"/, foo) end end end diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb index 6eecfc8e2e..337257df7d 100644 --- a/railties/test/generators/migration_generator_test.rb +++ b/railties/test/generators/migration_generator_test.rb @@ -35,8 +35,8 @@ class MigrationGeneratorTest < Rails::Generators::TestCase assert_migration "db/migrate/#{migration}.rb" do |content| assert_method :change, content do |up| - assert_match /add_column :posts, :title, :string/, up - assert_match /add_column :posts, :body, :text/, up + assert_match(/add_column :posts, :title, :string/, up) + assert_match(/add_column :posts, :body, :text/, up) end end end @@ -47,13 +47,13 @@ class MigrationGeneratorTest < Rails::Generators::TestCase assert_migration "db/migrate/#{migration}.rb" do |content| assert_method :up, content do |up| - assert_match /remove_column :posts, :title/, up - assert_match /remove_column :posts, :body/, up + assert_match(/remove_column :posts, :title/, up) + assert_match(/remove_column :posts, :body/, up) end assert_method :down, content do |down| - assert_match /add_column :posts, :title, :string/, down - assert_match /add_column :posts, :body, :text/, down + assert_match(/add_column :posts, :title, :string/, down) + assert_match(/add_column :posts, :body, :text/, down) end end end @@ -64,11 +64,11 @@ class MigrationGeneratorTest < Rails::Generators::TestCase assert_migration "db/migrate/#{migration}.rb" do |content| assert_method :up, content do |up| - assert_match /^\s*$/, up + assert_match(/^\s*$/, up) end assert_method :down, content do |down| - assert_match /^\s*$/, down + assert_match(/^\s*$/, down) end end end diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb index 3d773b4134..8c5ba9926b 100644 --- a/railties/test/generators/model_generator_test.rb +++ b/railties/test/generators/model_generator_test.rb @@ -7,14 +7,14 @@ class ModelGeneratorTest < Rails::Generators::TestCase def test_help_shows_invoked_generators_options content = run_generator ["--help"] - assert_match /ActiveRecord options:/, content - assert_match /TestUnit options:/, content + assert_match(/ActiveRecord options:/, content) + assert_match(/TestUnit options:/, content) end def test_model_with_missing_attribute_type content = capture(:stderr) { run_generator ["post", "title:string", "body"] } - assert_match /Missing type for attribute 'body'/, content - assert_match /Example: 'body:string' where string is the type/, content + assert_match(/Missing type for attribute 'body'/, content) + assert_match(/Example: 'body:string' where string is the type/, content) end def test_invokes_default_orm @@ -100,9 +100,9 @@ class ModelGeneratorTest < Rails::Generators::TestCase assert_migration "db/migrate/create_products.rb" do |m| assert_method :change, m do |up| - assert_match /create_table :products/, up - assert_match /t\.string :name/, up - assert_match /t\.integer :supplier_id/, up + assert_match(/create_table :products/, up) + assert_match(/t\.string :name/, up) + assert_match(/t\.integer :supplier_id/, up) end end end @@ -138,7 +138,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase assert_migration "db/migrate/create_accounts.rb" do |m| assert_method :change, m do |up| - assert_no_match /t.timestamps/, up + assert_no_match(/t.timestamps/, up) end end end @@ -164,7 +164,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase 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 + assert_no_match(/Another migration is already named create_accounts/, error) end def test_migration_is_removed_on_revoke @@ -177,7 +177,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase run_generator old_migration = Dir["#{destination_root}/db/migrate/*_create_accounts.rb"].first error = capture(:stderr) { run_generator ["Account", "--force"] } - assert_no_match /Another migration is already named create_accounts/, error + assert_no_match(/Another migration is already named create_accounts/, error) assert_no_file old_migration assert_migration 'db/migrate/create_accounts.rb' end @@ -195,13 +195,13 @@ class ModelGeneratorTest < Rails::Generators::TestCase 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_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 + assert_match(/The name 'Object' is either already used in your application or reserved/, content) end def test_index_is_added_for_belongs_to_association @@ -209,7 +209,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase assert_migration "db/migrate/create_accounts.rb" do |m| assert_method :change, m do |up| - assert_match /add_index/, up + assert_match(/add_index/, up) end end end @@ -219,7 +219,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase assert_migration "db/migrate/create_accounts.rb" do |m| assert_method :change, m do |up| - assert_match /add_index/, up + assert_match(/add_index/, up) end end end @@ -229,7 +229,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase assert_migration "db/migrate/create_accounts.rb" do |m| assert_method :change, m do |up| - assert_no_match /add_index/, up + assert_no_match(/add_index/, up) end end end @@ -239,9 +239,8 @@ class ModelGeneratorTest < Rails::Generators::TestCase assert_migration "db/migrate/create_accounts.rb" do |m| assert_method :change, m do |up| - assert_no_match /add_index/, up + assert_no_match(/add_index/, up) end end end - end diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb index 38f024f061..6f8a9b4280 100644 --- a/railties/test/generators/namespaced_generators_test.rb +++ b/railties/test/generators/namespaced_generators_test.rb @@ -161,12 +161,12 @@ class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase def test_mailer_skeleton_is_created run_generator assert_file "app/mailers/test_app/notifier.rb" do |mailer| - assert_match /module TestApp/, mailer - assert_match /class Notifier < ActionMailer::Base/, mailer + assert_match(/module TestApp/, mailer) + assert_match(/class Notifier < ActionMailer::Base/, mailer) if RUBY_VERSION < "1.9" - assert_match /default :from => "from@example.com"/, mailer + assert_match(/default :from => "from@example.com"/, mailer) else - assert_match /default from: "from@example.com"/, mailer + assert_match(/default from: "from@example.com"/, mailer) end end end @@ -174,31 +174,31 @@ class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase def test_mailer_with_i18n_helper run_generator assert_file "app/mailers/test_app/notifier.rb" do |mailer| - assert_match /en\.notifier\.foo\.subject/, mailer - assert_match /en\.notifier\.bar\.subject/, mailer + assert_match(/en\.notifier\.foo\.subject/, mailer) + assert_match(/en\.notifier\.bar\.subject/, mailer) end end def test_invokes_default_test_framework run_generator assert_file "test/functional/test_app/notifier_test.rb" do |test| - assert_match /module TestApp/, test - assert_match /class NotifierTest < ActionMailer::TestCase/, test - assert_match /test "foo"/, test - assert_match /test "bar"/, test + assert_match(/module TestApp/, test) + assert_match(/class NotifierTest < ActionMailer::TestCase/, test) + assert_match(/test "foo"/, test) + assert_match(/test "bar"/, test) end end def test_invokes_default_template_engine run_generator assert_file "app/views/test_app/notifier/foo.text.erb" do |view| - assert_match %r(app/views/test_app/notifier/foo\.text\.erb), view - assert_match /<%= @greeting %>/, view + assert_match(%r(app/views/test_app/notifier/foo\.text\.erb), view) + assert_match(/<%= @greeting %>/, view) end assert_file "app/views/test_app/notifier/bar.text.erb" do |view| - assert_match %r(app/views/test_app/notifier/bar\.text\.erb), view - assert_match /<%= @greeting %>/, view + assert_match(%r(app/views/test_app/notifier/bar\.text\.erb), view) + assert_match(/<%= @greeting %>/, view) end end diff --git a/railties/test/generators/observer_generator_test.rb b/railties/test/generators/observer_generator_test.rb index 45fe8dfbd3..afcee0a2dc 100644 --- a/railties/test/generators/observer_generator_test.rb +++ b/railties/test/generators/observer_generator_test.rb @@ -22,6 +22,6 @@ class ObserverGeneratorTest < Rails::Generators::TestCase def test_logs_if_the_test_framework_cannot_be_found content = run_generator ["account", "--test-framework=rspec"] - assert_match /rspec \[not found\]/, content + assert_match(/rspec \[not found\]/, content) end end diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb index e6686a6af4..5c0774ddbd 100644 --- a/railties/test/generators/plugin_generator_test.rb +++ b/railties/test/generators/plugin_generator_test.rb @@ -32,7 +32,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase 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 + assert_match(/The name 'Object' is either already used in your application or reserved/, content) end def test_invokes_default_test_framework @@ -44,7 +44,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase def test_logs_if_the_test_framework_cannot_be_found content = nil silence(:stderr) { content = run_generator ["plugin_fu", "--test-framework=rspec"] } - assert_match /rspec \[not found\]/, content + assert_match(/rspec \[not found\]/, content) end def test_creates_tasks_if_required @@ -66,6 +66,6 @@ class PluginGeneratorTest < Rails::Generators::TestCase def test_deprecation output = capture(:stderr) { run_generator } - assert_match /Plugin generator is deprecated, please use 'rails plugin new' command to generate plugin structure./, output + assert_match(/Plugin generator is deprecated, please use 'rails plugin new' command to generate plugin structure./, output) end end diff --git a/railties/test/generators/plugin_new_generator_test.rb b/railties/test/generators/plugin_new_generator_test.rb index 2af728e766..297ac5d238 100644 --- a/railties/test/generators/plugin_new_generator_test.rb +++ b/railties/test/generators/plugin_new_generator_test.rb @@ -95,6 +95,11 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase assert_file "test/dummy/config/database.yml", /postgres/ end + def test_generation_runs_bundle_install_with_full_and_mountable + result = run_generator [destination_root, "--mountable", "--full"] + assert_equal 1, result.scan("Your bundle is complete").size + end + def test_skipping_javascripts_without_mountable_option run_generator assert_no_file "app/assets/javascripts/application.js" diff --git a/railties/test/generators/resource_generator_test.rb b/railties/test/generators/resource_generator_test.rb index 71b3619351..73804dae45 100644 --- a/railties/test/generators/resource_generator_test.rb +++ b/railties/test/generators/resource_generator_test.rb @@ -9,8 +9,8 @@ class ResourceGeneratorTest < Rails::Generators::TestCase def test_help_with_inherited_options content = run_generator ["--help"] - assert_match /ActiveRecord options:/, content - assert_match /TestUnit options:/, content + assert_match(/ActiveRecord options:/, content) + assert_match(/TestUnit options:/, content) end def test_files_from_inherited_invocation @@ -55,7 +55,7 @@ class ResourceGeneratorTest < Rails::Generators::TestCase run_generator assert_file "config/routes.rb" do |route| - assert_match /resources :accounts$/, route + assert_match(/resources :accounts$/, route) end end @@ -63,19 +63,19 @@ class ResourceGeneratorTest < Rails::Generators::TestCase content = run_generator ["accounts".freeze] 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 + 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 + assert_no_match(/Plural version of the model detected/, content) end def test_mass_nouns_do_not_throw_warnings content = run_generator ["sheep".freeze] - assert_no_match /Plural version of the model detected/, content + assert_no_match(/Plural version of the model detected/, content) end def test_route_is_removed_on_revoke @@ -83,7 +83,7 @@ class ResourceGeneratorTest < Rails::Generators::TestCase run_generator ["account"], :behavior => :revoke assert_file "config/routes.rb" do |route| - assert_no_match /resources :accounts$/, route + assert_no_match(/resources :accounts$/, route) end end end diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb index c7f45a807d..65b30b9fbd 100644 --- a/railties/test/generators/scaffold_controller_generator_test.rb +++ b/railties/test/generators/scaffold_controller_generator_test.rb @@ -14,39 +14,39 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase run_generator assert_file "app/controllers/users_controller.rb" do |content| - assert_match /class UsersController < ApplicationController/, content + assert_match(/class UsersController < ApplicationController/, content) assert_instance_method :index, content do |m| - assert_match /@users = User\.all/, m + assert_match(/@users = User\.all/, m) end assert_instance_method :show, content do |m| - assert_match /@user = User\.find\(params\[:id\]\)/, m + assert_match(/@user = User\.find\(params\[:id\]\)/, m) end assert_instance_method :new, content do |m| - assert_match /@user = User\.new/, m + assert_match(/@user = User\.new/, m) end assert_instance_method :edit, content do |m| - assert_match /@user = User\.find\(params\[:id\]\)/, m + assert_match(/@user = User\.find\(params\[:id\]\)/, m) end assert_instance_method :create, content do |m| - assert_match /@user = User\.new\(params\[:user\]\)/, m - assert_match /@user\.save/, m - assert_match /@user\.errors/, m + assert_match(/@user = User\.new\(params\[:user\]\)/, m) + assert_match(/@user\.save/, m) + assert_match(/@user\.errors/, m) end assert_instance_method :update, content do |m| - assert_match /@user = User\.find\(params\[:id\]\)/, m - assert_match /@user\.update_attributes\(params\[:user\]\)/, m - assert_match /@user\.errors/, 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 :destroy, content do |m| - assert_match /@user = User\.find\(params\[:id\]\)/, m - assert_match /@user\.destroy/, m + assert_match(/@user = User\.find\(params\[:id\]\)/, m) + assert_match(/@user\.destroy/, m) end end end @@ -73,8 +73,8 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase 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 + assert_match(/class UsersControllerTest < ActionController::TestCase/, content) + assert_match(/test "should get index"/, content) end end @@ -93,10 +93,10 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase run_generator ["User", "--orm=unknown"] assert_file "app/controllers/users_controller.rb" do |content| - assert_match /class UsersController < ApplicationController/, content + assert_match(/class UsersController < ApplicationController/, content) assert_instance_method :index, content do |m| - assert_match /@users = User\.all/, m + assert_match(/@users = User\.all/, m) end end end @@ -112,11 +112,11 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase run_generator ["User", "--orm=unknown"] assert_file "app/controllers/users_controller.rb" do |content| - assert_match /class UsersController < ApplicationController/, content + assert_match(/class UsersController < ApplicationController/, content) assert_instance_method :index, content do |m| - assert_match /@users = User\.find\(:all\)/, m - assert_no_match /@users = User\.all/, m + assert_match(/@users = User\.find\(:all\)/, m) + assert_no_match(/@users = User\.all/, m) end end ensure @@ -127,9 +127,9 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase run_generator assert_file "app/controllers/users_controller.rb" do |content| if RUBY_VERSION < "1.9" - assert_match /\{ render :action => "new" \}/, content + assert_match(/\{ render :action => "new" \}/, content) else - assert_match /\{ render action: "new" \}/, content + assert_match(/\{ render action: "new" \}/, content) end end end @@ -137,7 +137,7 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase def test_force_old_style_hash run_generator ["User", "--old-style-hash"] assert_file "app/controllers/users_controller.rb" do |content| - assert_match /\{ render :action => "new" \}/, content + assert_match(/\{ render :action => "new" \}/, content) end end end diff --git a/railties/test/generators/session_migration_generator_test.rb b/railties/test/generators/session_migration_generator_test.rb index 9fee948d7c..b590047ff0 100644 --- a/railties/test/generators/session_migration_generator_test.rb +++ b/railties/test/generators/session_migration_generator_test.rb @@ -18,8 +18,8 @@ class SessionMigrationGeneratorTest < Rails::Generators::TestCase ActiveRecord::SessionStore::Session.table_name = "custom_table_name" run_generator assert_migration "db/migrate/add_sessions_table.rb" do |migration| - assert_match /class AddSessionsTable < ActiveRecord::Migration/, migration - assert_match /create_table :custom_table_name/, migration + assert_match(/class AddSessionsTable < ActiveRecord::Migration/, migration) + assert_match(/create_table :custom_table_name/, migration) end ensure ActiveRecord::SessionStore::Session.table_name = "sessions" diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb index 99c9d790eb..1264ac7764 100644 --- a/railties/test/generators_test.rb +++ b/railties/test/generators_test.rb @@ -28,7 +28,7 @@ class GeneratorsTest < Rails::Generators::TestCase def test_help_when_a_generator_with_required_arguments_is_invoked_without_arguments output = capture(:stdout){ Rails::Generators.invoke :model, [] } - assert_match /Description:/, output + assert_match(/Description:/, output) end def test_should_give_higher_preference_to_rails_generators @@ -90,8 +90,8 @@ class GeneratorsTest < Rails::Generators::TestCase def test_find_by_namespace_show_warning_if_generator_cant_be_loaded output = capture(:stderr) { Rails::Generators.find_by_namespace(:wrong) } - assert_match /\[WARNING\] Could not load generator/, output - assert_match /Rails 2\.x generator/, output + assert_match(/\[WARNING\] Could not load generator/, output) + assert_match(/Rails 2\.x generator/, output) end def test_invoke_with_nested_namespaces @@ -104,38 +104,38 @@ class GeneratorsTest < Rails::Generators::TestCase def test_rails_generators_help_with_builtin_information output = capture(:stdout){ Rails::Generators.help } - assert_match /Rails:/, output - assert_match /^ model$/, output - assert_match /^ scaffold_controller$/, output - assert_no_match /^ app$/, output + assert_match(/Rails:/, output) + assert_match(/^ model$/, output) + assert_match(/^ scaffold_controller$/, output) + assert_no_match(/^ app$/, output) end def test_rails_generators_help_does_not_include_app_nor_plugin_new output = capture(:stdout){ Rails::Generators.help } - assert_no_match /app/, output - assert_no_match /plugin_new/, output + assert_no_match(/app/, output) + assert_no_match(/plugin_new/, output) end def test_rails_generators_with_others_information output = capture(:stdout){ Rails::Generators.help } - assert_match /Fixjour:/, output - assert_match /^ fixjour$/, output + assert_match(/Fixjour:/, output) + assert_match(/^ fixjour$/, output) end def test_rails_generators_does_not_show_active_record_hooks output = capture(:stdout){ Rails::Generators.help } - assert_match /ActiveRecord:/, output - assert_match /^ active_record:fixjour$/, output + assert_match(/ActiveRecord:/, output) + assert_match(/^ active_record:fixjour$/, output) end def test_default_banner_should_show_generator_namespace klass = Rails::Generators.find_by_namespace(:foobar) - assert_match /^rails generate foobar:foobar/, klass.banner + assert_match(/^rails generate foobar:foobar/, klass.banner) end def test_default_banner_should_not_show_rails_generator_namespace klass = Rails::Generators.find_by_namespace(:model) - assert_match /^rails generate model/, klass.banner + assert_match(/^rails generate model/, klass.banner) end def test_no_color_sets_proper_shell |