aboutsummaryrefslogtreecommitdiffstats
path: root/railties
diff options
context:
space:
mode:
authorJeff Dean <jeff@zilkey.com>2008-11-13 00:06:27 -0500
committerJeff Dean <jeff@zilkey.com>2008-11-13 00:06:27 -0500
commitc78c247c7293781438ba524b15d1ca6c5989ed0e (patch)
tree51914b48fdce370c02e9f63515dfb772d44820f5 /railties
parent40bc386ed8cc403050292ab19428f1e467fa1737 (diff)
parent1dff35063becf4a52eb38db799345650b60f500a (diff)
downloadrails-c78c247c7293781438ba524b15d1ca6c5989ed0e.tar.gz
rails-c78c247c7293781438ba524b15d1ca6c5989ed0e.tar.bz2
rails-c78c247c7293781438ba524b15d1ca6c5989ed0e.zip
Merge branch 'master' of git@github.com:lifo/docrails
Diffstat (limited to 'railties')
-rw-r--r--railties/doc/guides/html/2_2_release_notes.html24
-rw-r--r--railties/doc/guides/html/actioncontroller_basics.html8
-rw-r--r--railties/doc/guides/html/activerecord_validations_callbacks.html38
-rw-r--r--railties/doc/guides/html/caching_with_rails.html72
-rw-r--r--railties/doc/guides/html/routing_outside_in.html38
-rw-r--r--railties/doc/guides/source/2_2_release_notes.txt14
-rw-r--r--railties/doc/guides/source/activerecord_validations_callbacks.txt30
-rw-r--r--railties/doc/guides/source/command_line.txt147
-rw-r--r--railties/doc/guides/source/routing_outside_in.txt26
-rw-r--r--railties/doc/guides/source/testing_rails_applications.txt390
10 files changed, 603 insertions, 184 deletions
diff --git a/railties/doc/guides/html/2_2_release_notes.html b/railties/doc/guides/html/2_2_release_notes.html
index 59e862a3cb..e79f7ec511 100644
--- a/railties/doc/guides/html/2_2_release_notes.html
+++ b/railties/doc/guides/html/2_2_release_notes.html
@@ -243,6 +243,8 @@ ul#navMain {
<li><a href="#_method_arrays_for_member_or_collection_routes">Method Arrays for Member or Collection Routes</a></li>
+ <li><a href="#_resources_with_specific_actions">Resources With Specific Actions</a></li>
+
<li><a href="#_other_action_controller_changes">Other Action Controller Changes</a></li>
</ul>
@@ -698,7 +700,7 @@ Counter cache columns (for associations declared with <tt>:counter_cache &#8658;
</div>
<h2 id="_action_controller">6. Action Controller</h2>
<div class="sectionbody">
-<div class="para"><p>On the controller side, there are a couple of changes that will help tidy up your routes.</p></div>
+<div class="para"><p>On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications.</p></div>
<h3 id="_shallow_route_nesting">6.1. Shallow Route Nesting</h3>
<div class="para"><p>Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with.</p></div>
<div class="listingblock">
@@ -761,8 +763,24 @@ Lead Contributor: <a href="http://brennandunn.com/">Brennan Dunn</a>
</p>
</li>
</ul></div>
-<div class="para"><p>Action Controller now offers good support for HTTP conditional GET requests, as well as some other additions.</p></div>
-<h3 id="_other_action_controller_changes">6.3. Other Action Controller Changes</h3>
+<h3 id="_resources_with_specific_actions">6.3. Resources With Specific Actions</h3>
+<div class="para"><p>By default, when you use <tt>map.resources</tt> to create a route, Rails generates routes for seven default actions (index, show, create, new, edit, update, and destroy). But each of these routes takes up memory in your application, and causes Rails to generate additional routing logic. Now you can use the <tt>:only</tt> and <tt>:except</tt> options to fine-tune the routes that Rails will generate for resources. You can supply a single action, an array of actions, or the special <tt>:all</tt> or <tt>:none</tt> options. These options are inherited by nested resources.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>map<span style="color: #990000">.</span>resources <span style="color: #990000">:</span>photos<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[:</span>index<span style="color: #990000">,</span> <span style="color: #990000">:</span>show<span style="color: #990000">]</span>
+map<span style="color: #990000">.</span>resources <span style="color: #990000">:</span>products<span style="color: #990000">,</span> <span style="color: #990000">:</span>except <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>destroy
+</tt></pre></div></div>
+<div class="ilist"><ul>
+<li>
+<p>
+Lead Contributor: <a href="http://experthuman.com/">Tom Stuart</a>
+</p>
+</li>
+</ul></div>
+<h3 id="_other_action_controller_changes">6.4. Other Action Controller Changes</h3>
<div class="ilist"><ul>
<li>
<p>
diff --git a/railties/doc/guides/html/actioncontroller_basics.html b/railties/doc/guides/html/actioncontroller_basics.html
index 19d7e9e502..66563bf1a3 100644
--- a/railties/doc/guides/html/actioncontroller_basics.html
+++ b/railties/doc/guides/html/actioncontroller_basics.html
@@ -925,7 +925,7 @@ http://www.gnu.org/software/src-highlite -->
<div class="sectionbody">
<div class="para"><p>In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The <tt>request</tt> method contains an instance of AbstractRequest and the <tt>response</tt> method returns a <tt>response</tt> object representing what is going to be sent back to the client.</p></div>
<h3 id="_the_tt_request_tt_object">9.1. The <tt>request</tt> Object</h3>
-<div class="para"><p>The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the <a href="http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html">API documentation</a>. Among the properties that you can access on this object:</p></div>
+<div class="para"><p>The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the <a href="http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html">API documentation</a>. Among the properties that you can access on this object are:</p></div>
<div class="ilist"><ul>
<li>
<p>
@@ -1039,7 +1039,7 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AdminController <span style="color: #990000">&lt;</span> ApplicationController
- USERNAME<span style="color: #990000">,</span> PASSWORD <span style="color: #990000">=</span> <span style="color: #FF0000">"humbaba"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"f59a4805511bf4bb61978445a5380c6c"</span>
+ USERNAME<span style="color: #990000">,</span> PASSWORD <span style="color: #990000">=</span> <span style="color: #FF0000">"humbaba"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"</span>
before_filter <span style="color: #990000">:</span>authenticate
@@ -1047,7 +1047,7 @@ private
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> authenticate
authenticate_or_request_with_http_basic <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>username<span style="color: #990000">,</span> password<span style="color: #990000">|</span>
- username <span style="color: #990000">==</span> USERNAME <span style="color: #990000">&amp;&amp;</span> Digest<span style="color: #990000">::</span>MD5<span style="color: #990000">.</span>hexdigest<span style="color: #990000">(</span>password<span style="color: #990000">)</span> <span style="color: #990000">==</span> PASSWORD
+ username <span style="color: #990000">==</span> USERNAME <span style="color: #990000">&amp;&amp;</span> Digest<span style="color: #990000">::</span>SHA1<span style="color: #990000">.</span>hexdigest<span style="color: #990000">(</span>password<span style="color: #990000">)</span> <span style="color: #990000">==</span> PASSWORD
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -1104,7 +1104,7 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the <tt>stream</tt> option or adjust the block size with the <tt>buffer_size</tt> option.</p></div>
+<div class="para"><p>This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the <tt>:stream</tt> option or adjust the block size with the <tt>:buffer_size</tt> option.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html
index 209722e9e0..45eec6ffa1 100644
--- a/railties/doc/guides/html/activerecord_validations_callbacks.html
+++ b/railties/doc/guides/html/activerecord_validations_callbacks.html
@@ -264,6 +264,9 @@ ul#navMain {
</ul>
</li>
<li>
+ <a href="#_writing_your_own_validation_methods">Writing your own validation methods</a>
+ </li>
+ <li>
<a href="#_changelog">Changelog</a>
</li>
</ol>
@@ -702,7 +705,40 @@ http://www.gnu.org/software/src-highlite -->
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
</div>
-<h2 id="_changelog">6. Changelog</h2>
+<h2 id="_writing_your_own_validation_methods">6. Writing your own validation methods</h2>
+<div class="sectionbody">
+<div class="para"><p>When the built-in validation helpers are not enough for your needs, you can write your own validation methods, by implementing one or more of the <tt>validate</tt>, <tt>validate_on_create</tt> or <tt>validate_on_update</tt> methods. As the names of the methods states, the right method to implement depends on when you want the validations to be ran. The meaning of valid is still the same: to make an object invalid you just need to add a message to it's <tt>errors</tt> collection.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Invoice <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> validate_on_create
+ errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+<div class="para"><p>If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of <tt>validate</tt>, <tt>validate_on_create</tt> or <tt>validate_on_update</tt> methods, passing it the symbols for the methods' names.</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Invoice <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
+ validate <span style="color: #990000">:</span>expiration_date_cannot_be_in_the_past<span style="color: #990000">,</span> <span style="color: #990000">:</span>discount_cannot_be_be_more_than_total_value
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> expiration_date_cannot_be_in_the_past
+ errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>expiration_date<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be in the past"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #990000">!</span>expiration_date<span style="color: #990000">.</span>blank? <span style="font-weight: bold"><span style="color: #0000FF">and</span></span> expiration_date <span style="color: #990000">&lt;</span> Date<span style="color: #990000">.</span>today
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> discount_cannot_be_greater_than_total_value
+ errors<span style="color: #990000">.</span>add<span style="color: #990000">(:</span>discount<span style="color: #990000">,</span> <span style="color: #FF0000">"can't be greater than total value"</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> discount <span style="color: #990000">&lt;=</span> total_value
+ <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+</tt></pre></div></div>
+</div>
+<h2 id="_changelog">7. Changelog</h2>
<div class="sectionbody">
<div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks">http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks</a></p></div>
</div>
diff --git a/railties/doc/guides/html/caching_with_rails.html b/railties/doc/guides/html/caching_with_rails.html
index df30c46c35..7aa5999e1a 100644
--- a/railties/doc/guides/html/caching_with_rails.html
+++ b/railties/doc/guides/html/caching_with_rails.html
@@ -235,48 +235,54 @@ need to return to those hungry web clients in the shortest time possible.</p></d
<div class="sectionbody">
<div class="para"><p>This is an introduction to the three types of caching techniques that Rails
provides by default without the use of any third party plugins.</p></div>
-<div class="para"><p>To get started make sure Base.perform_caching is set to true for your
-environment.</p></div>
+<div class="para"><p>To get started make sure config.action_controller.perform_caching is set
+to true for your environment. This flag is normally set in the
+corresponding config/environments/*.rb and caching is disabled by default
+there for development and test, and enabled for production.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt>Base<span style="color: #990000">.</span>perform_caching <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
+<pre><tt>config<span style="color: #990000">.</span>action_controller<span style="color: #990000">.</span>perform_caching <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
</tt></pre></div></div>
<h3 id="_page_caching">1.1. Page Caching</h3>
<div class="para"><p>Page caching is a Rails mechanism which allows the request for a generated
page to be fulfilled by the webserver, without ever having to go through the
-Rails stack at all. Obviously, this is super fast. Unfortunately, it can't be
+Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be
applied to every situation (such as pages that need authentication) and since
the webserver is literally just serving a file from the filesystem, cache
expiration is an issue that needs to be dealt with.</p></div>
<div class="para"><p>So, how do you enable this super-fast cache behavior? Simple, let's say you
-have a controller called ProductController and a <em>list</em> action that lists all
+have a controller called ProductsController and a <em>list</em> action that lists all
the products</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000">&lt;</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</span> ActionController
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>index
- <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> list<span style="color: #990000">;</span> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
+ <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> index<span style="color: #990000">;</span> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
</tt></pre></div></div>
-<div class="para"><p>The first time anyone requestsion products/list, Rails will generate a file
-called list.html and the webserver will then look for that file before it
-passes the next request for products/list to your Rails application.</p></div>
+<div class="para"><p>The first time anyone requests products/index, Rails will generate a file
+called index.html and the webserver will then look for that file before it
+passes the next request for products/index to your Rails application.</p></div>
<div class="para"><p>By default, the page cache directory is set to Rails.public_path (which is
-usually set to RAILS_ROOT + "/public") and this can be configured by changing
-the configuration setting Base.cache_public_directory</p></div>
-<div class="para"><p>The page caching mechanism will automatically add a .html exxtension to
+usually set to RAILS_ROOT + "/public") and this can be configured by
+changing the configuration setting ActionController::Base.page_cache_directory. Changing the
+default from /public helps avoid naming conflicts, since you may want to
+put other static html in /public, but changing this will require web
+server reconfiguration to let the web server know where to serve the
+cached files from.</p></div>
+<div class="para"><p>The Page Caching mechanism will automatically add a .html exxtension to
requests for pages that do not have an extension to make it easy for the
webserver to find those pages and this can be configured by changing the
-configuration setting Base.page_cache_extension</p></div>
+configuration setting ActionController::Base.page_cache_extension.</p></div>
<div class="para"><p>In order to expire this page when a new product is added we could extend our
example controler like this:</p></div>
<div class="listingblock">
@@ -284,9 +290,9 @@ example controler like this:</p></div>
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000">&lt;</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</span> ActionController
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>list
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> list<span style="color: #990000">;</span> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -299,11 +305,11 @@ http://www.gnu.org/software/src-highlite -->
<div class="para"><p>If you want a more complicated expiration scheme, you can use cache sweepers
to expire cached objects when things change. This is covered in the section on Sweepers.</p></div>
<h3 id="_action_caching">1.2. Action Caching</h3>
-<div class="para"><p>One of the issues with page caching is that you cannot use it for pages that
+<div class="para"><p>One of the issues with Page Caching is that you cannot use it for pages that
require to restrict access somehow. This is where Action Caching comes in.
Action Caching works like Page Caching except for the fact that the incoming
web request does go from the webserver to the Rails stack and Action Pack so
-that before_filters can be run on it before the cache is served, so that
+that before filters can be run on it before the cache is served, so that
authentication and other restrictions can be used while still serving the
result of the output from a cached copy.</p></div>
<div class="para"><p>Clearing the cache works in the exact same way as with Page Caching.</p></div>
@@ -314,10 +320,10 @@ object, but still cache those pages:</p></div>
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000">&lt;</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</span> ActionController
before_filter <span style="color: #990000">:</span>authenticate<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>edit<span style="color: #990000">,</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>list
caches_action <span style="color: #990000">:</span>edit
<span style="font-weight: bold"><span style="color: #0000FF">def</span></span> list<span style="color: #990000">;</span> <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
@@ -336,7 +342,7 @@ action should be cached. Also, you can use :layout &#8658; false to cache withou
layout so that dynamic information in the layout such as logged in user info
or the number of items in the cart can be left uncached. This feature is
available as of Rails 2.2.</p></div>
-<div class="para"><p>[More: more examples? Walk-through of action caching from request to response?
+<div class="para"><p>[More: more examples? Walk-through of Action Caching from request to response?
Description of Rake tasks to clear cached files? Show example of
subdomain caching? Talk about :cache_path, :if and assing blocks/Procs
to expire_action?]</p></div>
@@ -346,13 +352,13 @@ a page or action and serving it out to the world. Unfortunately, dynamic web
applications usually build pages with a variety of components not all of which
have the same caching characteristics. In order to address such a dynamically
created page where different parts of the page need to be cached and expired
-differently Rails provides a mechanism called Fragment caching.</p></div>
-<div class="para"><p>Fragment caching allows a fragment of view logic to be wrapped in a cache
+differently Rails provides a mechanism called Fragment Caching.</p></div>
+<div class="para"><p>Fragment Caching allows a fragment of view logic to be wrapped in a cache
block and served out of the cache store when the next request comes in.</p></div>
-<div class="para"><p>As an example, if you wanted to show all the orders placed on your website in
-real time and didn't want to cache that part of the page, but did want to
-cache the part of the page which lists all products available, you could use
-this piece of code:</p></div>
+<div class="para"><p>As an example, if you wanted to show all the orders placed on your website
+in real time and didn't want to cache that part of the page, but did want
+to cache the part of the page which lists all products available, you
+could use this piece of code:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -371,7 +377,7 @@ http://www.gnu.org/software/src-highlite -->
</tt></pre></div></div>
<div class="para"><p>The cache block in our example will bind to the action that called it and is
written out to the same place as the Action Cache, which means that if you
-want to cache multiple fragments per action, you should provide an action_path to the cache call:</p></div>
+want to cache multiple fragments per action, you should provide an action_suffix to the cache call:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
@@ -439,10 +445,10 @@ following:</p></div>
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000">&lt;</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</span> ActionController
before_filter <span style="color: #990000">:</span>authenticate<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>edit<span style="color: #990000">,</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>list
caches_action <span style="color: #990000">:</span>edit
cache_sweeper <span style="color: #990000">:</span>store_sweeper<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
@@ -468,10 +474,10 @@ database again.</p></div>
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductController <span style="color: #990000">&lt;</span> ActionController
+<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</span> ActionController
before_filter <span style="color: #990000">:</span>authenticate<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>edit<span style="color: #990000">,</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
- cache_page <span style="color: #990000">:</span>list
+ caches_page <span style="color: #990000">:</span>list
caches_action <span style="color: #990000">:</span>edit
cache_sweeper <span style="color: #990000">:</span>store_sweeper<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span> <span style="color: #990000">:</span>create <span style="color: #990000">]</span>
diff --git a/railties/doc/guides/html/routing_outside_in.html b/railties/doc/guides/html/routing_outside_in.html
index bf9992ff4e..8add4e7789 100644
--- a/railties/doc/guides/html/routing_outside_in.html
+++ b/railties/doc/guides/html/routing_outside_in.html
@@ -925,6 +925,16 @@ cellspacing="0" cellpadding="4">
<tt>:name_prefix</tt>
</p>
</li>
+<li>
+<p>
+<tt>:only</tt>
+</p>
+</li>
+<li>
+<p>
+<tt>:except</tt>
+</p>
+</li>
</ul></div>
<div class="para"><p>You can also add additional routes via the <tt>:member</tt> and <tt>:collection</tt> options, which are discussed later in this guide.</p></div>
<h4 id="_using_controller">3.6.1. Using :controller</h4>
@@ -1419,6 +1429,34 @@ map<span style="color: #990000">.</span>resources <span style="color: #990000">:
<td class="content">You can also use <tt>:name_prefix</tt> with non-RESTful routes.</td>
</tr></table>
</div>
+<h4 id="_using_only_and_except">3.7.8. Using :only and :except</h4>
+<div class="para"><p>By default, Rails creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the <tt>:only</tt> and <tt>:except</tt> options to fine-tune this behavior. The <tt>:only</tt> option specifies that only certain routes should be generated:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>map<span style="color: #990000">.</span>resources <span style="color: #990000">:</span>photos<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[:</span>index<span style="color: #990000">,</span> <span style="color: #990000">:</span>show<span style="color: #990000">]</span>
+</tt></pre></div></div>
+<div class="para"><p>With this declaration, a <tt>GET</tt> request to <tt>/photos</tt> would succeed, but a <tt>POST</tt> request to <tt>/photos</tt> (which would ordinarily be routed to the create action) will fail.</p></div>
+<div class="para"><p>The <tt>:except</tt> option specifies a route or list of routes that should <em>not</em> be generated:</p></div>
+<div class="listingblock">
+<div class="content"><!-- Generator: GNU source-highlight 2.9
+by Lorenzo Bettini
+http://www.lorenzobettini.it
+http://www.gnu.org/software/src-highlite -->
+<pre><tt>map<span style="color: #990000">.</span>resources <span style="color: #990000">:</span>photos<span style="color: #990000">,</span> <span style="color: #990000">:</span>except <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>destroy
+</tt></pre></div></div>
+<div class="para"><p>In this case, all of the normal routes except the route for <tt>destroy</tt> (a <tt>DELETE</tt> request to <tt>/photos/<em>id</em></tt>) will be generated.</p></div>
+<div class="para"><p>In addition to an action or a list of actions, you can also supply the special symbols <tt>:all</tt> or <tt>:none</tt> to the <tt>:only</tt> and <tt>:accept</tt> options.</p></div>
+<div class="admonitionblock">
+<table><tr>
+<td class="icon">
+<img src="./images/icons/tip.png" alt="Tip" />
+</td>
+<td class="content">If your application has many RESTful routes, using <tt>:only</tt> and <tt>:accept</tt> to generate only the routes that you actually need can cut down on memory use and speed up the routing process.</td>
+</tr></table>
+</div>
<h3 id="_nested_resources">3.8. Nested Resources</h3>
<div class="para"><p>It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:</p></div>
<div class="listingblock">
diff --git a/railties/doc/guides/source/2_2_release_notes.txt b/railties/doc/guides/source/2_2_release_notes.txt
index c730f72748..f78c179ba1 100644
--- a/railties/doc/guides/source/2_2_release_notes.txt
+++ b/railties/doc/guides/source/2_2_release_notes.txt
@@ -209,7 +209,7 @@ Active Record association proxies now respect the scope of methods on the proxie
== Action Controller
-On the controller side, there are a couple of changes that will help tidy up your routes.
+On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications.
=== Shallow Route Nesting
@@ -250,7 +250,17 @@ map.resources :photos, :collection => { :search => [:get, :post] }
* Lead Contributor: link:http://brennandunn.com/[Brennan Dunn]
-Action Controller now offers good support for HTTP conditional GET requests, as well as some other additions.
+=== Resources With Specific Actions
+
+By default, when you use +map.resources+ to create a route, Rails generates routes for seven default actions (index, show, create, new, edit, update, and destroy). But each of these routes takes up memory in your application, and causes Rails to generate additional routing logic. Now you can use the +:only+ and +:except+ options to fine-tune the routes that Rails will generate for resources. You can supply a single action, an array of actions, or the special +:all+ or +:none+ options. These options are inherited by nested resources.
+
+[source, ruby]
+-------------------------------------------------------
+map.resources :photos, :only => [:index, :show]
+map.resources :products, :except => :destroy
+-------------------------------------------------------
+
+* Lead Contributor: link:http://experthuman.com/[Tom Stuart]
=== Other Action Controller Changes
diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt
index 29be2182ce..fd6eb86b0b 100644
--- a/railties/doc/guides/source/activerecord_validations_callbacks.txt
+++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt
@@ -369,6 +369,36 @@ class Account < ActiveRecord::Base
end
------------------------------------------------------------------
+== Writing your own validation methods
+
+When the built-in validation helpers are not enough for your needs, you can write your own validation methods, by implementing one or more of the +validate+, +validate_on_create+ or +validate_on_update+ methods. As the names of the methods states, the right method to implement depends on when you want the validations to be ran. The meaning of valid is still the same: to make an object invalid you just need to add a message to it's +errors+ collection.
+
+[source, ruby]
+------------------------------------------------------------------
+class Invoice < ActiveRecord::Base
+ def validate_on_create
+ errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
+ end
+end
+------------------------------------------------------------------
+
+If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of +validate+, +validate_on_create+ or +validate_on_update+ methods, passing it the symbols for the methods' names.
+
+[source, ruby]
+------------------------------------------------------------------
+class Invoice < ActiveRecord::Base
+ validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value
+
+ def expiration_date_cannot_be_in_the_past
+ errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
+ end
+
+ def discount_cannot_be_greater_than_total_value
+ errors.add(:discount, "can't be greater than total value") unless discount <= total_value
+ end
+end
+------------------------------------------------------------------
+
== Changelog
http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks
diff --git a/railties/doc/guides/source/command_line.txt b/railties/doc/guides/source/command_line.txt
new file mode 100644
index 0000000000..5f7c6ceff5
--- /dev/null
+++ b/railties/doc/guides/source/command_line.txt
@@ -0,0 +1,147 @@
+A Guide to The Rails Command Line
+=================================
+
+Rails comes with every command line tool you'll need to
+
+* Create a Rails application
+* Generate models, controllers, database migrations, and unit tests
+* Start a development server
+* Mess with objects through an interactive shell
+* Profile and benchmark your new creation
+
+... and much, much more! (Buy now!)
+
+This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide.
+
+== Command Line Basics ==
+
+There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:
+
+* console
+* server
+* rake
+* generate
+* rails
+
+Let's create a simple Rails application to step through each of these commands in context.
+
+=== rails ===
+
+The first thing we'll want to do is create a new Rails application by running the `rails` command after installing Rails.
+
+NOTE: You know you need the rails gem installed by typing `gem install rails` first, right? Okay, okay, just making sure.
+
+[source,shell]
+------------------------------------------------------
+$ rails commandsapp
+
+ create
+ create app/controllers
+ create app/helpers
+ create app/models
+ ...
+ ...
+ create log/production.log
+ create log/development.log
+ create log/test.log
+------------------------------------------------------
+
+Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.
+
+NOTE: This output will seem very familiar when we get to the `generate` command. Creepy foreshadowing!
+
+=== server ===
+
+Let's try it! The `server` command launches a small web server written in Ruby named WEBrick which was also installed when you installed Rails. You'll use this any time you want to view your work through a web browser.
+
+NOTE: WEBrick isn't your only option for serving Rails. We'll get to that in a later section. [XXX: which section]
+
+Here we'll flex our `server` command, which without any prodding of any kind will run our new shiny Rails app:
+
+[source,shell]
+------------------------------------------------------
+$ cd commandsapp
+$ ./script/server
+=> Booting WEBrick...
+=> Rails 2.2.0 application started on http://0.0.0.0:3000
+=> Ctrl-C to shutdown server; call with --help for options
+[2008-11-04 10:11:38] INFO WEBrick 1.3.1
+[2008-11-04 10:11:38] INFO ruby 1.8.5 (2006-12-04) [i486-linux]
+[2008-11-04 10:11:38] INFO WEBrick::HTTPServer#start: pid=18994 port=3000
+------------------------------------------------------
+
+WHOA. With just three commands we whipped up a Rails server listening on port 3000. Go! Go right now to your browser and go to http://localhost:3000. I'll wait.
+
+See? Cool! It doesn't do much yet, but we'll change that.
+
+=== generate ===
+
+The `generate` command uses templates to create a whole lot of things. You can always find out what's available by running `generate` by itself. Let's do that:
+
+[source,shell]
+------------------------------------------------------
+$ ./script/generate
+Usage: ./script/generate generator [options] [args]
+
+...
+...
+
+Installed Generators
+ Builtin: controller, integration_test, mailer, migration, model, observer, performance_test, plugin, resource, scaffold, session_migration
+
+...
+...
+------------------------------------------------------
+
+NOTE: You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
+
+Using generators will save you a large amount of time by writing *boilerplate code* for you -- necessary for the darn thing to work, but not necessary for you to spend time writing. That's what we have computers for, right?
+
+Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
+
+NOTE: All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can just try the command without any parameters (like `rails` or `./script/generate`). For others, you can try adding `--help` or `-h` to the end, as in `./script/server --help`.
+
+[source,shell]
+------------------------------------------------------
+$ ./script/generate controller
+Usage: ./script/generate controller ControllerName [options]
+
+...
+...
+
+Example:
+ `./script/generate controller CreditCard open debit credit close`
+
+ Credit card controller with URLs like /credit_card/debit.
+ Controller: app/controllers/credit_card_controller.rb
+ Views: app/views/credit_card/debit.html.erb [...]
+ Helper: app/helpers/credit_card_helper.rb
+ Test: test/functional/credit_card_controller_test.rb
+
+Modules Example:
+ `./script/generate controller 'admin/credit_card' suspend late_fee`
+
+ Credit card admin controller with URLs /admin/credit_card/suspend.
+ Controller: app/controllers/admin/credit_card_controller.rb
+ Views: app/views/admin/credit_card/debit.html.erb [...]
+ Helper: app/helpers/admin/credit_card_helper.rb
+ Test: test/functional/admin/credit_card_controller_test.rb
+------------------------------------------------------
+
+Ah, the controller generator is expecting parameters in the form of `generate controller ControllerName action1 action2`. Let's make a `Greetings` controller with an action of *hello*, which will say something nice to us.
+
+[source,shell]
+------------------------------------------------------
+$ ./script/generate controller Greeting hello
+ exists app/controllers/
+ exists app/helpers/
+ create app/views/greeting
+ exists test/functional/
+ create app/controllers/greetings_controller.rb
+ create test/functional/greetings_controller_test.rb
+ create app/helpers/greetings_helper.rb
+ create app/views/greetings/hello.html.erb
+------------------------------------------------------
+
+Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. All from one command!
+
diff --git a/railties/doc/guides/source/routing_outside_in.txt b/railties/doc/guides/source/routing_outside_in.txt
index a9ebb7bc36..0f6cd358e2 100644
--- a/railties/doc/guides/source/routing_outside_in.txt
+++ b/railties/doc/guides/source/routing_outside_in.txt
@@ -229,6 +229,8 @@ Although the conventions of RESTful routing are likely to be sufficient for many
* +:path_names+
* +:path_prefix+
* +:name_prefix+
+* +:only+
+* +:except+
You can also add additional routes via the +:member+ and +:collection+ options, which are discussed later in this guide.
@@ -400,6 +402,30 @@ This combination will give you route helpers such as +photographer_photos_path+
NOTE: You can also use +:name_prefix+ with non-RESTful routes.
+==== Using :only and :except
+
+By default, Rails creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the +:only+ and +:except+ options to fine-tune this behavior. The +:only+ option specifies that only certain routes should be generated:
+
+[source, ruby]
+-------------------------------------------------------
+map.resources :photos, :only => [:index, :show]
+-------------------------------------------------------
+
+With this declaration, a +GET+ request to +/photos+ would succeed, but a +POST+ request to +/photos+ (which would ordinarily be routed to the create action) will fail.
+
+The +:except+ option specifies a route or list of routes that should _not_ be generated:
+
+[source, ruby]
+-------------------------------------------------------
+map.resources :photos, :except => :destroy
+-------------------------------------------------------
+
+In this case, all of the normal routes except the route for +destroy+ (a +DELETE+ request to +/photos/_id_+) will be generated.
+
+In addition to an action or a list of actions, you can also supply the special symbols +:all+ or +:none+ to the +:only+ and +:except+ options.
+
+TIP: If your application has many RESTful routes, using +:only+ and +:accept+ to generate only the routes that you actually need can cut down on memory use and speed up the routing process.
+
=== Nested Resources
It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:
diff --git a/railties/doc/guides/source/testing_rails_applications.txt b/railties/doc/guides/source/testing_rails_applications.txt
index 31b6fc2cfa..6cced2fdd1 100644
--- a/railties/doc/guides/source/testing_rails_applications.txt
+++ b/railties/doc/guides/source/testing_rails_applications.txt
@@ -11,18 +11,17 @@ This guide won't teach you to write a Rails application; it assumes basic famili
== Why Write Tests for your Rails Applications? ==
- * Because Ruby code that you write in your Rails application is interpreted, you may only find that it's broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code in advance and catching syntactical and logic errors.
- * Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
- * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
* Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.
+ * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
+ * Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
-== Before you Start Writing Tests ==
+== Introduction to Testing ==
-Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
+Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
=== The 3 Environments ===
-Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. One of the consequences of this design decision is that every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
+Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
One place you'll find this distinction is in the +config/database.yml+ file. This YAML configuration file has 3 different sections defining 3 unique database setups:
@@ -55,11 +54,11 @@ For good tests, you'll need to give some thought to setting up test data. In Rai
==== What Are Fixtures? ====
-_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*.
+_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*. In this guide we will use *YAML* which is the preferred format.
You'll find fixtures under your +test/fixtures+ directory. When you run +script/generate model+ to create a new model, fixture stubs will be automatically created and placed in this directory.
-==== YAML the Camel is a Mammal with Enamel ====
+==== YAML ====
YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the *.yml* file extension (as in +users.yml+).
@@ -69,13 +68,11 @@ Here's a sample YAML fixture file:
---------------------------------------------
# low & behold! I am a YAML comment!
david:
- id: 1
name: David Heinemeier Hansson
birthday: 1979-10-15
profession: Systems development
steve:
- id: 2
name: Steve Ross Kellock
birthday: 1974-09-27
profession: guy with keyboard
@@ -83,55 +80,24 @@ steve:
Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column.
-==== Comma Seperated ====
-
-Fixtures can also be described using the all-too-familiar comma-separated value (CSV) file format. These files, just like YAML fixtures, are placed in the 'test/fixtures' directory, but these end with the +.csv+ file extension (as in +celebrity_holiday_figures.csv+).
-
-A CSV fixture looks like this:
-
---------------------------------------------------------------
-id, username, password, stretchable, comments
-1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!""
-2, ebunny, ihateeggs, true, Hoppity hop y'all
-3, tfairy, ilovecavities, true, "Pull your teeth, I will"
---------------------------------------------------------------
-
-The first line is the header. It is a comma-separated list of fields. The rest of the file is the payload: 1 record per line. A few notes about this format:
-
- * Leading and trailing spaces are trimmed from each value when it is imported
- * If you use a comma as data, the cell must be encased in quotes
- * If you use a quote as data, you must escape it with a 2nd quote
- * Don't use blank lines
- * Nulls can be defined by including no data between a pair of commas
-
-Unlike the YAML format where you give each record in a fixture a name, CSV fixture names are automatically generated. They follow a pattern of "model-name-counter". In the above example, you would have:
-
-* +celebrity-holiday-figures-1+
-* +celebrity-holiday-figures-2+
-* +celebrity-holiday-figures-3+
-
-The CSV format is great to use if you have existing data in a spreadsheet or database and you are able to save it (or export it) as a CSV.
-
==== ERb'in It Up ====
ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data.
-I'll demonstrate with a YAML file:
-
[source, ruby]
--------------------------------------------------------------
<% earth_size = 20 -%>
mercury:
- id: 1
size: <%= earth_size / 50 %>
+ brightest_on: <%= 113.days.ago.to_s(:db) %>
venus:
- id: 2
size: <%= earth_size / 2 %>
+ brightest_on: <%= 67.days.ago.to_s(:db) %>
mars:
- id: 3
size: <%= earth_size - 69 %>
+ brightest_on: <%= 13.days.from_now.to_s(:db) %>
--------------------------------------------------------------
Anything encased within the
@@ -141,7 +107,7 @@ Anything encased within the
<% %>
------------------------
-tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively.
+tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The +brightest_on+ attribute will also be evaluated and formatted by Rails to be compatible with the database.
==== Fixtures in Action ====
@@ -164,9 +130,7 @@ users(:david)
users(:david).id
--------------------------------------------------------------
-But, by there's another side to fixtures... at night, if the moon is full and the wind completely still, fixtures can also transform themselves into the form of the original class!
-
-Now you can get at the methods only available to that class.
+Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class.
[source, ruby]
--------------------------------------------------------------
@@ -177,14 +141,18 @@ david = users(:david).find
email(david.girlfriend.email, david.location_tonight)
--------------------------------------------------------------
-== Unit Testing Your Models ==
+== Unit Testing your Models ==
In Rails, unit tests are what you write to test your models.
-When you create a model using +script/generate+, among other things it creates a test stub in the +test/unit+ folder, as well as a fixture for the model:
+For this guide we will be using Rails _scaffolding_. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practises. I will be using examples from this generated code and would be supplementing it with additional examples where necessary.
+
+NOTE: For more information on Rails _scaffolding_, refer to link:../getting_started_with_rails.html[Getting Started with Rails]
+
+When you use +script/generate scaffold+, for a resource among other things it creates a test stub in the +test/unit+ folder:
-------------------------------------------------------
-$ script/generate model Post
+$ script/generate scaffold post title:string body:text
...
create app/models/post.rb
create test/unit/post_test.rb
@@ -243,6 +211,36 @@ This line of code is called an _assertion_. An assertion is a line of code that
Every test contains one or more assertions. Only when all the assertions are successful the test passes.
+=== Preparing you Application for Testing ===
+
+Before you can run your tests you need to ensure that the test database structure is current. For this you can use the following rake commands:
+
+[source, shell]
+-------------------------------------------------------
+$ rake db:migrate
+...
+$ rake db:test:load
+-------------------------------------------------------
+
+Above +rake db:migrate+ runs any pending migrations on the _developemnt_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run +db:test:prepare+ as it first checks for pending migrations and warns you appropriately.
+
+NOTE: +db:test:prepare+ will fail with an error if db/schema.rb doesn't exists.
+
+==== Rake Tasks for Preparing you Application for Testing ==
+
+[grid="all"]
+--------------------------------`----------------------------------------------------
+Tasks Description
+------------------------------------------------------------------------------------
++rake db:test:clone+ Recreate the test database from the current environment's database schema
++rake db:test:clone_structure+ Recreate the test databases from the development structure
++rake db:test:load+ Recreate the test database from the current +schema.rb+
++rake db:test:prepare+ Check for pending migrations and load the test schema
++rake db:test:purge+ Empty the test database.
+------------------------------------------------------------------------------------
+
+TIP: You can see all these rake tasks and their descriptions by running +rake --tasks --describe+
+
=== Running Tests ===
Running a test is as simple as invoking the file containing the test cases through Ruby:
@@ -277,65 +275,90 @@ Finished in 0.023513 seconds.
The +.+ (dot) above indicates a passing test. When a test fails you see an +F+; when a test throws an error you see an +E+ in its place. The last line of the output is the summary.
-To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case:
+To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case.
[source,ruby]
--------------------------------------------------
-def test_should_have_atleast_one_post
- post = Post.find(:first)
- assert_not_nil post
+def test_should_not_save_post_without_title
+ post = Post.new
+ assert !post.save
end
--------------------------------------------------
-If you haven't added any data to the test fixture for posts, this test will fail. You can see this by running it:
+Let us run this newly added test.
-------------------------------------------------------
-$ ruby unit/post_test.rb
+$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
-F.
-Finished in 0.027274 seconds.
+F
+Finished in 0.197094 seconds.
1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:12:in `test_should_have_atleast_one_post'
+test_should_not_save_post_without_title(PostTest)
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-<nil> expected to not be nil.
+<false> is not true.
-2 tests, 2 assertions, 1 failures, 0 errors
+1 tests, 1 assertions, 1 failures, 0 errors
-------------------------------------------------------
In the output, +F+ denotes a failure. You can see the corresponding trace shown under +1)+ along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here:
[source,ruby]
--------------------------------------------------
-def test_should_have_atleast_one_post
- post = Post.find(:first)
- assert_not_nil post, "Should not be nil as Posts table should have atleast one post"
+def test_should_not_save_post_without_title
+ post = Post.new
+ assert !post.save, "Saved the post without a title"
end
--------------------------------------------------
Running this test shows the friendlier assertion message:
-------------------------------------------------------
-$ ruby unit/post_test.rb
+$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
-F.
-Finished in 0.024727 seconds.
+F
+Finished in 0.198093 seconds.
1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
+test_should_not_save_post_without_title(PostTest)
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-Should not be nil as Posts table should have atleast one post.
-<nil> expected to not be nil.
+Saved the post without a title.
+<false> is not true.
+
+1 tests, 1 assertions, 1 failures, 0 errors
+-------------------------------------------------------
+
+Now to get this test to pass we can add a model level validation for the _title_ field.
+
+[source,ruby]
+--------------------------------------------------
+class Post < ActiveRecord::Base
+ validates_presence_of :title
+end
+--------------------------------------------------
+
+Now the test should pass. Let us verify by running the test again:
+
+-------------------------------------------------------
+$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
+Loaded suite unit/post_test
+Started
+.
+Finished in 0.193608 seconds.
-2 tests, 2 assertions, 1 failures, 0 errors
+1 tests, 1 assertions, 0 failures, 0 errors
-------------------------------------------------------
+Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD).
+
+TIP: Many Rails developers practice _Test-Driven Development_ (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with link:http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html[15 TDD steps to create a Rails application].
+
To see how an error gets reported, here's a test containing an error:
[source,ruby]
@@ -350,29 +373,21 @@ end
Now you can see even more output in the console from running the tests:
-------------------------------------------------------
-$ ruby unit/post_test.rb
+$ ruby unit/post_test.rb -n test_should_report_error
Loaded suite unit/post_test
Started
-FE.
-Finished in 0.108389 seconds.
-
- 1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-Should not be nil as Posts table should have atleast one post.
-<nil> expected to not be nil.
+E
+Finished in 0.195757 seconds.
- 2) Error:
+ 1) Error:
test_should_report_error(PostTest):
-NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x304a7b0>
+NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x2cc9de8>
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing'
- unit/post_test.rb:15:in `test_should_report_error'
+ unit/post_test.rb:16:in `test_should_report_error'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'
-3 tests, 2 assertions, 1 failures, 1 errors
+1 tests, 0 assertions, 0 failures, 1 errors
-------------------------------------------------------
Notice the 'E' in the output. It denotes a test with error.
@@ -383,8 +398,6 @@ NOTE: The execution of each test method stops as soon as any error or a assertio
Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.
-TIP: Many Rails developers practice _test-driven development_ (TDD), in which the tests are written _before_ the code that they are testing. This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with link:http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html[15 TDD steps to create a Rails application].
-
=== Assertions Available ===
By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.
@@ -454,32 +467,9 @@ You should test for things such as:
* was the correct object stored in the response template?
* was the appropriate message displayed to the user in the view
-When you use +script/generate+ to create a controller, it automatically creates a functional test for that controller in +test/functional+. For example, if you create a post controller:
-
-[source, shell]
--------------------------------------------------------
-$ script/generate controller post
-...
- create app/controllers/post_controller.rb
- create test/functional/post_controller_test.rb
-...
--------------------------------------------------------
-
-Now if you take a look at the file +posts_controller_test.rb+ in the +test/functional+ directory, you should see:
-
-[source,ruby]
---------------------------------------------------
-require 'test_helper'
-
-class PostsControllerTest < ActionController::TestCase
- # Replace this with your real tests.
- def test_truth
- assert true
- end
-end
---------------------------------------------------
+Now that we have used Rails scaffold generator for our +Post+ resource, it has already created the controller code and functional tests. You can take look at the file +posts_controller_test.rb+ in the +test/functional+ directory.
-Of course, you need to replace the simple assertion with real testing. Here's a starting example of a functional test:
+Let me take you through one such test, +test_should_get_index+ from the file +posts_controller_test.rb+.
[source,ruby]
--------------------------------------------------
@@ -513,6 +503,23 @@ Another example: Calling the +:view+ action, passing an +id+ of 12 as the +param
get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
--------------------------------------------------
+NOTE: If you try running +test_should_create_post+ test from +posts_controller_test.rb+ it will fail on account of the newly added model level validation and rightly so.
+
+Let us modify +test_should_create_post+ test in +posts_controller_test.rb+ so that all our test pass:
+
+[source,ruby]
+--------------------------------------------------
+def test_should_create_post
+ assert_difference('Post.count') do
+ post :create, :post => { :title => 'Some title'}
+ end
+
+ assert_redirected_to post_path(assigns(:post))
+end
+--------------------------------------------------
+
+Now you can try running all the tests and they should pass.
+
=== Available Request Types for Functional Tests ===
If you're familiar with the HTTP protocol, you'll know that +get+ is a type of request. There are 5 request types supported in Rails functional tests:
@@ -756,6 +763,130 @@ class UserFlowsTest < ActionController::IntegrationTest
end
--------------------------------------------------
+== Rake Tasks for Running your Tests ==
+
+You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
+
+[grid="all"]
+--------------------------------`----------------------------------------------------
+Tasks Description
+------------------------------------------------------------------------------------
++rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
++rake test:units+ Runs all the unit tests from +test/unit+
++rake test:functionals+ Runs all the functional tests from +test/functional+
++rake test:integration+ Runs all the integration tests from +test/integration+
++rake test:recent+ Tests recent changes
++rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
++rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
+------------------------------------------------------------------------------------
+
+
+== Brief Note About Test::Unit ==
+
+Ruby ships with a boat load of libraries. One little gem of a library is +Test::Unit+, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in +Test::Unit::Assertions+. The class +ActiveSupport::TestCase+ which we have been using in our unit and functional tests extends +Test::Unit::TestCase+ that it is how we can use all the basic assertions in our tests.
+
+NOTE: For more information on +Test::Unit+, refer to link:http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/[test/unit Documentation]
+
+== Setup and Teardown ==
+
+If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in +Posts+ controller:
+
+[source,ruby]
+--------------------------------------------------
+require 'test_helper'
+
+class PostsControllerTest < ActionController::TestCase
+
+ # called before every single test
+ def setup
+ @post = posts(:one)
+ end
+
+ # called after every single test
+ def teardown
+ # as we are re-initializing @post before every test
+ # setting it to nil here is not essential but I hope
+ # you understand how you can use the teardown method
+ @post = nil
+ end
+
+ def test_should_show_post
+ get :show, :id => @post.id
+ assert_response :success
+ end
+
+ def test_should_destroy_post
+ assert_difference('Post.count', -1) do
+ delete :destroy, :id => @post.id
+ end
+
+ assert_redirected_to posts_path
+ end
+
+end
+--------------------------------------------------
+
+Above, the +setup+ method is called before each test and so +@post+ is available for each of the tests. Rails implements +setup+ and +teardown+ as ActiveSupport::Callbacks. Which essentially means you need not only use +setup+ and +teardown+ as methods in your tests. You could specify them by using:
+
+ * a block
+ * a method (like in the earlier example)
+ * a method name as a symbol
+ * a lambda
+
+Let's see the earlier example by specifying +setup+ callback by specifying a method name as a symbol:
+
+[source,ruby]
+--------------------------------------------------
+require '../test_helper'
+
+class PostsControllerTest < ActionController::TestCase
+
+ # called before every single test
+ setup :initialize_post
+
+ # called after every single test
+ def teardown
+ @post = nil
+ end
+
+ def test_should_show_post
+ get :show, :id => @post.id
+ assert_response :success
+ end
+
+ def test_should_update_post
+ put :update, :id => @post.id, :post => { }
+ assert_redirected_to post_path(assigns(:post))
+ end
+
+ def test_should_destroy_post
+ assert_difference('Post.count', -1) do
+ delete :destroy, :id => @post.id
+ end
+
+ assert_redirected_to posts_path
+ end
+
+ private
+
+ def initialize_post
+ @post = posts(:one)
+ end
+
+end
+--------------------------------------------------
+
+== Testing Routes ==
+
+Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default +show+ action of +Posts+ controller above should look like:
+
+[source,ruby]
+--------------------------------------------------
+def test_should_route_to_post
+ assert_routing '/posts/1', { :controller => "posts", :action => "show", :id => "1" }
+end
+--------------------------------------------------
+
== Testing Your Mailers ==
Testing mailer classes requires some specific tools to do a thorough job.
@@ -845,30 +976,6 @@ class UserControllerTest < ActionController::TestCase
end
----------------------------------------------------------------
-== Rake Tasks for Testing
-
-You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
-
-[grid="all"]
---------------------------------`----------------------------------------------------
-Tasks Description
-------------------------------------------------------------------------------------
-+rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
-+rake test:units+ Runs all the unit tests from +test/unit+
-+rake test:functionals+ Runs all the functional tests from +test/functional+
-+rake test:integration+ Runs all the integration tests from +test/integration+
-+rake test:recent+ Tests recent changes
-+rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
-+rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
-+rake db:test:clone+ Recreate the test database from the current environment's database schema
-+rake db:test:clone_structure+ Recreate the test databases from the development structure
-+rake db:test:load+ Recreate the test database from the current +schema.rb+
-+rake db:test:prepare+ Check for pending migrations and load the test schema
-+rake db:test:purge+ Empty the test database.
-------------------------------------------------------------------------------------
-
-TIP: You can see all these rake task and their descriptions by running +rake --tasks --describe+
-
== Other Testing Approaches
The built-in +test/unit+ based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:
@@ -882,6 +989,7 @@ The built-in +test/unit+ based testing is not the only way to test Rails applica
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8[Lighthouse ticket]
+* November 13, 2008: Revised based on feedback from Pratik Naik by link:../authors.html#asurve[Akshay Surve] (not yet approved for publication)
* October 14, 2008: Edit and formatting pass by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
-* October 12, 2008: First draft by link:../authors.html#asurve[Akashay Surve] (not yet approved for publication)
+* October 12, 2008: First draft by link:../authors.html#asurve[Akshay Surve] (not yet approved for publication)