diff options
Diffstat (limited to 'railties')
-rw-r--r-- | railties/guides/source/3_0_release_notes.textile | 2 | ||||
-rw-r--r-- | railties/guides/source/active_support_core_extensions.textile | 4 | ||||
-rw-r--r-- | railties/guides/source/activerecord_validations_callbacks.textile | 104 | ||||
-rw-r--r-- | railties/guides/source/caching_with_rails.textile | 2 | ||||
-rw-r--r-- | railties/guides/source/command_line.textile | 2 | ||||
-rw-r--r-- | railties/guides/source/contribute.textile | 54 | ||||
-rw-r--r-- | railties/guides/source/debugging_rails_applications.textile | 2 | ||||
-rw-r--r-- | railties/guides/source/form_helpers.textile | 4 | ||||
-rw-r--r-- | railties/guides/source/getting_started.textile | 6 | ||||
-rw-r--r-- | railties/guides/source/i18n.textile | 4 | ||||
-rw-r--r-- | railties/guides/source/performance_testing.textile | 3 | ||||
-rw-r--r-- | railties/guides/source/routing.textile | 12 | ||||
-rw-r--r-- | railties/guides/source/security.textile | 2 | ||||
-rw-r--r-- | railties/guides/source/testing.textile | 39 |
14 files changed, 145 insertions, 95 deletions
diff --git a/railties/guides/source/3_0_release_notes.textile b/railties/guides/source/3_0_release_notes.textile index 4b66baae1c..b7f4fbf35c 100644 --- a/railties/guides/source/3_0_release_notes.textile +++ b/railties/guides/source/3_0_release_notes.textile @@ -36,6 +36,8 @@ h4. Rails 3 requires Ruby 1.8.7+ Rails 3.0 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.0 is also compatible with Ruby 1.9.2. +TIP: Note that Ruby 1.8.7 p248 and p249 has marshaling bugs that crash Rails 3.0.0. Ruby 1.9.1 outright segfaults on Rails 3.0.0, so if you want to use Rails 3 with 1.9.x, jump on 1.9.2 trunk for smooth sailing. + h4. Rails Application object As part of the groundwork for supporting running multiple Rails applications in the same process, Rails 3 introduces the concept of an Application object. An application object holds all the application specific configurations and is very similar in nature to +config/environment.rb+ from the previous versions of Rails. diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index fed0c25e8e..08fddd2926 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -1894,10 +1894,10 @@ Similarly, +from+ returns the tail from the element at the passed index on: The methods +second+, +third+, +fourth+, and +fifth+ return the corresponding element (+first+ is builtin). Thanks to social wisdom and positive constructiveness all around, +forty_two+ is also available. -You can pick a random element with +rand+: +You can pick a random element with +random_element+: <ruby> -shape_type = [Circle, Square, Triangle].rand +shape_type = [Circle, Square, Triangle].random_element </ruby> NOTE: Defined in +active_support/core_ext/array/access.rb+. diff --git a/railties/guides/source/activerecord_validations_callbacks.textile b/railties/guides/source/activerecord_validations_callbacks.textile index 97915d5d55..ee30f3963b 100644 --- a/railties/guides/source/activerecord_validations_callbacks.textile +++ b/railties/guides/source/activerecord_validations_callbacks.textile @@ -139,17 +139,19 @@ end +invalid?+ is simply the inverse of +valid?+. +invalid?+ triggers your validations and returns true if any errors were added to the object, and false otherwise. -h4. +errors.invalid?+ +h4. +errors[]+ -To verify whether or not a particular attribute of an object is valid, you can use the +errors.invalid?+ method. This method is only useful _after_ validations have been run, because it only inspects the errors collection and does not trigger validations itself. It's different from the +ActiveRecord::Base#invalid?+ method explained above because it doesn't verify the validity of the object as a whole. It only checks to see whether there are errors found on an individual attribute of the object. +To verify whether or not a particular attribute of an object is valid, you can use +errors[:attribute]+ that returns an array with all attribute errors, when there are no errors on the specified attribute, an empty array is returned. + +This method is only useful _after_ validations have been run, because it only inspects the errors collection and does not trigger validations itself. It's different from the +ActiveRecord::Base#invalid?+ method explained above because it doesn't verify the validity of the object as a whole. It only checks to see whether there are errors found on an individual attribute of the object. <ruby> class Person < ActiveRecord::Base validates_presence_of :name end ->> Person.new.errors.invalid?(:name) # => false ->> Person.create.errors.invalid?(:name) # => true +>> Person.new.errors[:name].any? # => false +>> Person.create.errors[:name].any? # => true </ruby> We'll cover validation errors in greater depth in the "Working with Validation Errors":#working-with-validation-errors section. For now, let's turn to the built-in validation helpers that Rails provides by default. @@ -595,21 +597,53 @@ In addition to the +valid?+ and +invalid?+ methods covered earlier, Rails provid The following is a list of the most commonly used methods. Please refer to the +ActiveRecord::Errors+ documentation for a list of all the available methods. -h4. +errors.add_to_base+ +h4. +errors+ -The +add_to_base+ method lets you add errors messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. +add_to_base+ simply receives a string and uses this as the error message. +Returns an OrderedHash with all errors. Each key is the attribute name and value is an array of strings with all errors. <ruby> class Person < ActiveRecord::Base - def a_method_used_for_validation_purposes - errors.add_to_base("This person is invalid because ...") - end + validates_presence_of :name + validates_length_of :name, :minimum => 3 +end + +person = Person.new +person.valid? # => false +person.errors + # => {:name => ["can't be blank", "is too short (minimum is 3 characters)"]} + +person = Person.new(:name => "John Doe") +person.valid? # => true +person.errors # => [] +</ruby> + +h4. +errors[]+ + ++errors[]+ is used when you want to check the error messages for a specific attribute. It returns an array of strings with all error messages for the given attribute, each string with one error message. If there are no errors related to the attribute returns an empty array. + +<ruby> +class Person < ActiveRecord::Base + validates_presence_of :name + validates_length_of :name, :minimum => 3 end + +person = Person.new(:name => "John Doe") +person.valid? # => true +person.errors[:name] # => [] + +person = Person.new(:name => "JD") +person.valid? # => false +person.errors[:name] # => ["is too short (minimum is 3 characters)"] + +person = Person.new +person.valid? # => false +person.errors[:name] + # => ["can't be blank", "is too short (minimum is 3 characters)"] </ruby> h4. +errors.add+ -The +add+ method lets you manually add messages that are related to particular attributes. You can use the +full_messages+ method to view the messages in the form they might be displayed to a user. Those particular messages get the attribute name prepended (and capitalized). +add+ receives the name of the attribute you want to add the message to, and the message itself. +The +add+ method lets you manually add messages that are related to particular attributes. You can use the +errors.full_messages+ or +errors.to_a+ methods to view the messages in the form they might be displayed to a user. Those particular messages get the attribute name prepended (and capitalized). +add+ receives the name of the attribute you want to add the message to, and the message itself. <ruby> class Person < ActiveRecord::Base @@ -620,37 +654,44 @@ end person = Person.create(:name => "!@#") -person.errors.on(:name) - # => "cannot contain the characters !@#%*()_-+=" +person.errors[:name] + # => ["cannot contain the characters !@#%*()_-+="] person.errors.full_messages # => ["Name cannot contain the characters !@#%*()_-+="] </ruby> + +Another way to do this is using +[]=+ setter -h4. +errors.on+ +<ruby> + class Person < ActiveRecord::Base + def a_method_used_for_validation_purposes + errors[:name] = "cannot contain the characters !@#%*()_-+=" + end + end -The +on+ method is used when you want to check the error messages for a specific attribute. It returns different kinds of objects depending on the state of the +errors+ collection for the given attribute. If there are no errors related to the attribute +on+ returns +nil+. If there is just one error message for this attribute +on+ returns a string with the message. When +errors+ holds two or more error messages for the attribute, +on+ returns an array of strings, each one with one error message. + person = Person.create(:name => "!@#") + + person.errors[:name] + # => ["cannot contain the characters !@#%*()_-+="] + + person.errors.to_a + # => ["Name cannot contain the characters !@#%*()_-+="] +</ruby> + +h4. +errors[:base]+ + +You can add errors messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since +errors[:base]+ is an array, you can simply add a string to the array and uses it as the error message. <ruby> class Person < ActiveRecord::Base - validates_presence_of :name - validates_length_of :name, :minimum => 3 + def a_method_used_for_validation_purposes + errors[:base] << "This person is invalid because ..." + end end +</ruby> -person = Person.new(:name => "John Doe") -person.valid? # => true -person.errors.on(:name) # => nil -person = Person.new(:name => "JD") -person.valid? # => false -person.errors.on(:name) - # => "is too short (minimum is 3 characters)" - -person = Person.new -person.valid? # => false -person.errors.on(:name) - # => ["can't be blank", "is too short (minimum is 3 characters)"] -</ruby> h4. +errors.clear+ @@ -664,7 +705,7 @@ end person = Person.new person.valid? # => false -person.errors.on(:name) +person.errors[:name] # => ["can't be blank", "is too short (minimum is 3 characters)"] person.errors.clear @@ -672,7 +713,7 @@ person.errors.empty? # => true p.save # => false -p.errors.on(:name) +p.errors[:name] # => ["can't be blank", "is too short (minimum is 3 characters)"] </ruby> @@ -1121,6 +1162,7 @@ h3. Changelog "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks +* May 15, 2010: Validation Errors section updated by "Emili ParreƱo":http://www.eparreno.com * March 7, 2009: Callbacks revision by Trevor Turk * February 10, 2009: Observers revision by Trevor Turk * February 5, 2009: Initial revision by Trevor Turk diff --git a/railties/guides/source/caching_with_rails.textile b/railties/guides/source/caching_with_rails.textile index e27c2a6dc6..6dee4b9c61 100644 --- a/railties/guides/source/caching_with_rails.textile +++ b/railties/guides/source/caching_with_rails.textile @@ -57,7 +57,7 @@ class ProductsController < ActionController end def create - expire_page :action => :list + expire_page :action => :index end end diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile index ab024d7fc3..983c04c3d9 100644 --- a/railties/guides/source/command_line.textile +++ b/railties/guides/source/command_line.textile @@ -31,7 +31,7 @@ h4. +rails+ The first thing we'll want to do is create a new Rails application by running the +rails+ command after installing Rails. -WARNING: You know you need the rails gem installed by typing +gem install rails+ first, if you don't have this installed, follow the instructions in the "Rails 3 Release Notes":/3_0_release_notes.textile +WARNING: You know you need the rails gem installed by typing +gem install rails+ first, if you don't have this installed, follow the instructions in the "Rails 3 Release Notes":/3_0_release_notes.html <shell> $ rails commandsapp diff --git a/railties/guides/source/contribute.textile b/railties/guides/source/contribute.textile index 8c64df5362..66f24e5c7e 100644 --- a/railties/guides/source/contribute.textile +++ b/railties/guides/source/contribute.textile @@ -6,33 +6,36 @@ endprologue. h3. How to Contribute? -* We have an open commit policy: anyone is welcome to contribute, but you'll need to ask for commit access. -* PM lifo at "GitHub":http://github.com asking for "docrails":http://github.com/lifo/docrails/tree/master commit access. -* Guides are written in Textile, and reside at railties/guides/source in the docrails project. +* We have an open commit policy: anyone is welcome to contribute and to review contributions. +* "docrails is hosted on GitHub":http://github.com/lifo/docrails and has public write access. +* Guides are written in Textile, and reside at +railties/guides/source+ in the docrails project. +* Follow the "Rails Guides Conventions":http://wiki.github.com/lifo/docrails/rails-guides-conventions. * Assets are stored in the +railties/guides/assets+ directory. -* Sample format : "Active Record Associations":http://github.com/lifo/docrails/blob/3e56a3832415476fdd1cb963980d0ae390ac1ed3/railties/guides/source/association_basics.textile -* Sample output : "Active Record Associations":association_basics.html +* Sample format : "Active Record Associations":http://github.com/lifo/docrails/blob/3e56a3832415476fdd1cb963980d0ae390ac1ed3/railties/guides/source/association_basics.textile. +* Sample output : "Active Record Associations":association_basics.html. * You can build the Guides during testing by running +rake generate_guides+ in the +railties+ directory. +* Edge guides "can be consulted online":http://edgeguides.rubyonrails.org/. That website is generated periodically from docrails. h3. What to Contribute? * We need authors, editors, proofreaders, and translators. Adding a single paragraph of quality content to a guide is a good way to get started. * The easiest way to start is by improving an existing guide: -** Improve the structure to make it more coherent -** Add missing information -** Correct any factual errors -** Fix typos or improve style -** Bring it up to date with the latest Edge Rails -* We're also open to suggestions for entire new guides -** Contact lifo or mikeg1a in IRC or via "email":mailto:MikeG1@larkfarm.com to get your idea approved -** If you're the main author on a significant guide, you're eligible for the prizes - -h3. How to Commit - -* If you have a small change or typo fix, just ask lifo for commit access and commit it to the project. -* If your change is more significant, post a patch or a message on Lighthouse, and commit after you get a +1 from lifo or mikeg1a. -* If the guide is already marked done, you should get a +1 before pushing your changes. -* Put [#<ticket number>] in your commit message to enable GitHub/Lighthouse integration. +** Improve the structure to make it more coherent. +** Add missing information. +** Correct any factual errors. +** Fix typos or improve style. +** Bring it up to date with the latest Edge Rails. +* We're also open to suggestions for entire new guides: +** Contact lifo or fxn to get your idea approved. See the Contact section below. +** If you're the main author on a significant guide, you're eligible for the prizes. + +h3. How is the process? + +* The preferred way to contribute is to commit to docrails directly. +* A new guide is only edited by its author until finished though. In that case feedback can be given in its LH ticket. +* If you are writing a new guide freely commit to docrails partial work and ping lifo or fxn when done with a first draft. +* Guides reviewers will then provide feedback, some of it possibly in form of direct commits to agilize the process. +* Eventually the guide will be approved and added to the index. h3. Prizes @@ -59,13 +62,8 @@ h3. Mailing List "Ruby on Rails: Documentation":http://groups.google.com/group/rubyonrails-docs is the mailing list for all the guides/documentation related discussions. -h3. IRC Channel - -==#docrails @ irc.freenode.net== - h3. Contact -If you have any questions or need any clarification, feel free to contact: - -* IRC : lifo, mikeg1a or fxn in #docrails -* Email : pratiknaik aT gmail +* IRC : #docrails channel in irc.freenode.net +* Twitter: "@docrails":http://twitter.com/docrails, "@lifo":http://twitter.com/lifo, "@fxn":http://twitter.com/fxn +* Email : pratiknaik aT gmail, fxn aT hashref dot com diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile index 0fb7542995..26aee82ae1 100644 --- a/railties/guides/source/debugging_rails_applications.textile +++ b/railties/guides/source/debugging_rails_applications.textile @@ -680,7 +680,7 @@ h3. Plugins for Debugging There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging: -* "Footnotes":http://github.com/drnic/rails-footnotes/tree/master: Every Rails page has footnotes that give request information and link back to your source via TextMate. +* "Footnotes":http://github.com/josevalim/rails-footnotes: Every Rails page has footnotes that give request information and link back to your source via TextMate. * "Query Trace":http://github.com/ntalbott/query_trace/tree/master: Adds query origin tracing to your logs. * "Query Stats":http://github.com/dan-manges/query_stats/tree/master: A Rails plugin to track database queries. * "Query Reviewer":http://code.google.com/p/query-reviewer/: This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed. diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile index 70b88db3a4..0c0a4e2263 100644 --- a/railties/guides/source/form_helpers.textile +++ b/railties/guides/source/form_helpers.textile @@ -205,7 +205,7 @@ Upon form submission the value entered by the user will be stored in +params[:pe WARNING: You must pass the name of an instance variable, i.e. +:person+ or +"person"+, not an actual instance of your model object. -Rails provides helpers for displaying the validation errors associated with a model object. These are covered in detail by the "Active Record Validations and Callbacks":./activerecord_validations_callbacks.html#_using_the_tt_errors_tt_collection_in_your_view_templates guide. +Rails provides helpers for displaying the validation errors associated with a model object. These are covered in detail by the "Active Record Validations and Callbacks":./activerecord_validations_callbacks.html#displaying-validation-errors-in-the-view guide. h4. Binding a Form to an Object @@ -280,7 +280,7 @@ The Article model is directly available to users of the application, so -- follo map.resources :articles </ruby> -TIP: Declaring a resource has a number of side-affects. See "Rails Routing From the Outside In":routing.html#restful-routing-the-rails-default for more information on setting up and using resources. +TIP: Declaring a resource has a number of side-affects. See "Rails Routing From the Outside In":routing.html#resource-routing-the-rails-default for more information on setting up and using resources. When dealing with RESTful resources, calls to +form_for+ can get significantly easier if you rely on *record identification*. In short, you can just pass the model instance and have Rails figure out model name and the rest: diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index b7301bff20..dd4e94a9e1 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -1489,10 +1489,10 @@ h3. Changelog * May 16, 2010: Added a section on configuration gotchas to address common encoding problems that people might have * April 30, 2010: Fixes, editing and updating of code samples by "Rohit Arondekar":http://rohitarondekar.com -* April 25, 2010: Couple of more minor fixups "Mikel Lindsaar":credits:html#raasdnil +* April 25, 2010: Couple of more minor fixups "Mikel Lindsaar":credits.html#raasdnil * April 1, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com -* February 8, 2010: Full re-write for Rails 3.0-beta, added helpers and before_filters, refactored code by "Mikel Lindsaar":credits:html#raasdnil -* January 24, 2010: Re-write for Rails 3.0 by "Mikel Lindsaar":credits:html#raasdnil +* February 8, 2010: Full re-write for Rails 3.0-beta, added helpers and before_filters, refactored code by "Mikel Lindsaar":credits.html#raasdnil +* January 24, 2010: Re-write for Rails 3.0 by "Mikel Lindsaar":credits.html#raasdnil * July 18, 2009: Minor cleanup in anticipation of Rails 2.3.3 by "Mike Gunderloy":credits.html#mgunderloy * February 1, 2009: Updated for Rails 2.3 by "Mike Gunderloy":credits.html#mgunderloy * November 3, 2008: Formatting patch from Dave Rothlisberger diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile index bb383d3cf9..b09bb470ee 100644 --- a/railties/guides/source/i18n.textile +++ b/railties/guides/source/i18n.textile @@ -540,7 +540,7 @@ If a translation uses +:default+ or +:scope+ as an interpolation variable, an I+ h4. Pluralization -In English there are only one singular and one plural form for a given string, e.g. "1 message" and "2 messages". Other languages ("Arabic":http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ar, "Japanese":http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ja, "Russian":http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ru and many more) have different grammars that have additional or fewer "plural forms":http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html. Thus, the I18n API provides a flexible pluralization feature. +In English there are only one singular and one plural form for a given string, e.g. "1 message" and "2 messages". Other languages ("Arabic":http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ar, "Japanese":http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ja, "Russian":http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ru and many more) have different grammars that have additional or fewer "plural forms":http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html. Thus, the I18n API provides a flexible pluralization feature. The +:count+ interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR: @@ -769,7 +769,7 @@ h5. Action View Helper Methods h5. Active Record Methods -* +human_name+ and +human_attribute_name+ use translations for model names and attribute names if available in the "activerecord.models":http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L43 scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes". +* +human_name+ and +human_attribute_name+ use translations for model names and attribute names if available in the "activerecord.models":http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L29 scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes". * +ActiveRecord::Errors#generate_message+ (which is used by Active Record validations but may also be used manually) uses +human_name+ and +human_attribute_name+ (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes". diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile index c02fabc0b2..65f8d07e7a 100644 --- a/railties/guides/source/performance_testing.textile +++ b/railties/guides/source/performance_testing.textile @@ -517,10 +517,9 @@ h4. Tutorials and Documentation h3. Commercial Products -Rails has been lucky to have three startups dedicated to Rails specific performance tools: +Rails has been lucky to have two startups dedicated to Rails specific performance tools: * "New Relic":http://www.newrelic.com -* "Fiveruns":http://www.fiveruns.com * "Scout":http://scoutapp.com h3. Changelog diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index 7ac5bc8d3a..2bc1736137 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -119,6 +119,12 @@ h4. Singular Resources Sometimes, you have a resource that clients always look up without referencing an ID. A common example, +/profile+ always shows the profile of the currently logged in user. In this case, you can use a singular resource to map +/profile+ (rather than +/profile/:id+) to the +show+ action. <ruby> +match "profile" => "users#show" +</ruby> + +This resourceful route + +<ruby> resource :geocoder </ruby> @@ -391,7 +397,7 @@ h4. The Query String The +params+ will also include any parameters from the query string. For example, with this route: <ruby> -match ':controller/:action/:id +match ':controller/:action/:id' </ruby> An incoming URL of +/photos/show/1?user_id=2+ will be dispatched to the +show+ action of the +Photos+ controller. +params+ will be <tt>{ :controller => "photos", :action => "show", :id => "1", :user_id => "2" }</tt>. @@ -419,7 +425,7 @@ h4. Naming Routes You can specify a name for any route using the +:as+ option. <ruby> -match 'logout' => 'sessions#destroy', :as => :logout +match 'exit' => 'sessions#destroy', :as => :logout </ruby> This will create +logout_path+ and +logout_url+ as named helpers in your application. Calling +logout_path+ will return +/logout+ @@ -636,7 +642,7 @@ end resources :photos </ruby> -This will provide route helpers such as +photographer_photos_path+. +This will provide route helpers such as +admin_photos_path+, +new_admin_photo_path+ etc. You could specify a name prefix to use for a group of routes in the scope: diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile index 1ddf094d18..b45514f66d 100644 --- a/railties/guides/source/security.textile +++ b/railties/guides/source/security.textile @@ -698,7 +698,7 @@ The most common entry points are message posts, user comments, and guest books, XSS attacks work like this: An attacker injects some code, the web application saves it and displays it on a page, later presented to a victim. Most XSS examples simply display an alert box, but it is more powerful than that. XSS can steal the cookie, hijack the session, redirect the victim to a fake website, display advertisements for the benefit of the attacker, change elements on the web site to get confidential information or install malicious software through security holes in the web browser. -During the second half of 2007, there were 88 vulnerabilities reported in Mozilla browsers, 22 in Safari, 18 in IE, and 12 in Opera. The "Symantec Global Internet Security threat report":http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf also documented 239 browser plug-in vulnerabilities in the last six months of 2007. "Mpack":http://pandalabs.pandasecurity.com/archive/MPack-uncovered_2100_.aspx is a very active and up-to-date attack framework which exploits these vulnerabilities. For criminal hackers, it is very attractive to exploit an SQL-Injection vulnerability in a web application framework and insert malicious code in every textual table column. In April 2008 more than 510,000 sites were hacked like this, among them the British government, United Nations, and many more high targets. +During the second half of 2007, there were 88 vulnerabilities reported in Mozilla browsers, 22 in Safari, 18 in IE, and 12 in Opera. The "Symantec Global Internet Security threat report":http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf also documented 239 browser plug-in vulnerabilities in the last six months of 2007. "Mpack":http://pandalabs.pandasecurity.com/mpack-uncovered/ is a very active and up-to-date attack framework which exploits these vulnerabilities. For criminal hackers, it is very attractive to exploit an SQL-Injection vulnerability in a web application framework and insert malicious code in every textual table column. In April 2008 more than 510,000 sites were hacked like this, among them the British government, United Nations, and many more high targets. A relatively new, and unusual, form of entry points are banner advertisements. In earlier 2008, malicious code appeared in banner ads on popular sites, such as MySpace and Excite, according to "Trend Micro":http://blog.trendmicro.com/myspace-excite-and-blick-serve-up-malicious-banner-ads/. diff --git a/railties/guides/source/testing.textile b/railties/guides/source/testing.textile index 8d7d73b487..69695c93c8 100644 --- a/railties/guides/source/testing.textile +++ b/railties/guides/source/testing.textile @@ -12,7 +12,7 @@ endprologue. h3. Why Write Tests for your Rails Applications? -* 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. +* Rails makes it super easy to write your tests. It starts by producing skeleton test code in the 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. @@ -54,7 +54,7 @@ For good tests, you'll need to give some thought to setting up test data. In Rai h5. 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*. In this guide we will use *YAML* which is the preferred format. +_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 +rails generate model+ to create a new model, fixture stubs will be automatically created and placed in this directory. @@ -140,7 +140,7 @@ h3. Unit Testing your Models In Rails, unit tests are what you write to test your models. -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 practices. I will be using examples from this generated code and would be supplementing it with additional examples where necessary. +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 practices. I will be using examples from this generated code and will be supplementing it with additional examples where necessary. NOTE: For more information on Rails <i>scaffolding</i>, refer to "Getting Started with Rails":getting_started.html @@ -174,7 +174,7 @@ A line by line examination of this file will help get you oriented to Rails test require 'test_helper' </ruby> -As you know by now that +test_helper.rb+ specifies the default configuration to run our tests. This is included with all the tests, so any methods added to this file are available to all your tests. +As you know by now, +test_helper.rb+ specifies the default configuration to run our tests. This is included with all the tests, so any methods added to this file are available to all your tests. <ruby> class PostTest < ActiveSupport::TestCase @@ -204,16 +204,16 @@ assert true This line of code is called an _assertion_. An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check: -* is this value = that value? +* does this value = that value? * is this object nil? * does this line of code throw an exception? * is the user's password greater than 5 characters? -Every test contains one or more assertions. Only when all the assertions are successful the test passes. +Every test contains one or more assertions. Only when all the assertions are successful will the test pass. h4. Preparing your 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: +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: <shell> $ rake db:migrate @@ -221,7 +221,7 @@ $ rake db:migrate $ rake db:test:load </shell> -Above +rake db:migrate+ runs any pending migrations on the _development_ 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. +Above +rake db:migrate+ runs any pending migrations on the _development_ 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 idea 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. @@ -294,7 +294,7 @@ test_should_not_save_post_without_title(PostTest) [/test/unit/post_test.rb:6]: 1 tests, 1 assertions, 1 failures, 0 errors </shell> -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: +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: <ruby> test "should not save post without title" do @@ -332,7 +332,7 @@ Finished in 0.193608 seconds. 1 tests, 1 assertions, 0 failures, 0 errors </shell> -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). +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 "15 TDD steps to create a Rails application":http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html. @@ -369,13 +369,13 @@ NOTE: The execution of each test method stops as soon as any error or an asserti h4. What to Include in Your Unit Tests -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. +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. h4. 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. -There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with +test/unit+, the testing library used by Rails. The +[msg]+ parameter is an optional string message you can specify to make your test failure messages clearer. It's not required. +There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with +test/unit+, the default testing library used by Rails. The +[msg]+ parameter is an optional string message you can specify to make your test failure messages clearer. It's not required. |_.Assertion |_.Purpose| |+assert( boolean, [msg] )+ |Ensures that the object/expression is true.| @@ -615,7 +615,7 @@ Here's what a freshly-generated integration test looks like: require 'test_helper' class UserFlowsTest < ActionController::IntegrationTest - # fixtures :your, :models + fixtures :all # Replace this with your real tests. test "the truth" do @@ -729,12 +729,15 @@ You don't need to set up and run your tests by hand on a test-by-test basis. Rai |_.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:benchmark+ |Benchmark the performance tests| |+rake test:functionals+ |Runs all the functional tests from +test/functional+| |+rake test:integration+ |Runs all the integration tests from +test/integration+| +|+rake test:plugins+ |Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)| +|+rake test:profile+ |Profile the performance tests| |+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 test:units+ |Runs all the unit tests from +test/unit+| + h3. Brief Note About +Test::Unit+ @@ -780,7 +783,7 @@ class PostsControllerTest < ActionController::TestCase end </ruby> -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: +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) @@ -855,7 +858,7 @@ The goals of testing your mailer classes are to ensure that: h5. From All Sides -There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a known value (a fixture -- yay! more fixtures!). In the functional tests you don't so much test the minute details produced by the mailer Instead we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time. +There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a known value (a fixture.) In the functional tests you don't so much test the minute details produced by the mailer; instead, we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time. h4. Unit Testing @@ -907,7 +910,7 @@ However often in unit tests, mails will not actually be sent, simply constructed h4. Functional Testing -Functional testing for mailers involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests you call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job You are probably more interested in is whether your own business logic is sending emails when you expect them to got out. For example, you can check that the invite friend operation is sending an email appropriately: +Functional testing for mailers involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests you call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job. You are probably more interested in whether your own business logic is sending emails when you expect them to go out. For example, you can check that the invite friend operation is sending an email appropriately: <ruby> require 'test_helper' |