From c3f53f412cd170fc295b46e48aa81837ad15ec83 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Fri, 19 Dec 2008 14:27:43 +0000 Subject: [PATCH] Merge docrails --- actionmailer/lib/action_mailer/base.rb | 1 + .../lib/action_view/helpers/date_helper.rb | 2 +- .../helpers/form_options_helper.rb | 20 +- .../lib/active_record/associations.rb | 10 +- activerecord/lib/active_record/base.rb | 3 +- .../abstract/connection_specification.rb | 1 + .../abstract/schema_definitions.rb | 4 +- activerecord/lib/active_record/validations.rb | 6 +- .../activerecord_validations_callbacks.html | 81 +- railties/doc/guides/html/finders.html | 6 + .../html/getting_started_with_rails.html | 2 +- .../guides/html/layouts_and_rendering.html | 2 +- .../html/testing_rails_applications.html | 1496 ++++++----------- .../activerecord_validations_callbacks.txt | 75 +- railties/doc/guides/source/finders.txt | 44 +- .../source/getting_started_with_rails.txt | 2 +- railties/doc/guides/source/i18n.txt | 266 ++- .../images/i18n/demo_localized_pirate.png | Bin 0 -> 36500 bytes .../source/images/i18n/demo_translated_en.png | Bin 0 -> 32877 bytes .../images/i18n/demo_translated_pirate.png | Bin 0 -> 34506 bytes .../images/i18n/demo_translation_missing.png | Bin 0 -> 34373 bytes .../source/images/i18n/demo_untranslated.png | Bin 0 -> 32793 bytes .../source/testing_rails_applications.txt | 20 +- railties/lib/rails/plugin/locator.rb | 2 +- 24 files changed, 898 insertions(+), 1145 deletions(-) create mode 100644 railties/doc/guides/source/images/i18n/demo_localized_pirate.png create mode 100644 railties/doc/guides/source/images/i18n/demo_translated_en.png create mode 100644 railties/doc/guides/source/images/i18n/demo_translated_pirate.png create mode 100644 railties/doc/guides/source/images/i18n/demo_translation_missing.png create mode 100644 railties/doc/guides/source/images/i18n/demo_untranslated.png diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 730dd2d7aa..f1273eb02e 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -17,6 +17,7 @@ module ActionMailer #:nodoc: # class Notifier < ActionMailer::Base # def signup_notification(recipient) # recipients recipient.email_address_with_name + # bcc ["bcc@example.com", "Order Watcher "] # from "system@example.com" # subject "New account information" # body :account => recipient diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index 22108dd99d..a04bb8c598 100644 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -111,7 +111,7 @@ module ActionView # # ==== Options # * :use_month_numbers - Set to true if you want to use month numbers rather than month names (e.g. - # "2" instead of "February"). + # "2" instead of "February"). # * :use_short_month - Set to true if you want to use the abbreviated month name instead of the full # name (e.g. "Feb" instead of "February"). # * :add_month_number - Set to true if you want to show both, the month's number and name (e.g. diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb index 33f8aaf9ed..9ed50a9653 100644 --- a/actionpack/lib/action_view/helpers/form_options_helper.rb +++ b/actionpack/lib/action_view/helpers/form_options_helper.rb @@ -201,13 +201,21 @@ module ActionView # Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the # the result of a call to the +value_method+ as the option value and the +text_method+ as the option text. + # Example: + # options_from_collection_for_select(@people, 'id', 'name') + # This will output the same HTML as if you did this: + # + # + # This is more often than not used inside a #select_tag like this example: + # select_tag 'person', options_from_collection_for_select(@people, 'id', 'name') + # # If +selected+ is specified, the element returning a match on +value_method+ will get the selected option tag. - # - # Example (call, result). Imagine a loop iterating over each +person+ in @project.people to generate an input tag: - # options_from_collection_for_select(@project.people, "id", "name") - # - # - # NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag. + # Be sure to specify the same class as the +value_method+ when specifying a selected option. + # Failure to do this will produce undesired results. Example: + # options_from_collection_for_select(@people, 'id', 'name', '1') + # Will not select a person with the id of 1 because 1 (an Integer) is not the same as '1' (a string) + # options_from_collection_for_select(@people, 'id', 'name', 1) + # should produce the desired results. def options_from_collection_for_select(collection, value_method, text_method, selected = nil) options = collection.map do |element| [element.send(text_method), element.send(value_method)] diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 3165015f3e..3cee9c7af2 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -153,7 +153,7 @@ module ActiveRecord # #others.destroy_all | X | X | X # #others.find(*args) | X | X | X # #others.find_first | X | | - # #others.exist? | X | X | X + # #others.exists? | X | X | X # #others.uniq | X | X | X # #others.reset | X | X | X # @@ -652,7 +652,7 @@ module ActiveRecord # Returns the number of associated objects. # [collection.find(...)] # Finds an associated object according to the same rules as ActiveRecord::Base.find. - # [collection.exist?(...)] + # [collection.exists?(...)] # Checks whether an associated object with the given conditions exists. # Uses the same rules as ActiveRecord::Base.exists?. # [collection.build(attributes = {}, ...)] @@ -682,7 +682,7 @@ module ActiveRecord # * Firm#clients.empty? (similar to firm.clients.size == 0) # * Firm#clients.size (similar to Client.count "firm_id = #{id}") # * Firm#clients.find (similar to Client.find(id, :conditions => "firm_id = #{id}")) - # * Firm#clients.exist?(:name => 'ACME') (similar to Client.exist?(:name => 'ACME', :firm_id => firm.id)) + # * Firm#clients.exists?(:name => 'ACME') (similar to Client.exists?(:name => 'ACME', :firm_id => firm.id)) # * Firm#clients.build (similar to Client.new("firm_id" => id)) # * Firm#clients.create (similar to c = Client.new("firm_id" => id); c.save; c) # The declaration can also include an options hash to specialize the behavior of the association. @@ -1107,7 +1107,7 @@ module ActiveRecord # Finds an associated object responding to the +id+ and that # meets the condition that it has to be associated with this object. # Uses the same rules as ActiveRecord::Base.find. - # [collection.exist?(...)] + # [collection.exists?(...)] # Checks whether an associated object with the given conditions exists. # Uses the same rules as ActiveRecord::Base.exists?. # [collection.build(attributes = {})] @@ -1133,7 +1133,7 @@ module ActiveRecord # * Developer#projects.empty? # * Developer#projects.size # * Developer#projects.find(id) - # * Developer#clients.exist?(...) + # * Developer#clients.exists?(...) # * Developer#projects.build (similar to Project.new("project_id" => id)) # * Developer#projects.create (similar to c = Project.new("project_id" => id); c.save; c) # The declaration may include an options hash to specialize the behavior of the association. diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index dfead0b94f..aa6013583d 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -811,8 +811,7 @@ module ActiveRecord #:nodoc: # # ==== Parameters # - # * +updates+ - A string of column and value pairs that will be set on any records that match conditions. - # What goes into the SET clause. + # * +updates+ - A string of column and value pairs that will be set on any records that match conditions. This creates the SET clause of the generated SQL. # * +conditions+ - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro for more info. # * +options+ - Additional options are :limit and :order, see the examples for usage. # diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb index ccb79f547a..bbc290f721 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb @@ -123,6 +123,7 @@ module ActiveRecord connection_handler.retrieve_connection(self) end + # Returns true if +ActiveRecord+ is connected. def connected? connection_handler.connected?(self) end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index 58992f91da..fe9cbcf024 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -32,10 +32,12 @@ module ActiveRecord @primary = nil end + # Returns +true+ if the column is either of type string or text. def text? type == :string || type == :text end + # Returns +true+ if the column is either of type integer, float or decimal. def number? type == :integer || type == :float || type == :decimal end @@ -295,7 +297,7 @@ module ActiveRecord # puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition" # end # end - # + # # def self.down # ... # end diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index 4b275ddd70..617b3f440f 100644 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -1049,15 +1049,15 @@ module ActiveRecord protected # Overwrite this method for validation checks on all saves and use Errors.add(field, msg) for invalid attributes. - def validate #:doc: + def validate end # Overwrite this method for validation checks used only on creation. - def validate_on_create #:doc: + def validate_on_create end # Overwrite this method for validation checks used only on updates. - def validate_on_update # :doc: + def validate_on_update end end end diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html index cb381e7191..039e3d1891 100644 --- a/railties/doc/guides/html/activerecord_validations_callbacks.html +++ b/railties/doc/guides/html/activerecord_validations_callbacks.html @@ -231,7 +231,7 @@ ul#navMain {
  • The validates_length_of helper
  • -
  • The validates_numericallity_of helper
  • +
  • The validates_numericality_of helper
  • The validates_presence_of helper
  • @@ -338,7 +338,7 @@ Create your own custom validation methods
  • -Work with the error messages generated by the validation proccess +Work with the error messages generated by the validation process

  • @@ -405,7 +405,7 @@ http://www.gnu.org/software/src-highlite --> >> p.new_record? => false -

    Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either save or update_attributes) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.

    +

    Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either save or update_attributes) will result in a SQL update operation. Active Record will use these facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.

    - +
    @@ -524,7 +524,8 @@ by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    class MovieFile < ActiveRecord::Base
    -  validates_exclusion_of :format, :in => %w(mov avi), :message => "Extension %s is not allowed"
    +  validates_exclusion_of :format, :in => %w(mov avi),
    +    :message => "Extension %s is not allowed"
     end
     

    The validates_exclusion_of helper has an option :in that receives the set of values that will not be accepted for the validated attributes. The :in option has an alias called :within that you can use for the same purpose, if you'd like to. In the previous example we used the :message option to show how we can personalize it with the current attribute's value, through the %s format mask.

    @@ -537,7 +538,8 @@ by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    class Product < ActiveRecord::Base
    -  validates_format_of :description, :with => /^[a-zA-Z]+$/, :message => "Only letters allowed"
    +  validates_format_of :description, :with => /^[a-zA-Z]+$/,
    +    :message => "Only letters allowed"
     end
     

    The default error message for validates_format_of is "is invalid".

    @@ -549,7 +551,8 @@ by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    class Coffee < ActiveRecord::Base
    -  validates_inclusion_of :size, :in => %w(small medium large), :message => "%s is not a valid size"
    +  validates_inclusion_of :size, :in => %w(small medium large),
    +    :message => "%s is not a valid size"
     end
     

    The validates_inclusion_of helper has an option :in that receives the set of values that will be accepted. The :in option has an alias called :within that you can use for the same purpose, if you'd like to. In the previous example we used the :message option to show how we can personalize it with the current attribute's value, through the %s format mask.

    @@ -602,7 +605,7 @@ http://www.gnu.org/software/src-highlite --> end

    This helper has an alias called validates_size_of, it's the same helper with a different name. You can use it if you'd like to.

    -

    3.9. The validates_numericallity_of helper

    +

    3.9. The validates_numericality_of helper

    This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the :integer_only option set to true, you can specify that only integral numbers are allowed.

    If you use :integer_only set to true, then it will use the /\A[+\-]?\d+\Z/ regular expression to validate the attribute's value. Otherwise, it will try to convert the value using Kernel.Float.

    @@ -611,11 +614,11 @@ by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    class Player < ActiveRecord::Base
    -  validates_numericallity_of :points
    -  validates_numericallity_of :games_played, :integer_only => true
    +  validates_numericality_of :points
    +  validates_numericality_of :games_played, :integer_only => true
     end
     
    -

    The default error message for validates_numericallity_of is "is not a number".

    +

    The default error message for validates_numericality_of is "is not a number".

    3.10. The validates_presence_of helper

    This helper validates that the attributes are not empty. It uses the blank? method to check if the value is either nil or an empty string (if the string has only spaces, it will still be considered empty).

    @@ -673,7 +676,8 @@ by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    class Holiday < ActiveRecord::Base
    -  validates_uniqueness_of :name, :scope => :year, :message => "Should happen once per year"
    +  validates_uniqueness_of :name, :scope => :year,
    +    :message => "Should happen once per year"
     end
     

    There is also a :case_sensitive option that you can use to define if the uniqueness contraint will be case sensitive or not. This option defaults to true.

    @@ -692,7 +696,7 @@ http://www.gnu.org/software/src-highlite -->

    There are some common options that all the validation helpers can use. Here they are, except for the :if and :unless options, which we'll cover right at the next topic.

    4.1. The :allow_nil option

    -

    You may use the :allow_nil option everytime you just want to trigger a validation if the value being validated is not nil. You may be asking yourself if it makes any sense to use :allow_nil and validates_presence_of together. Well, it does. Remember, validation will be skipped only for nil attributes, but empty strings are not considered nil.

    +

    You may use the :allow_nil option everytime you want to trigger a validation only if the value being validated is not nil. You may be asking yourself if it makes any sense to use :allow_nil and validates_presence_of together. Well, it does. Remember, validation will be skipped only for nil attributes, but empty strings are not considered nil.

    class Person < ActiveRecord::Base
    -  validates_uniqueness_of :email, :on => :create # => it will be possible to update email with a duplicated value
    -  validates_numericallity_of :age, :on => :update # => it will be possible to create the record with a 'non-numerical age'
    -  validates_presence_of :name, :on => :save # => that's the default
    +  # => it will be possible to update email with a duplicated value
    +  validates_uniqueness_of :email, :on => :create
    +
    +  # => it will be possible to create the record with a 'non-numerical age'
    +  validates_numericality_of :age, :on => :update
    +
    +  # => the default
    +  validates_presence_of :name, :on => :save
     end
     
    @@ -756,7 +765,8 @@ by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    class Account < ActiveRecord::Base
    -  validates_confirmation_of :password, :unless => Proc.new { |a| a.password.blank? }
    +  validates_confirmation_of :password,
    +    :unless => Proc.new { |a| a.password.blank? }
     end
     
    @@ -770,7 +780,8 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    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
    +    errors.add(:expiration_date, "can't be in the past") if
    +      !expiration_date.blank? and expiration_date < Date.today
       end
     end
     
    @@ -781,14 +792,17 @@ by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    class Invoice < ActiveRecord::Base
    -  validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value
    +  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
    +    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
    +    errors.add(:discount, "can't be greater than total value") unless
    +      discount <= total_value
       end
     end
     
    @@ -874,16 +888,18 @@ person.errors.< person = Person.new(:name => "JD") person.valid? # => false -person.errors.on(:name) # => "is too short (minimum is 3 characters)" +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)"] +person.errors.on(:name) +# => ["can't be blank", "is too short (minimum is 3 characters)"]
    • -clear is used when you intentionally wants to clear all the messages in the errors collection. +clear is used when you intentionally want to clear all the messages in the errors collection. However, calling errors.clear upon an invalid object won't make it valid: the errors collection will now be empty, but the next time you call valid? or any method that tries to save this object to the database, the validations will run. If any of them fails, the errors collection will get filled again.

    @@ -898,10 +914,15 @@ http://www.gnu.org/software/src-highlite --> end person = Person.new -puts person.valid? # => false -person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"] +person.valid? # => false +person.errors.on(:name) +# => ["can't be blank", "is too short (minimum is 3 characters)"] + person.errors.clear -person.errors # => nil +person.errors.empty? # => true +p.save # => false +p.errors.on(:name) +# => ["can't be blank", "is too short (minimum is 3 characters)"]

    8. Callbacks

    @@ -910,7 +931,7 @@ person.errors 8.1. Callbacks registration

    In order to use the available callbacks, you need to registrate them. There are two ways of doing that.

    8.2. Registering callbacks by overriding the callback methods

    -

    You can specify the callback method direcly, by overriding it. Let's see how it works using the before_validation callback, which will surprisingly run right before any validation is done.

    +

    You can specify the callback method directly, by overriding it. Let's see how it works using the before_validation callback, which will surprisingly run right before any validation is done.

    end

    12.1. Registering observers

    -

    If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register then in our application's config/environment.rb file. In this file there is a commented out line where we can define the observers that our application should load at start-up.

    +

    If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register them somewhere. The usual place to do that is in our application's config/environment.rb file. In this file there is a commented out line where we can define the observers that our application should load at start-up.

    # Activate observers that should always be running
     config.active_record.observers = :registration_observer, :auditor
     
    +

    You can uncomment the line with config.active_record.observers and change the symbols for the name of the observers that should be registered.

    +

    It's also possible to register callbacks in any of the files living at config/environments/, if you want an observer to work only in a specific environment. There is not a config.active_record.observers line at any of those files, but you can simply add it.

    12.2. Where to put the observers' source files

    By convention, you should always save your observers' source files inside app/models.

    diff --git a/railties/doc/guides/html/finders.html b/railties/doc/guides/html/finders.html index c2c1db99e3..603f488cc9 100644 --- a/railties/doc/guides/html/finders.html +++ b/railties/doc/guides/html/finders.html @@ -609,6 +609,7 @@ http://www.gnu.org/software/src-highlite -->

    6. Selecting Certain Fields

    To select certain fields, you can use the select option like this: Client.first(:select ⇒ "viewable_by, locked"). This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute SELECT viewable_by, locked FROM clients LIMIT 0,1 on your database.

    +

    You can also call SQL functions within the select option. For example, if you would like to only grab a single record per unique value in a certain field by using the DISTINCT function you can do it like this: Client.all(:select ⇒ "DISTINCT(name)").

    7. Limit & Offset

    @@ -1051,6 +1052,11 @@ http://www.gnu.org/software/src-highlite -->
    • +December 1 2008: Added using an SQL function example to Selecting Certain Fields section as per this ticket +

      +
    • +
    • +

      November 23 2008: Added documentation for find_by_last and find_by_bang!

    • diff --git a/railties/doc/guides/html/getting_started_with_rails.html b/railties/doc/guides/html/getting_started_with_rails.html index 4fc92f8ad7..ac16a79ac1 100644 --- a/railties/doc/guides/html/getting_started_with_rails.html +++ b/railties/doc/guides/html/getting_started_with_rails.html @@ -1723,7 +1723,7 @@ http://www.gnu.org/software/src-highlite -->
    Tip For more information on routing, see the Rails Routing from the Outside In guide.For more information on routing, see the Rails Routing from the Outside In guide.

    8.4. Generating a Controller

    diff --git a/railties/doc/guides/html/layouts_and_rendering.html b/railties/doc/guides/html/layouts_and_rendering.html index 7138c45853..30c114ef82 100644 --- a/railties/doc/guides/html/layouts_and_rendering.html +++ b/railties/doc/guides/html/layouts_and_rendering.html @@ -642,7 +642,7 @@ end

    With those declarations, the inventory layout would be used only for the index method, the product layout would be used for everything else except the rss method, and the rss method will have its layout determined by the automatic layout rules.

    Layout Inheritance

    Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example:

    -

    application.rb:

    +

    application_controller.rb:

    -
    $ cd test
    -$ ruby unit/post_test.rb
    -
    -Loaded suite unit/post_test
    -Started
    -.
    -Finished in 0.023513 seconds.
    -
    -1 tests, 1 assertions, 0 failures, 0 errors
    -
    -

    This will run all the test methods from the test case.

    -

    You can also run a particular test method from the test case by using the -n switch with the test method 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.

    -
    $ ruby unit/post_test.rb -n test_truth
    +
    
    +TIP: You can see all these rake tasks and their descriptions by running +rake \-\-tasks \-\-describe+
     
    -Loaded suite unit/post_test
    +=== Running Tests ===
    +
    +Running a test is as simple as invoking the file containing the test cases through Ruby:
    +
    +[source, shell]
    +
    +

    $ cd test +$ ruby unit/post_test.rb

    +

    Loaded suite unit/post_test Started . -Finished in 0.023513 seconds. - -1 tests, 1 assertions, 0 failures, 0 errors -

    -

    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.

    -
    -
    -
    def test_should_not_save_post_without_title
    -  post = Post.new
    -  assert !post.save
    -end
    -
    -

    Let us run this newly added test.

    +Finished in 0.023513 seconds.

    +

    1 tests, 1 assertions, 0 failures, 0 errors

    -
    $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
    +
    
    +This will run all the test methods from the test case.
    +
    +You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+.
    +
    +

    $ ruby unit/post_test.rb -n test_truth

    +

    Loaded suite unit/post_test +Started +. +Finished in 0.023513 seconds.

    +

    1 tests, 1 assertions, 0 failures, 0 errors

    +
    +
    +
    
    +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.
    +
    +[source,ruby]
    +
    +

    def test_should_not_save_post_without_title + post = Post.new + assert !post.save +end

    +
    +
    +
    
    +Let us run this newly added test.
    +
    +

    $ ruby unit/post_test.rb -n test_should_not_save_post_without_title Loaded suite unit/post_test Started F -Finished in 0.197094 seconds. - - 1) Failure: +Finished in 0.197094 seconds.

    +
    +
    +
      1) Failure:
     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']:
    -<false> is not true.
    -
    -1 tests, 1 assertions, 1 failures, 0 errors
    +<false> is not true.
    -

    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:

    -
    -
    -
    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:

    +

    1 tests, 1 assertions, 1 failures, 0 errors

    -
    $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
    +
    
    +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_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 -n test_should_not_save_post_without_title Loaded suite unit/post_test Started F -Finished in 0.198093 seconds. - - 1) Failure: +Finished in 0.198093 seconds.

    +
    +
    +
      1) Failure:
     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']:
     Saved the post without a title.
    -<false> is not true.
    -
    -1 tests, 1 assertions, 1 failures, 0 errors
    +<false> is not true.
    -

    Now to get this test to pass we can add a model level validation for the title field.

    -
    -
    -
    class Post < ActiveRecord::Base
    -  validates_presence_of :title
    -end
    -
    -

    Now the test should pass. Let us verify by running the test again:

    +

    1 tests, 1 assertions, 1 failures, 0 errors

    -
    $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
    +
    
    +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. - -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 15 TDD steps to create a Rails application.
    -
    -

    To see how an error gets reported, here's a test containing an error:

    -
    -
    -
    def test_should_report_error
    -  # some_undefined_variable is not defined elsewhere in the test case
    -  some_undefined_variable
    -  assert true
    -end
    -
    -

    Now you can see even more output in the console from running the tests:

    +Finished in 0.193608 seconds.

    +

    1 tests, 1 assertions, 0 failures, 0 errors

    -
    $ ruby unit/post_test.rb -n test_should_report_error
    +
    
    +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]
    +
    +

    def test_should_report_error + # some_undefined_variable is not defined elsewhere in the test case + some_undefined_variable + assert true +end

    +
    +
    +
    
    +Now you can see even more output in the console from running the tests:
    +
    +

    $ ruby unit/post_test.rb -n test_should_report_error Loaded suite unit/post_test Started E -Finished in 0.195757 seconds. - - 1) Error: +Finished in 0.195757 seconds.

    +
    +
    +
      1) Error:
     test_should_report_error(PostTest):
     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: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'
    -
    -1 tests, 0 assertions, 0 failures, 1 errors
    + /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'
    -

    Notice the E in the output. It denotes a test with error.

    -
    - - - -
    -Note -The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
    -
    -

    3.3. 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.

    -

    3.4. 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.

    -
    - --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - Assertion - - Purpose -
    - assert( boolean, [msg] ) - - Ensures that the object/expression is true. -
    - assert_equal( obj1, obj2, [msg] ) - - Ensures that obj1 == obj2 is true. -
    - assert_not_equal( obj1, obj2, [msg] ) - - Ensures that obj1 == obj2 is false. -
    - assert_same( obj1, obj2, [msg] ) - - Ensures that obj1.equal?(obj2) is true. -
    - assert_not_same( obj1, obj2, [msg] ) - - Ensures that obj1.equal?(obj2) is false. -
    - assert_nil( obj, [msg] ) - - Ensures that obj.nil? is true. -
    - assert_not_nil( obj, [msg] ) - - Ensures that obj.nil? is false. -
    - assert_match( regexp, string, [msg] ) - - Ensures that a string matches the regular expression. -
    - assert_no_match( regexp, string, [msg] ) - - Ensures that a string doesn't matches the regular expression. -
    - assert_in_delta( expecting, actual, delta, [msg] ) - - Ensures that the numbers expecting and actual are within delta of each other. -
    - assert_throws( symbol, [msg] ) { block } - - Ensures that the given block throws the symbol. -
    - assert_raises( exception1, exception2, … ) { block } - - Ensures that the given block raises one of the given exceptions. -
    - assert_nothing_raised( exception1, exception2, … ) { block } - - Ensures that the given block doesn't raise one of the given exceptions. -
    - assert_instance_of( class, obj, [msg] ) - - Ensures that obj is of the class type. -
    - assert_kind_of( class, obj, [msg] ) - - Ensures that obj is or descends from class. -
    - assert_respond_to( obj, symbol, [msg] ) - - Ensures that obj has a method called symbol. -
    - assert_operator( obj1, operator, obj2, [msg] ) - - Ensures that obj1.operator(obj2) is true. -
    - assert_send( array, [msg] ) - - Ensures that executing the method listed in array[1] on the object in array[0] with the parameters of array[2 and up] is true. This one is weird eh? -
    - flunk( [msg] ) - - Ensures failure. This is useful to explicitly mark a test that isn't finished yet. -
    -
    -

    Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It includes some specialized assertions to make your life easier.

    -
    - - - -
    -Note -Creating your own assertions is an advanced topic that we won't cover in this tutorial.
    -
    -

    3.5. Rails Specific Assertions

    -

    Rails adds some custom assertions of its own to the test/unit framework:

    -
    - --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - Assertion - - Purpose -
    - assert_valid(record) - - Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not. -
    - assert_difference(expressions, difference = 1, message = nil) {|| …} - - Test numeric difference between the return value of an expression as a result of what is evaluated in the yielded block. -
    - assert_no_difference(expressions, message = nil, &block) - - Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block. -
    - assert_recognizes(expected_options, path, extras={}, message=nil) - - Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options. -
    - assert_generates(expected_path, options, defaults={}, extras = {}, message=nil) - - Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures. -
    - assert_response(type, message = nil) - - Asserts that the response comes with a specific status code. You can specify :success to indicate 200, :redirect to indicate 300-399, :missing to indicate 404, or :error to match the 500-599 range -
    - assert_redirected_to(options = {}, message=nil) - - Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that assert_redirected_to(:controller ⇒ "weblog") will also match the redirection of redirect_to(:controller ⇒ "weblog", :action ⇒ "show") and so on. -
    - assert_template(expected = nil, message=nil) - - Asserts that the request was rendered with the appropriate template file. -
    -
    -

    You'll see the usage of some of these assertions in the next chapter.

    - -

    4. Functional Tests for Your Controllers

    -
    -

    In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.

    -

    4.1. What to include in your Functional Tests

    -

    You should test for things such as:

    -
      -
    • -

      -was the web request successful? -

      -
    • -
    • -

      -was the user redirected to the right page? -

      -
    • -
    • -

      -was the user successfully authenticated? -

      -
    • -
    • -

      -was the correct object stored in the response template? -

      -
    • -
    • -

      -was the appropriate message displayed to the user in the view -

      -
    • -
    -

    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.

    -

    Let me take you through one such test, test_should_get_index from the file posts_controller_test.rb.

    +

    1 tests, 0 assertions, 0 failures, 1 errors

    -
    -
    def test_should_get_index
    -  get :index
    -  assert_response :success
    -  assert_not_nil assigns(:posts)
    -end
    -
    -

    In the test_should_get_index test, Rails simulates a request on the action called index, making sure the request was successful and also ensuring that it assigns a valid posts instance variable.

    -

    The get method kicks off the web request and populates the results into the response. It accepts 4 arguments:

    -
      -
    • -

      -The action of the controller you are requesting. This can be in the form of a string or a symbol. -

      -
    • -
    • -

      -An optional hash of request parameters to pass into the action (eg. query string parameters or post variables). -

      -
    • -
    • -

      -An optional hash of session variables to pass along with the request. -

      -
    • -
    • -

      -An optional hash of flash values. -

      -
    • -
    -

    Example: Calling the :show action, passing an id of 12 as the params and setting a user_id of 5 in the session:

    +
    +
    
    +Notice the 'E' in the output. It denotes a test with error.
    +
    +NOTE: The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
    +
    +=== 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.
    +
    +=== 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.
    +
    +[grid="all"]
    +`-----------------------------------------------------------------`------------------------------------------------------------------------
    +Assertion                                                         Purpose
    +
    +

    assert( boolean, [msg] ) Ensures that the object/expression is true. +assert_equal( obj1, obj2, [msg] ) Ensures that obj1 == obj2 is true. +assert_not_equal( obj1, obj2, [msg] ) Ensures that obj1 == obj2 is false. +assert_same( obj1, obj2, [msg] ) Ensures that obj1.equal?(obj2) is true. +assert_not_same( obj1, obj2, [msg] ) Ensures that obj1.equal?(obj2) is false. +assert_nil( obj, [msg] ) Ensures that obj.nil? is true. +assert_not_nil( obj, [msg] ) Ensures that obj.nil? is false. +assert_match( regexp, string, [msg] ) Ensures that a string matches the regular expression. +assert_no_match( regexp, string, [msg] ) Ensures that a string doesn't matches the regular expression. +assert_in_delta( expecting, actual, delta, [msg] ) Ensures that the numbers expecting and actual are within delta of each other. +assert_throws( symbol, [msg] ) { block } Ensures that the given block throws the symbol. +assert_raises( exception1, exception2, … ) { block } Ensures that the given block raises one of the given exceptions. +assert_nothing_raised( exception1, exception2, … ) { block } Ensures that the given block doesn't raise one of the given exceptions. +assert_instance_of( class, obj, [msg] ) Ensures that obj is of the class type. +assert_kind_of( class, obj, [msg] ) Ensures that obj is or descends from class. +assert_respond_to( obj, symbol, [msg] ) Ensures that obj has a method called symbol. +assert_operator( obj1, operator, obj2, [msg] ) Ensures that obj1.operator(obj2) is true. +assert_send( array, [msg] ) Ensures that executing the method listed in array[1] on the object in array[0] with the parameters of array[2 and up] is true. This one is weird eh? +flunk( [msg] ) Ensures failure. This is useful to explicitly mark a test that isn't finished yet.

    -
    -
    get(:show, {'id' => "12"}, {'user_id' => 5})
    -
    -

    Another example: Calling the :view action, passing an id of 12 as the params, this time with no session, but with a flash message.

    +
    +
    
    +Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It includes some specialized assertions to make your life easier.
    +
    +NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial.
    +
    +=== Rails Specific Assertions ===
    +
    +Rails adds some custom assertions of its own to the +test/unit+ framework:
    +
    +[grid="all"]
    +`----------------------------------------------------------------------------------`-------------------------------------------------------
    +Assertion                                                                          Purpose
    +
    +

    assert_valid(record) Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not. +assert_difference(expressions, difference = 1, message = nil) {|| …} Test numeric difference between the return value of an expression as a result of what is evaluated in the yielded block. +assert_no_difference(expressions, message = nil, &block) Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block. +assert_recognizes(expected_options, path, extras={}, message=nil) Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options. +assert_generates(expected_path, options, defaults={}, extras = {}, message=nil) Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures. +assert_response(type, message = nil) Asserts that the response comes with a specific status code. You can specify :success to indicate 200, :redirect to indicate 300-399, :missing to indicate 404, or :error to match the 500-599 range +assert_redirected_to(options = {}, message=nil) Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that assert_redirected_to(:controller ⇒ "weblog") will also match the redirection of redirect_to(:controller ⇒ "weblog", :action ⇒ "show") and so on. +assert_template(expected = nil, message=nil) Asserts that the request was rendered with the appropriate template file.

    -
    -
    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:

    +
    +
    
    +You'll see the usage of some of these assertions in the next chapter.
    +
    +== Functional Tests for Your Controllers ==
    +
    +In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.
    +
    +=== What to include in your Functional Tests ===
    +
    +You should test for things such as:
    +
    + * was the web request successful?
    + * was the user redirected to the right page?
    + * was the user successfully authenticated?
    + * was the correct object stored in the response template?
    + * was the appropriate message displayed to the user in the view
    +
    +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.
    +
    +Let me take you through one such test, +test_should_get_index+ from the file +posts_controller_test.rb+.
    +
    +[source,ruby]
    +
    +

    def test_should_get_index + get :index + assert_response :success + assert_not_nil assigns(:posts) +end

    -
    -
    def test_should_create_post
    -  assert_difference('Post.count') do
    -    post :create, :post => { :title => 'Some title'}
    -  end
    +
    +
    
    +In the +test_should_get_index+ test, Rails simulates a request on the action called index, making sure the request was successful and also ensuring that it assigns a valid +posts+ instance variable.
     
    -  assert_redirected_to post_path(assigns(:post))
    -end
    -
    -

    Now you can try running all the tests and they should pass.

    -

    4.2. 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:

    -
      -
    • -

      -get -

      -
    • -
    • -

      -post -

      -
    • -
    • -

      -put -

      -
    • -
    • -

      -head -

      -
    • -
    • -

      -delete -

      -
    • -
    -

    All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others.

    -

    4.3. The 4 Hashes of the Apocalypse

    -

    After a request has been made by using one of the 5 methods (get, post, etc.) and processed, you will have 4 Hash objects ready for use:

    -
      -
    • -

      -assigns - Any objects that are stored as instance variables in actions for use in views. -

      -
    • -
    • -

      -cookies - Any cookies that are set. -

      -
    • -
    • -

      -flash - Any objects living in the flash. -

      -
    • -
    • -

      -session - Any object living in session variables. -

      -
    • -
    -

    As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for assigns. For example:

    +The +get+ method kicks off the web request and populates the results into the response. It accepts 4 arguments: + +* The action of the controller you are requesting. This can be in the form of a string or a symbol. +* An optional hash of request parameters to pass into the action (eg. query string parameters or post variables). +* An optional hash of session variables to pass along with the request. +* An optional hash of flash values. + +Example: Calling the +:show+ action, passing an +id+ of 12 as the +params+ and setting a +user_id+ of 5 in the session: + +[source,ruby]
    +
    +

    get(:show, {id ⇒ "12"}, {user_id ⇒ 5})

    -
    -
      flash["gordon"]               flash[:gordon]
    -  session["shmession"]          session[:shmession]
    -  cookies["are_good_for_u"]     cookies[:are_good_for_u]
    +
    +
    
    +Another example: Calling the +:view+ action, passing an +id+ of 12 as the +params+, this time with no session, but with a flash message.
     
    -# Because you can't use assigns[:something] for historical reasons:
    -  assigns["something"]          assigns(:something)
    -
    -

    4.4. Instance Variables Available

    -

    You also have access to three instance variables in your functional tests:

    -
      -
    • -

      -@controller - The controller processing the request -

      -
    • -
    • -

      -@request - The request -

      -
    • -
    • -

      -@response - The response -

      -
    • -
    -

    4.5. A Fuller Functional Test Example

    -

    Here's another example that uses flash, assert_redirected_to, and assert_difference:

    +[source,ruby]
    +
    +

    get(:view, {id12}, nil, {messagebooya!})

    -
    -
    def test_should_create_post
    -  assert_difference('Post.count') do
    -    post :create, :post => { :title => 'Hi', :body => 'This is my first post.'}
    -  end
    -  assert_redirected_to post_path(assigns(:post))
    -  assert_equal 'Post was successfully created.', flash[:notice]
    -end
    -
    -

    4.6. Testing Views

    -

    Testing the response to your request by asserting the presence of key HTML elements and their content is a useful way to test the views of your application. The assert_select assertion allows you to do this by using a simple yet powerful syntax.

    -
    - - - -
    -Note -You may find references to assert_tag in other documentation, but this is now deprecated in favor of assert_select.
    -
    -

    There are two forms of assert_select:

    -

    assert_select(selector, [equality], [message])` ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String), an expression with substitution values, or an HTML::Selector object.

    -

    assert_select(element, selector, [equality], [message]) ensures that the equality condition is met on all the selected elements through the selector starting from the element (instance of HTML::Node) and its descendants.

    -

    For example, you could verify the contents on the title element in your response with:

    +
    +
    
    +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
    +
    -
    -
    assert_select 'title', "Welcome to Rails Testing Guide"
    -
    -

    You can also use nested assert_select blocks. In this case the inner assert_select will run the assertion on each element selected by the outer assert_select block:

    +
    +
    
    +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:
    +
    +* +get+
    +* +post+
    +* +put+
    +* +head+
    +* +delete+
    +
    +All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others.
    +
    +=== The 4 Hashes of the Apocalypse ===
    +
    +After a request has been made by using one of the 5 methods (+get+, +post+, etc.) and processed, you will have 4 Hash objects ready for use:
    +
    +* +assigns+ - Any objects that are stored as instance variables in actions for use in views.
    +* +cookies+ - Any cookies that are set.
    +* +flash+ - Any objects living in the flash.
    +* +session+ - Any object living in session variables.
    +
    +As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for +assigns+. For example:
    +
    +[source,ruby]
    +
    +
    +
    +
    flash["gordon"]               flash[:gordon]
    +session["shmession"]          session[:shmession]
    +cookies["are_good_for_u"]     cookies[:are_good_for_u]
    +
    +

    # Because you can't use assigns[:something] for historical reasons: + assigns["something"] assigns(:something)

    -
    -
    assert_select 'ul.navigation' do
    -  assert_select 'li.menu_item'
    -end
    -
    -

    The assert_select assertion is quite powerful. For more advanced usage, refer to its documentation.

    -

    4.6.1. Additional View-based Assertions

    -

    There are more assertions that are primarily used in testing views:

    -
    - --- - - - - - - - - - - - - - - - - - - - - - - - -
    - Assertion - - Purpose -
    - assert_select_email - - Allows you to make assertions on the body of an e-mail. -
    - assert_select_rjs - - Allows you to make assertions on RJS response. assert_select_rjs has variants which allow you to narrow down on the updated element or even a particular operation on an element. -
    - assert_select_encoded - - Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements. -
    - css_select(selector) or css_select(element, selector) - - Returns an array of all the elements selected by the selector. In the second variant it first matches the base element and tries to match the selector expression on any of its children. If there are no matches both variants return an empty array. -
    -
    -

    Here's an example of using assert_select_email:

    +
    +
    
    +=== Instance Variables Available ===
    +
    +You also have access to three instance variables in your functional tests:
    +
    +* +@controller+ - The controller processing the request
    +* +@request+ - The request
    +* +@response+ - The response
    +
    +=== A Fuller Functional Test Example
    +
    +Here's another example that uses +flash+, +assert_redirected_to+, and +assert_difference+:
    +
    +[source,ruby]
    +
    +

    def test_should_create_post + assert_difference(Post.count) do + post :create, :post ⇒ { :title ⇒ Hi, :body ⇒ This is my first post.} + end + assert_redirected_to post_path(assigns(:post)) + assert_equal Post was successfully created., flash[:notice] +end

    -
    -
    assert_select_email do
    -  assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
    -end
    -
    - -

    5. Integration Testing

    -
    -

    Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.

    -

    Unlike Unit and Functional tests, integration tests have to be explicitly created under the test/integration folder within your application. Rails provides a generator to create an integration test skeleton for you.

    +
    +
    
    +=== Testing Views ===
    +
    +Testing the response to your request by asserting the presence of key HTML elements and their content is a useful way to test the views of your application. The +assert_select+ assertion allows you to do this by using a simple yet powerful syntax.
    +
    +NOTE: You may find references to +assert_tag+ in other documentation, but this is now deprecated in favor of +assert_select+.
    +
    +There are two forms of +assert_select+:
    +
    ++assert_select(selector, [equality], [message])`+ ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String), an expression with substitution values, or an +HTML::Selector+ object.
    +
    ++assert_select(element, selector, [equality], [message])+ ensures that the equality condition is met on all the selected elements through the selector starting from the _element_ (instance of +HTML::Node+) and its descendants.
    +
    +For example, you could verify the contents on the title element in your response with:
    +
    +[source,ruby]
    +
    +

    assert_select title, "Welcome to Rails Testing Guide"

    -
    -
    $ script/generate integration_test user_flows
    -      exists  test/integration/
    -      create  test/integration/user_flows_test.rb
    -
    -

    Here's what a freshly-generated integration test looks like:

    +
    +
    
    +You can also use nested +assert_select+ blocks. In this case the inner +assert_select+ will run the assertion on each element selected by the outer `assert_select` block:
    +
    +[source,ruby]
    +
    +

    assert_select ul.navigation do + assert_select li.menu_item +end

    -
    -
    require 'test_helper'
    +
    +
    
    +The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its link:http://api.rubyonrails.com/classes/ActionController/Assertions/SelectorAssertions.html#M000749[documentation].
     
    -class UserFlowsTest < ActionController::IntegrationTest
    -  # fixtures :your, :models
    +==== Additional View-based Assertions ====
     
    -  # Replace this with your real tests.
    -  def test_truth
    -    assert true
    -  end
    -end
    -
    -

    Integration tests inherit from ActionController::IntegrationTest. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.

    -

    5.1. Helpers Available for Integration tests

    -

    In addition to the standard testing helpers, there are some additional helpers available to integration tests:

    -
    - --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - Helper - - Purpose -
    - https? - - Returns true if the session is mimicking a secure HTTPS request. -
    - https! - - Allows you to mimic a secure HTTPS request. -
    - host! - - Allows you to set the host name to use in the next request. -
    - redirect? - - Returns true if the last request was a redirect. -
    - follow_redirect! - - Follows a single redirect response. -
    - request_via_redirect(http_method, path, [parameters], [headers]) - - Allows you to make an HTTP request and follow any subsequent redirects. -
    - post_via_redirect(path, [parameters], [headers]) - - Allows you to make an HTTP POST request and follow any subsequent redirects. -
    - get_via_redirect(path, [parameters], [headers]) - - Allows you to make an HTTP GET request and follow any subsequent redirects. -
    - put_via_redirect(path, [parameters], [headers]) - - Allows you to make an HTTP PUT request and follow any subsequent redirects. -
    - delete_via_redirect(path, [parameters], [headers]) - - Allows you to make an HTTP DELETE request and follow any subsequent redirects. -
    - open_session - - Opens a new session instance. -
    -
    -

    5.2. Integration Testing Examples

    -

    A simple integration test that exercises multiple controllers:

    +There are more assertions that are primarily used in testing views: + +[grid="all"] +`----------------------------------------------------------------------------------`------------------------------------------------------- +Assertion Purpose
    +
    +

    assert_select_email Allows you to make assertions on the body of an e-mail. +assert_select_rjs Allows you to make assertions on RJS response. assert_select_rjs has variants which allow you to narrow down on the updated element or even a particular operation on an element. +assert_select_encoded Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements. +css_select(selector) or css_select(element, selector) Returns an array of all the elements selected by the selector. In the second variant it first matches the base element and tries to match the selector expression on any of its children. If there are no matches both variants return an empty array.

    -
    -
    require 'test_helper'
    +
    +
    
    +Here's an example of using +assert_select_email+:
     
    -class UserFlowsTest < ActionController::IntegrationTest
    -  fixtures :users
    -
    -  def test_login_and_browse_site
    -    # login via https
    -    https!
    -    get "/login"
    -    assert_response :success
    -
    -    post_via_redirect "/login", :username => users(:avs).username, :password => users(:avs).password
    -    assert_equal '/welcome', path
    -    assert_equal 'Welcome avs!', flash[:notice]
    -
    -    https!(false)
    -    get "/posts/all"
    -    assert_response :success
    -    assert assigns(:products)
    -  end
    -end
    -
    -

    As you can see the integration test involves multiple controllers and exercises the entire stack from database to dispatcher. In addition you can have multiple session instances open simultaneously in a test and extend those instances with assertion methods to create a very powerful testing DSL (domain-specific language) just for your application.

    -

    Here's an example of multiple sessions and custom DSL in an integration test

    +[source,ruby]
    +
    +

    assert_select_email do + assert_select small, Please click the "Unsubscribe" link if you want to opt-out. +end

    -
    -
    require 'test_helper'
    +
    +
    
    +== Integration Testing ==
     
    -class UserFlowsTest < ActionController::IntegrationTest
    -  fixtures :users
    +Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.
     
    -  def test_login_and_browse_site
    +Unlike Unit and Functional tests, integration tests have to be explicitly created under the 'test/integration' folder within your application. Rails provides a generator to create an integration test skeleton for you.
     
    -    # User avs logs in
    -    avs = login(:avs)
    -    # User guest logs in
    -    guest = login(:guest)
    +[source, shell]
    +
    +

    $ script/generate integration_test user_flows + exists test/integration/ + create test/integration/user_flows_test.rb

    +
    +
    +
    
    +Here's what a freshly-generated integration test looks like:
     
    -    # Both are now available in different sessions
    -    assert_equal 'Welcome avs!', avs.flash[:notice]
    -    assert_equal 'Welcome guest!', guest.flash[:notice]
    +[source,ruby]
    +
    +

    require test_helper

    +

    class UserFlowsTest < ActionController::IntegrationTest + # fixtures :your, :models

    +
    +
    +
      # Replace this with your real tests.
    +  def test_truth
    +    assert true
    +  end
    +end
    +
    +
    +
    +
    
    +Integration tests inherit from +ActionController::IntegrationTest+. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.
     
    -    # User avs can browse site
    -    avs.browses_site
    -    # User guest can browse site aswell
    -    guest.browses_site
    +=== Helpers Available for Integration tests ===
     
    -    # Continue with other assertions
    -  end
    +In addition to the standard testing helpers, there are some additional helpers available to integration tests:
     
    -  private
    +[grid="all"]
    +`----------------------------------------------------------------------------------`-------------------------------------------------------
    +Helper                                                                             Purpose
    +
    +

    https? Returns true if the session is mimicking a secure HTTPS request. +https! Allows you to mimic a secure HTTPS request. +host! Allows you to set the host name to use in the next request. +redirect? Returns true if the last request was a redirect. +follow_redirect! Follows a single redirect response. +request_via_redirect(http_method, path, [parameters], [headers]) Allows you to make an HTTP request and follow any subsequent redirects. +post_via_redirect(path, [parameters], [headers]) Allows you to make an HTTP POST request and follow any subsequent redirects. +get_via_redirect(path, [parameters], [headers]) Allows you to make an HTTP GET request and follow any subsequent redirects. +put_via_redirect(path, [parameters], [headers]) Allows you to make an HTTP PUT request and follow any subsequent redirects. +delete_via_redirect(path, [parameters], [headers]) Allows you to make an HTTP DELETE request and follow any subsequent redirects. +open_session Opens a new session instance.

    +
    +
    +
    
    +=== Integration Testing Examples ===
     
    -    module CustomDsl
    -      def browses_site
    -        get "/products/all"
    -        assert_response :success
    -        assert assigns(:products)
    -      end
    -    end
    +A simple integration test that exercises multiple controllers:
     
    -    def login(user)
    -      open_session do |sess|
    -        sess.extend(CustomDsl)
    -        u = users(user)
    -        sess.https!
    -        sess.post "/login", :username => u.username, :password => u.password
    -        assert_equal '/welcome', path
    -        sess.https!(false)
    -      end
    -    end
    -end
    -
    -
    -

    6. 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.

    -

    --------------------------------`---------------------------------------------------- -Tasks Description

    +[source,ruby]
    +
    +

    require test_helper

    +

    class UserFlowsTest < ActionController::IntegrationTest + fixtures :users

    +
    +
    +
    def test_login_and_browse_site
    +  # login via https
    +  https!
    +  get "/login"
    +  assert_response :success
    +
    +
    +
    +
    post_via_redirect "/login", :username => users(:avs).username, :password => users(:avs).password
    +assert_equal '/welcome', path
    +assert_equal 'Welcome avs!', flash[:notice]
    +
    +
    +
    +
        https!(false)
    +    get "/posts/all"
    +    assert_response :success
    +    assert assigns(:products)
    +  end
    +end
    +
    +
    +
    +
    
    +As you can see the integration test involves multiple controllers and exercises the entire stack from database to dispatcher. In addition you can have multiple session instances open simultaneously in a test and extend those instances with assertion methods to create a very powerful testing DSL (domain-specific language) just for your application.
    +
    +Here's an example of multiple sessions and custom DSL in an integration test
    +
    +[source,ruby]
    +
    +

    require test_helper

    +

    class UserFlowsTest < ActionController::IntegrationTest + fixtures :users

    +
    +
    +
    def test_login_and_browse_site
    +
    +
    +
    +
    # User avs logs in
    +avs = login(:avs)
    +# User guest logs in
    +guest = login(:guest)
    +
    +
    +
    +
    # Both are now available in different sessions
    +assert_equal 'Welcome avs!', avs.flash[:notice]
    +assert_equal 'Welcome guest!', guest.flash[:notice]
    +
    +
    +
    +
    # User avs can browse site
    +avs.browses_site
    +# User guest can browse site aswell
    +guest.browses_site
    +
    +
    +
    +
      # Continue with other assertions
    +end
    +
    +
    +
    +
    private
    +
    +
    +
    +
    module CustomDsl
    +  def browses_site
    +    get "/products/all"
    +    assert_response :success
    +    assert assigns(:products)
    +  end
    +end
    +
    +
    +
    +
        def login(user)
    +      open_session do |sess|
    +        sess.extend(CustomDsl)
    +        u = users(user)
    +        sess.https!
    +        sess.post "/login", :username => u.username, :password => u.password
    +        assert_equal '/welcome', path
    +        sess.https!(false)
    +      end
    +    end
    +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.
    @@ -1584,7 +1146,7 @@ Tasks                           Description

    +rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
    -

    7. Brief Note About Test::Unit

    +

    4. 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.

    @@ -1596,7 +1158,7 @@ Tasks Description

    -

    8. Setup and Teardown

    +

    5. 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:

    @@ -1704,7 +1266,7 @@ http://www.gnu.org/software/src-highlite --> end
    -

    9. Testing Routes

    +

    6. 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:

    @@ -1717,10 +1279,10 @@ http://www.gnu.org/software/src-highlite --> end
    -

    10. Testing Your Mailers

    +

    7. Testing Your Mailers

    Testing mailer classes requires some specific tools to do a thorough job.

    -

    10.1. Keeping the Postman in Check

    +

    7.1. Keeping the Postman in Check

    Your ActionMailer classes — like every other part of your Rails application — should be tested to ensure that it is working as expected.

    The goals of testing your ActionMailer classes are to ensure that:

      @@ -1740,14 +1302,14 @@ the right emails are being sent at the right times

    -

    10.1.1. From All Sides

    +

    7.1.1. 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 knownvalue (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.

    -

    10.2. Unit Testing

    +

    7.2. Unit Testing

    In order to test that your mailer is working as expected, you can use unit tests to compare the actual results of the mailer with pre-written examples of what should be produced.

    -

    10.2.1. Revenge of the Fixtures

    +

    7.2.1. Revenge of the Fixtures

    For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output should look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within test/fixtures directly corresponds to the name of the mailer. So, for a mailer named UserMailer, the fixtures should reside in test/fixtures/user_mailer directory.

    When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.

    -

    10.2.2. The Basic Test case

    +

    7.2.2. The Basic Test case

    Here's a unit test to test a mailer named UserMailer whose action invite is used to send an invitation to a friend. It is an adapted version of the base test created by the generator for an invite action.

    end
    -

    11. Other Testing Approaches

    +

    8. 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:

      @@ -1831,7 +1393,7 @@ link: RSpec, a behavior-driven development fram
    -

    12. Changelog

    +

    9. Changelog