diff options
Diffstat (limited to 'railties')
37 files changed, 1907 insertions, 941 deletions
diff --git a/railties/Rakefile b/railties/Rakefile index 8de7e24738..0837e71ceb 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -288,7 +288,7 @@ guides = [ { 'activerecord' => 'finders' }, { 'debugging' => 'debugging_rails_applications' }, { 'caching' => 'caching_with_rails' }, - { 'benchmarking_and_profiling' => 'preamble' }, + { 'benchmarking_and_profiling' => 'index' }, { 'actionview' => 'layouts_and_rendering' } ] diff --git a/railties/doc/guides/actioncontroller/rescue.txt b/railties/doc/guides/actioncontroller/rescue.txt index 50583bb71e..ec03006764 100644 --- a/railties/doc/guides/actioncontroller/rescue.txt +++ b/railties/doc/guides/actioncontroller/rescue.txt @@ -64,55 +64,4 @@ private end ----------------------------------- -NOTE: Certain exceptions are only rescuable from the ApplicationController class, as they are raised before the controller gets initialized and the action gets executed. See Partik Naik's link:http://m.onkey.org/2008/7/20/rescue-from-dispatching[article] on the subject for more information. - -=== `rescue_action` === - -The `rescue_from` method was added to make it easier to rescue different kinds of exceptions and deal with each separately. Action Controller has a default method which intercepts *all* exceptions raised, `rescue_action`. You can override this method in a controller or in ApplicationController to rescue all exceptions raised in that particular context. You can get a little bit more granular by using the link:http://api.rubyonrails.org/classes/ActionController/Rescue.html#M000615[rescue_action_in_public] and link:http://api.rubyonrails.org/classes/ActionController/Rescue.html#M000618[rescue_action_locally] methods which are used to rescue actions for public and local requests. Let's see how the User::NotAuthorized exception could be caught using this technique: - -[source, ruby] ----------------------------------------- -class ApplicationController < ActionController::Base - -private - - def rescue_action_in_public(exception) - case exception - when User::NotAuthorized - user_not_authorized - else - super - end - end - -end ----------------------------------------- - -As you can see, this gets a bit messy once you start rescuing various types of error that require separate handlers, so it's a good idea to use `rescue_from` instead. - -=== Getting down and dirty === - -Of course you can still use Ruby's `rescue` to rescue exceptions wherever you want. This is usually constrained to single methods, i.e. actions, but is still a very useful technique that should be used when appropriate. For example, you might use an API that raises a timeout error in one of your actions, and you have to handle that if it's raised: - -[source, ruby] ----------------------------------------- -require 'clients_international' -class ClientsController < ApplicationController - - def update - @client = Client.find(params[:id]) - @client.attributes = params[:client] - if @client.save - flash[:notice] = "Client was updated" - ClientsInternational.send_update(@client.to_xml) - redirect_to clients_url - else - render :action => "new" - end - rescue ClientsInternational::TimeoutError - flash[:error] = "Couldn't send API update" - redirect_to @client - end - -end ----------------------------------------- +NOTE: Certain exceptions are only rescuable from the ApplicationController class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's link:http://m.onkey.org/2008/7/20/rescue-from-dispatching[article] on the subject for more information. diff --git a/railties/doc/guides/actioncontroller/session.txt b/railties/doc/guides/actioncontroller/session.txt index 0a44bfd802..467cffbf85 100644 --- a/railties/doc/guides/actioncontroller/session.txt +++ b/railties/doc/guides/actioncontroller/session.txt @@ -162,3 +162,24 @@ class MainController < ApplicationController end ------------------------------------------ + +==== flash.now ==== + +By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the `create` action fails to save a resource and you render the `new` template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use `flash.now` in the same way you use the normal `flash`: + +[source, ruby] +------------------------------------------ +class ClientsController < ApplicationController + + def create + @client = Client.new(params[:client]) + if @client.save + # ... + else + flash.now[:error] = "Could not save client" + render :action => "new" + end + end + +end +------------------------------------------ diff --git a/railties/doc/guides/actionview/layouts_and_rendering.txt b/railties/doc/guides/actionview/layouts_and_rendering.txt index 01fd8256f4..ed56b82ffd 100644 --- a/railties/doc/guides/actionview/layouts_and_rendering.txt +++ b/railties/doc/guides/actionview/layouts_and_rendering.txt @@ -635,6 +635,17 @@ Here, the +_ad_banner.html.erb+ and +_footer.html.erb+ partials could contain co TIP: For content that is shared among all pages in your application, you can use partials directly from layouts. +==== Partial Layouts + +A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this: + +[source, html] +------------------------------------------------------- +<%= render :partial => "link_area", :layout => "graybar" %> +------------------------------------------------------- + +This would look for a partial named +_link_area.html.erb+ and render it using the layout +_graybar.html.erb+. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master +layouts+ folder). + ==== Passing Local Variables You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content: @@ -677,6 +688,15 @@ Every partial also has a local variable with the same name as the partial (minus Within the +customer+ partial, the +@customer+ variable will refer to +@new_customer+ from the parent view. +If you have an instance of a model to render into a partial, you can use a shorthand syntax: + +[source, html] +------------------------------------------------------- +<%= render :partial => @customer %> +------------------------------------------------------- + +Assuming that the +@customer+ instance variable contains an instance of the +Customer+ model, this will use +_customer.html.erb+ to render it. + ==== Rendering Collections Partials are very useful in rendering collections. When you pass a collection to a partial via the +:collection+ option, the partial will be inserted once for each member in the collection: @@ -711,10 +731,45 @@ You can also specify a second partial to be rendered between instances of the ma Rails will render the +_product_ruler+ partial (with no data passed in to it) between each pair of +_product+ partials. +There's also a shorthand syntax available for rendering collections. For example, if +@products+ is a collection of products, you can render the collection this way: + +[source, html] +------------------------------------------------------- +index.rhtml.erb: + +<h1>Products</h1> +<%= render :partial => @products %> + +_product.html.erb: + +<p>Product Name: <%= product.name %></p> +------------------------------------------------------- + +Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection: + +[source, html] +------------------------------------------------------- +index.rhtml.erb: + +<h1>Contacts</h1> +<%= render :partial => [customer1, employee1, customer2, employee2] %> + +_customer.html.erb: + +<p>Name: <%= customer.name %></p> + +_employee.html.erb: + +<p>Name: <%= employee.name %></p> +------------------------------------------------------- + +In this case, Rails will use the customer or employee partials as appropriate for each member of the collection. + == Changelog == http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15[Lighthouse ticket] +* October 16, 2008: Ready for publication by link:../authors.html#mgunderloy[Mike Gunderloy] * October 4, 2008: Additional info on partials (+:object+, +:as+, and +:spacer_template+) by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) * September 28, 2008: First draft by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) @@ -757,4 +812,3 @@ http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15[Lighthouse - diff --git a/railties/doc/guides/activerecord/active_record_basics.txt b/railties/doc/guides/activerecord/active_record_basics.txt new file mode 100644 index 0000000000..345b377dfd --- /dev/null +++ b/railties/doc/guides/activerecord/active_record_basics.txt @@ -0,0 +1,2 @@ +ActiveRecord Basics +================================= diff --git a/railties/doc/guides/activerecord/association_basics.txt b/railties/doc/guides/activerecord/association_basics.txt index f9ec7a5f55..695b834652 100644 --- a/railties/doc/guides/activerecord/association_basics.txt +++ b/railties/doc/guides/activerecord/association_basics.txt @@ -354,8 +354,8 @@ In designing a data model, you will sometimes find a model that should have a re [source, ruby] ------------------------------------------------------- class Employee < ActiveRecord::Base - has_many :subordinates, :class_name => :user, :foreign_key => "manager_id" - belongs_to :manager, :class_name => :user + has_many :subordinates, :class_name => "User", :foreign_key => "manager_id" + belongs_to :manager, :class_name => "User" end ------------------------------------------------------- @@ -636,12 +636,12 @@ The +belongs_to+ association supports these options: // ===== +:class_name+ -If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is patron, you'd set things up this way: +If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is +Patron+, you'd set things up this way: [source, ruby] ------------------------------------------------------- class Order < ActiveRecord::Base - belongs_to :customer, :class_name => :patron + belongs_to :customer, :class_name => "Patron" end ------------------------------------------------------- @@ -711,7 +711,7 @@ By convention, Rails guesses that the column used to hold the foreign key on thi [source, ruby] ------------------------------------------------------- class Order < ActiveRecord::Base - belongs_to :customer, :class_name => :patron, :foreign_key => "patron_id" + belongs_to :customer, :class_name => "Patron", :foreign_key => "patron_id" end ------------------------------------------------------- @@ -863,7 +863,7 @@ In many situations, you can use the default behavior of +has_one+ without any cu [source, ruby] ------------------------------------------------------- class Supplier < ActiveRecord::Base - has_one :account, :class_name => :billing, :dependent => :nullify + has_one :account, :class_name => "Billing", :dependent => :nullify end ------------------------------------------------------- @@ -895,12 +895,12 @@ Setting the +:as+ option indicates that this is a polymorphic association. Polym ===== +:class_name+ -If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is billing, you'd set things up this way: +If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is Billing, you'd set things up this way: [source, ruby] ------------------------------------------------------- class Supplier < ActiveRecord::Base - has_one :account, :class_name => :billing + has_one :account, :class_name => "Billing" end ------------------------------------------------------- @@ -1085,7 +1085,8 @@ The +_collection_.delete+ method removes one or more objects from the collection @customer.orders.delete(@order1) ------------------------------------------------------- -WARNING: The +_collection_.delete+ method will destroy the deleted object if they are declared as +belongs_to+ and are dependent on this model. +WARNING: Objects will be in addition destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+. + ===== +_collection_=objects+ @@ -1205,12 +1206,12 @@ Setting the +:as+ option indicates that this is a polymorphic association, as di ===== +:class_name+ -If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is transactions, you'd set things up this way: +If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is +Transaction+, you'd set things up this way: [source, ruby] ------------------------------------------------------- class Customer < ActiveRecord::Base - has_many :orders, :class_name => :transaction + has_many :orders, :class_name => "Transaction" end ------------------------------------------------------- @@ -1221,7 +1222,7 @@ The +:conditions+ option lets you specify the conditions that the associated obj [source, ruby] ------------------------------------------------------- class Customer < ActiveRecord::Base - has_many :confirmed_orders, :class_name => :orders, :conditions => "confirmed = 1" + has_many :confirmed_orders, :class_name => "Order", :conditions => "confirmed = 1" end ------------------------------------------------------- @@ -1230,7 +1231,7 @@ You can also set conditions via a hash: [source, ruby] ------------------------------------------------------- class Customer < ActiveRecord::Base - has_many :confirmed_orders, :class_name => :orders, :conditions => { :confirmed => true } + has_many :confirmed_orders, :class_name => "Order", :conditions => { :confirmed => true } end ------------------------------------------------------- @@ -1321,7 +1322,7 @@ The +:limit+ option lets you restrict the total number of objects that will be f [source, ruby] ------------------------------------------------------- class Customer < ActiveRecord::Base - has_many :recent_orders, :class_name => :orders, :order => "order_date DESC", :limit => 100 + has_many :recent_orders, :class_name => "Order", :order => "order_date DESC", :limit => 100 end ------------------------------------------------------- @@ -1591,19 +1592,19 @@ TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when s [source, ruby] ------------------------------------------------------- class User < ActiveRecord::Base - has_and_belongs_to_many :friends, :class_name => :users, + has_and_belongs_to_many :friends, :class_name => "User", :foreign_key => "this_user_id", :association_foreign_key => "other_user_id" end ------------------------------------------------------- ===== +:class_name+ -If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is gadgets, you'd set things up this way: +If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is +Gadget+, you'd set things up this way: [source, ruby] ------------------------------------------------------- class Parts < ActiveRecord::Base - has_and_belongs_to_many :assemblies, :class_name => :gadgets + has_and_belongs_to_many :assemblies, :class_name => "Gadget" end ------------------------------------------------------- @@ -1654,7 +1655,7 @@ By convention, Rails guesses that the column in the join table used to hold the [source, ruby] ------------------------------------------------------- class User < ActiveRecord::Base - has_and_belongs_to_many :friends, :class_name => :users, + has_and_belongs_to_many :friends, :class_name => "User", :foreign_key => "this_user_id", :association_foreign_key => "other_user_id" end ------------------------------------------------------- diff --git a/railties/doc/guides/benchmarking_and_profiling/appendix.txt b/railties/doc/guides/benchmarking_and_profiling/appendix.txt index ce618603d4..8e2e383ff3 100644 --- a/railties/doc/guides/benchmarking_and_profiling/appendix.txt +++ b/railties/doc/guides/benchmarking_and_profiling/appendix.txt @@ -90,15 +90,6 @@ service both for when in development and when you put your application into prod #TODO more in-depth without being like an advertisement. -=== FiveRuns === -http://www.fiveruns.com/[http://www.fiveruns.com/] - -#TODO give a bit more detail - -==== TuneUp ==== - -In their words "a new socially networked application profiling tool for Ruby on Rails developers. Designed for rapid application performance analysis in development, both privately or collaboratively with input from the community, FiveRuns TuneUp gives developers visibility into performance trouble spots and bottlenecks before they reach production." - ==== Manage ==== Like new relic a production monitoring tool. diff --git a/railties/doc/guides/benchmarking_and_profiling/basics.txt b/railties/doc/guides/benchmarking_and_profiling/basics.txt deleted file mode 100644 index 2a34795b08..0000000000 --- a/railties/doc/guides/benchmarking_and_profiling/basics.txt +++ /dev/null @@ -1,55 +0,0 @@ -== On The Road to Optimization == -=== Looking at the log file in regards to optimization === - -You actually have been gathering data for benchmarking throughout your development cycle. Your log files are not just for error detection they also contain very useful information on how speedy your action is behaving. - -.Regular Log Output ----------------------------------------------------------------------------- - -Processing MediaController#index (for 127.0.0.1 at 2008-07-17 21:30:21) [GET] - - Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo -SGFzaHsABjoKQHVzZWR7AA==--cb57dad9c5e4704f0e1eddb3d498fef544faaf46 - - Parameters: {"action"=>"index", "controller"=>"media"} - - [4;35;1mProduct Columns (0.003187)[0m [0mSHOW FIELDS FROM `products`[0m - [4;36;1mProduct Load (0.000597)[0m [0;1mSELECT * FROM `products` WHERE (`products`.`name` = 'Escape Plane') LIMIT 1[0m - -Rendering template within layouts/standard - -Rendering media/index - [4;35;1mTrack Load (0.001507)[0m [0mSELECT * FROM `tracks` WHERE (`tracks`.product_id = 1) [0m - [4;36;1mTrack Columns (0.002280)[0m [0;1mSHOW FIELDS FROM `tracks`[0m - -Rendered layouts/_header (0.00051) - -*Completed in 0.04310 (23 reqs/sec) | Rendering: 0.00819 (19%) | DB: 0.00757 (17%) | 200 OK [http://localhost/media]* ----------------------------------------------------------------------------- - -What concerns us here is the last line of the action. - -Completed in 0.04310 (23 reqs/sec) gives us the amount of requests this specific action can handle. 0.04310 is the total amount of time the process to complete and 23 reqs/sec is an estimation from this. As we will see this number is not strictly valid since is a single instance of the process. But it does give you a general feel as to how the action is performing. - -Rendering: 0.00819 (19%) is the amount in milliseconds and the percentage of total time needed to complete the action for rendering the view - -DB: 0.00757 (17%) is the amount in milliseconds and the percentage of total time needed to complete the action for querying the database - -Pretty easy right. But wait 17+19 equals 36. 36%! where is the rest of the time going? The rest of the time is being spent processing the controller. It is not shown but it is easy to calculate. Usually there is where most of your time ends on well functions actions. - -=== Why the Log File on it's Own is not Helpful === - -So why can't we just use this to test our rails application. Technically that could work, but would be very stressful and slow. You don't have time to view your log after every request to see if your code is running quickly. Also a request that runs 100 reqs/sec might simply be an outlier and really usually runs at 20 reqs/sec. It's simply not enough information to do everything we need it to do but it's a start. - -But there is something else we must consider. - -=== A Simple Question, a Complicated Answer === - -Is Completed in 0.04310 (23 reqs/sec) a good time. Seems like it doesn't it. 43 ms does not outrageous time for a dynamic page load. But is this a dynamic page load. Maybe it was all cached. In which case this is very slow. Or maybe I'm running on five year old equipment and this is actually blazing fast for my G3. The truth is that we can't answer the question given the data. This is part of benchmarking. We need a baseline. Through comparative analysis of all your pages in your app, and an simple dynamic page for a control we can determine how fast your pages are actually running and if any of them need to be optimized. - -And now for something completely different a short statistic lesson. - - - - - diff --git a/railties/doc/guides/benchmarking_and_profiling/definitions.txt b/railties/doc/guides/benchmarking_and_profiling/definitions.txt deleted file mode 100644 index 565c301772..0000000000 --- a/railties/doc/guides/benchmarking_and_profiling/definitions.txt +++ /dev/null @@ -1,22 +0,0 @@ -== Terminology == - -=== What We Mean by Benchmarking and Profiling === - -Benchmarking: If you are new to programing you probably have heard the term mostly in comparative reviews of computer and graphic card specs. If you done a bit of coding you've probably seen in mostly in terms of comparing one language to another or iterations of the same language. - -Benchmarking in rails is more fine grained. It entails comparing and contrasting various parts and pages of an application against one another. Mostly one is looking for how long a page requires to render, but memory consumption is also an area of concern. - -While benchmarking two different sets of problems can emerge. Either you find that a few pages are performing worse then the rest of your app unexpectedly or that your whole entire application is slower then it reasonably should be. From there you start to profile to find the problem. - -Profiling: When a page or process is seen to be problematic due to speed or memory consumption we profile it. Meaning we measures the behavior as the page or process runs, particularly the frequency and duration of function calls. The goal of profiling is not to find bugs, but to eliminate bottlenecks and establish a baseline for future regression testing. It must be engaged in a carefully controlled process of measurement and analysis. - -==== What does that actually mean? ==== - -You have to have a clear goal for when you benchmark and profile. It's very comparable to BDD where you are taking small steps towards a solution instead of trying to do it all in one large all encompassing step. A clearly defined set of expectations is essential for meaningful performance testing. We will talk more about this later. - -==== Where Does this Leave Us ==== - -Numbers and data. You benchmark to compare, your profile to fix. It's all about gaining data to analyze and using that information to better your application. The most important thing you should take away at the moment that this must be done in a systematic way. - -So the next logical question is how do we get this data. - diff --git a/railties/doc/guides/benchmarking_and_profiling/index.txt b/railties/doc/guides/benchmarking_and_profiling/index.txt new file mode 100644 index 0000000000..0ba2660ebe --- /dev/null +++ b/railties/doc/guides/benchmarking_and_profiling/index.txt @@ -0,0 +1,239 @@ +Benchmarking and Profiling Rails +================================ + +This guide covers the benchmarking and profiling tactics/tools of Rails and Ruby in general. By referring to this guide, you will be able to: + +* Understand the various types of benchmarking and profiling metrics +* Generate performance/benchmarking tests +* Use GC patched Ruby binary to measure memory usage and object allocation +* Understand the information provided by Rails inside the log files +* Learn about various tools facilitating benchmarking and profiling + +== Why Benchmark and Profile ? + +Benchmarking and Profiling is an integral part of the development cycle. It is very important that you don't make your end users wait for too long before the page is completely loaded. Ensuring a plesant browsing experience to the end users and cutting cost of unnecessary hardwares is important for any web application. + +=== What is the difference between benchmarking and profiling ? === + +Benchmarking is the process of finding out if a piece of code is slow or not. Whereas profiling is the process of finding out what exactly is slowing down that piece of code. + +== Using and understanding the log files == + +Rails logs files containt basic but very useful information about the time taken to serve every request. A typical log entry looks something like : + +[source, ruby] +---------------------------------------------------------------------------- +Processing ItemsController#index (for 127.0.0.1 at 2008-10-17 00:08:18) [GET] + Session ID: BAh7BiIKZmxhc2hJQzonQWN0aHsABjoKQHVzZWR7AA==--83cff4fe0a897074a65335 + Parameters: {"action"=>"index", "controller"=>"items"} +Rendering template within layouts/items +Rendering items/index +Completed in 5ms (View: 2, DB: 0) | 200 OK [http://localhost/items] +---------------------------------------------------------------------------- + +For this section, we're only interested in the last line from that log entry: + +[source, ruby] +---------------------------------------------------------------------------- +Completed in 5ms (View: 2, DB: 0) | 200 OK [http://localhost/items] +---------------------------------------------------------------------------- + +This data is fairly straight forward to understand. Rails uses millisecond(ms) as the metric to measures the time taken. The complete request spent 5 ms inside Rails, out of which 2 ms were spent rendering views and none was spent communication with the database. It's safe to assume that the remaining 3 ms were spent inside the controller. + +== Helper methods == + +Rails provides various helper methods inside Active Record, Action Controller and Action View to measure the time taken by a specific code. The method is called +benchmark()+ in all three components. + +[source, ruby] +---------------------------------------------------------------------------- +Project.benchmark("Creating project") do + project = Project.create("name" => "stuff") + project.create_manager("name" => "David") + project.milestones << Milestone.find(:all) +end +---------------------------------------------------------------------------- + +The above code benchmarks the multiple statments enclosed inside +Project.benchmark("Creating project") do..end+ block and prints the results inside log files. The statement inside log files will look like: + +[source, ruby] +---------------------------------------------------------------------------- +Creating projectem (185.3ms) +---------------------------------------------------------------------------- + +Please refer to http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001336[API docs] for optional options to +benchmark()+ + +Similarly, you could use this helper method inside http://api.rubyonrails.com/classes/ActionController/Benchmarking/ClassMethods.html#M000715[controllers] ( Note that it's a class method here ): + +[source, ruby] +---------------------------------------------------------------------------- +def process_projects + self.class.benchmark("Processing projects") do + Project.process(params[:project_ids]) + Project.update_cached_projects + end +end +---------------------------------------------------------------------------- + +and http://api.rubyonrails.com/classes/ActionController/Benchmarking/ClassMethods.html#M000715[views]: + +[source, ruby] +---------------------------------------------------------------------------- +<% benchmark("Showing projects partial") do %> + <%= render :partial => @projects %> +<% end %> +---------------------------------------------------------------------------- + +== Performance Test Cases == + +Rails provides a very easy to write performance test cases, which look just like the regular integration tests. + +If you have a look at +test/performance/browsing_test.rb+ in a newly created Rails application: + +[source, ruby] +---------------------------------------------------------------------------- +require 'performance/test_helper' + +# Profiling results for each test method are written to tmp/performance. +class BrowsingTest < ActionController::PerformanceTest + def test_homepage + get '/' + end +end +---------------------------------------------------------------------------- + +This is an automatically generated example performance test file, for testing performance of homepage('/') of the application. + +=== Modes === + +==== Benchmarking ==== +==== Profiling ==== + +=== Metrics === + +==== Process Time ==== + +CPU Cycles. + +==== Memory ==== + +Memory taken. + +==== Objects ==== + +Objects allocated. + +==== GC Runs ==== + +Number of times the Ruby GC was run. + +==== GC Time ==== + +Time spent running the Ruby GC. + +=== Preparing Ruby and Ruby-prof === + +Before we go ahead, Rails performance testing requires you to build a special Ruby binary with some super powers - GC patch for measuring GC Runs/Time. This process is very straight forward. If you've never compiled a Ruby binary before, you can follow the following steps to build a ruby binary inside your home directory: + +==== Compile ==== + +[source, shell] +---------------------------------------------------------------------------- +[lifo@null ~]$ mkdir rubygc +[lifo@null ~]$ wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.6-p111.tar.gz +[lifo@null ~]$ tar -xzvf ruby-1.8.6-p111.tar.gz +[lifo@null ~]$ cd ruby-1.8.6-p111 +[lifo@null ruby-1.8.6-p111]$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0 +[lifo@null ruby-1.8.6-p111]$ ./configure --prefix=/Users/lifo/rubygc +[lifo@null ruby-1.8.6-p111]$ make && make install +---------------------------------------------------------------------------- + +==== Prepare aliases ==== + +Add the following lines in your ~/.profile for convenience: + +---------------------------------------------------------------------------- +alias gcruby='/Users/lifo/rubygc/bin/ruby' +alias gcrake='/Users/lifo/rubygc/bin/rake' +alias gcgem='/Users/lifo/rubygc/bin/gem' +alias gcirb='/Users/lifo/rubygc/bin/irb' +alias gcrails='/Users/lifo/rubygc/bin/rails' +---------------------------------------------------------------------------- + +==== Install rubygems and some basic gems ==== + +---------------------------------------------------------------------------- +[lifo@null ~]$ wget http://rubyforge.org/frs/download.php/38646/rubygems-1.2.0.tgz +[lifo@null ~]$ tar -xzvf rubygems-1.2.0.tgz +[lifo@null ~]$ cd rubygems-1.2.0 +[lifo@null rubygems-1.2.0]$ gcruby setup.rb +[lifo@null rubygems-1.2.0]$ cd ~ +[lifo@null ~]$ gcgem install rake +[lifo@null ~]$ gcgem install rails +---------------------------------------------------------------------------- + +==== Install MySQL gem ==== + +---------------------------------------------------------------------------- +[lifo@null ~]$ gcgem install mysql +---------------------------------------------------------------------------- + +If this fails, you can try to install it manually: + +---------------------------------------------------------------------------- +[lifo@null ~]$ cd /Users/lifo/rubygc/lib/ruby/gems/1.8/gems/mysql-2.7/ +[lifo@null mysql-2.7]$ gcruby extconf.rb --with-mysql-config +[lifo@null mysql-2.7]$ make && make install +---------------------------------------------------------------------------- + +=== Installing Jeremy Kemper's ruby-prof === + +We also need to install Jeremy's ruby-prof gem using our newly built ruby: + +[source, shell] +---------------------------------------------------------------------------- +[lifo@null ~]$ git clone git://github.com/jeremy/ruby-prof.git +[lifo@null ~]$ cd ruby-prof/ +[lifo@null ruby-prof (master)]$ gcrake gem +[lifo@null ruby-prof (master)]$ gcgem install pkg/ruby-prof-0.6.1.gem +---------------------------------------------------------------------------- + +=== Generating performance test === + +Rails provides a simple generator for creating new performance tests: + +[source, shell] +---------------------------------------------------------------------------- +[User profiling_tester (master)]$ script/generate performance_test homepage +---------------------------------------------------------------------------- + +This will generate +test/performance/homepage_test.rb+: + +---------------------------------------------------------------------------- +require 'performance/test_helper' + +class HomepageTest < ActionController::PerformanceTest + # Replace this with your real tests. + def test_homepage + get '/' + end +end +---------------------------------------------------------------------------- + +Which you can modify to suit your needs. + +=== Running tests === + +include::rubyprof.txt[] + +include::digging_deeper.txt[] + +include::gameplan.txt[] + +include::appendix.txt[] + +== Changelog == + +http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/4[Lighthouse ticket] + +* October 17, 2008: First revision by Pratik +* September 6, 2008: Initial version by Matthew Bergman <MzbPhoto@gmail.com>
\ No newline at end of file diff --git a/railties/doc/guides/benchmarking_and_profiling/preamble.txt b/railties/doc/guides/benchmarking_and_profiling/preamble.txt deleted file mode 100644 index aa1b4e49c8..0000000000 --- a/railties/doc/guides/benchmarking_and_profiling/preamble.txt +++ /dev/null @@ -1,44 +0,0 @@ -Benchmarking and Profiling Rails -================================ -Matthew Bergman <MzbPhoto@gmail.com> -v0.6, September 2008 - -Benchmarking and Profiling is an important part of the development process that is not nearly enough talked about for beginning developers. Its hard enough learning a language and successfully writing an application. But without a firm understanding optimization, production ready apps are a near impossibility. No matter how well you code, or how much you know about a language there is always something that will trip up your application. - -This article is my attempt to give the basic knowledge and methodology needed to optimize your application as painlessly as possible. We are are attempting this on two fronts. Both as a straight explanation and also through a real example of how benchmarking can speed up an application. - -The main things that are covered are - -* The basics of statistical analysis -* Methodology behind benchmarking and profiling -* Reading the log file for optimization -* Performance Unit tests -* Working with Ruby-Prof -* HTTPREF #because you should know it -* Overview of dedicated analysis options - -There are a lot of areas we need to cover so lets start. - - -include::definitions.txt[] - -include::basics.txt[] - -include::statistics.txt[] - -include::edge_rails_features.txt[] - -include::rubyprof.txt[] - -include::digging_deeper.txt[] - -include::gameplan.txt[] - -include::appendix.txt[] - - - - - - - diff --git a/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt b/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt index 3259ef8a45..b6d8203c8b 100644 --- a/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt +++ b/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt @@ -4,114 +4,209 @@ Getting Started With Rails This guide covers getting up and running with Ruby on Rails. After reading it, you should be familiar with: * Installing Rails, creating a new Rails application, and connecting your application to a database -* Understanding the purpose of each folder in the Rails structure -* Creating a scaffold, and explain what it is creating and why you need each element -* The basics of model, view, and controller interaction -* The basics of HTTP and RESTful design +* The general layout of a Rails application +* The basic principles of MVC (Model, View Controller) and RESTful design +* How to quickly generate the starting pieces of a Rails application. -== How to use this guide -This guide is designed for beginners who want to get started with a Rails application from scratch. It assumes that you have no prior experience using the framework. However, it is highly recommended that you *familiarize yourself with Ruby before diving into Rails*. Rails isn't going to magically revolutionize the way you write web applications if you have no experience with the language it uses. +== This Guide Assumes + +This guide is designed for beginners who want to get started with a Rails application from scratch. It does not assume that you have any prior experience with Rails. However, to get the most out of it, you need to have some prerequisites installed: + +* The link:http://www.ruby-lang.org/en/downloads/[Ruby] language +* The link:http://rubyforge.org/frs/?group_id=126[RubyGems] packaging system +* A working installation of link:http://www.sqlite.org/[SQLite] (preferred), link:http://www.mysql.com/[MySQL], or link:http://www.postgresql.org/[PostgreSQL] + +It is highly recommended that you *familiarize yourself with Ruby before diving into Rails*. You will find it much easier to follow what's going on with a Rails application if you understand basic Ruby syntax. Rails isn't going to magically revolutionize the way you write web applications if you have no experience with the language it uses. There are some good free resources on the net for learning Ruby, including: + +* link:http://www.humblelittlerubybook.com/[Mr. Neigborly’s Humble Little Ruby Book] +* link:http://www.rubycentral.com/book/[Programming Ruby] +* link:http://poignantguide.net/ruby/[Why's (Poignant) Guide to Ruby] == What is Rails? -Rails is a web development framework written in the Ruby language. It is designed to make programming web applications easier by making several assumptions about what every developer needs to get started. It allows you to write less code while accomplishing more than other languages and frameworks. -== Installing Rails +Rails is a web development framework written in the Ruby language. It is designed to make programming web applications easier by making several assumptions about what every developer needs to get started. It allows you to write less code while accomplishing more than many other languages and frameworks. Longtime Rails developers also report that it makes web application development more fun. + +Rails is _opinionated software_. That is, it assumes that there is a best way to do things, and it's designed to encourage that best way - and in some cases discourage alternatives. If you learn "The Rails Way" you'll probably discover a tremendous increase in productivity. If you persist in bringing old habits from other languages to your Rails development, and trying to use patterns you learned elsewhere, you may have a less happy experience. + +The Rails philosophy includes several guiding principles: + +* DRY - "Don't Repeat Yourself" - suggests that writing the same code over and over again is a bad thing. +* Convention Over Configuration - means that Rails makes assumptions about what you want to do and how you're going to do it, rather than letting you tweak every little thing through endless configuration files. +* REST is the best pattern for web applications - organizing your application around resources and standard HTTP verbs is the fastest way to go. + +=== The MVC Architecture + +Rails is organized around the Model, View, Controller architecture, usually just called MVC. MVC benefits include: + +* Isolation of business logic from the user interface +* Ease of keeping code DRY +* Making it clear where different types of code belong for easier maintenance + +==== Models + +A model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, one table in your database will correspond to one model in your application. The bulk of your application's business logic will be concentrated in the models. + +==== Views + +Views represent the user interface of your application. In Rails, views are often HTML files with embedded Ruby code that performs tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application. + +==== Controllers + +Controllers provide the "glue" between models and views. In Rails, controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation. + +=== The Components of Rails + +Rails provides a full stack of components for creating web applications, including: + +* Action Controller +* Action View +* Active Record +* Action Mailer +* Active Resource +* Railties +* Active Support + +==== Action Controller + +Action Controller is the component that manages the controllers in a Rails application. The Action Controller framework processes incoming requests to a Rails application, extracts parameters, and dispatches them to the intended action. Services provided by Action Controller include session management, template rendering, and redirect management. + +==== Action View + +Action View manages the views of your Rails application. It can create both HTML and XML output by default. Action View manages rendering templates, including nested and partial templates, and includes built-in AJAX support. + +==== Active Record + +Active Record is the base for the models in a Rails application. It provides database independence, basic CRUD functionality, advanced finding capabilities, and the ability to relate models to one another, among other services. + +==== Action Mailer + +Action Mailer is a framework for building e-mail services. You can use Action Mailer to send emails based on flexible templates, or to receive and process incoming email. + +==== Active Resource + +Active Resource provides a framework for managing the connection between business objects an RESTful web services. It implements a way to map web-based resources to local objects with CRUD semantics. + +==== Railties + +Railties is the core Rails code that builds new Rails applications and glues the various frameworks together in any Rails application. + +==== Active Support -`gem install rails` +Active Support is an extensive collection of utility classes and standard Ruby library extensions that are used in the Rails, both by the core code and by your applications. -== Create a new Rails project +=== REST -We're going to create a Rails project called "blog", which is the project that we will build off of for this guide. +The foundation of the RESTful architecture is generally considered to be Roy Fielding's doctoral thesis, link:http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm[Architectural Styles and the Design of Network-based Software Architectures]. Fortunately, you need not read this entire document to understand how REST works in Rails. REST, an acronym for Representational State Transfer, boils down to two main principles for our purposes: -From your terminal, type: +* Using resource identifiers (which, for the purposes of discussion, you can think of as URLs) to represent resources +* Transferring representations of the state of that resource between system components. -`rails blog` +For example, to a Rails application a request such as this: -This will create a folder in your working directory called "blog". Open up that folder and have a look at it. For the majority of this tutorial, we will live in the app/ folder, but here's a basic rundown on the function of each folder in a Rails app: ++DELETE /photos/17+ + +would be understood to refer to a photo resource with the ID of 17, and to indicate a desired action - deleting that resource. REST is a natural style for the architecture of web applications, and Rails makes it even more natural by using conventions to shield you from some of the RESTful complexities. + +== Creating a New Rails Project + +If you follow this guide, you'll create a Rails project called +blog+, a (very) simple weblog. Before you can start building the application, you need to make sure that you have Rails itself installed. + +=== Installing Rails + +In most cases, the easiest way to install Rails is to take advantage of RubyGems: + +[source, shell] +------------------------------------------------------- +$ gem install rails +------------------------------------------------------- + +NOTE: There are some special circumstances in which you might want to use an alternate installation strategy: + +* If you're working on Windows, you may find it easier to install link:http://instantrails.rubyforge.org/wiki/wiki.pl[Instant Rails]. Be aware, though, that Instant Rails releases tend to lag seriously behind the actual Rails version. Also, you will find that Rails development on Windows is overall less pleasant than on other operating systems. If at all possible, we suggest that you install a Linux virtual machine and use that for Rails development, instead of using Windows. +* If you want to keep up with cutting-edge changes to Rails, you'll want to clone the link:http://github.com/rails/rails/tree/master[Rails source code] from github. This is not recommended as an option for beginners, though. + +=== Creating the Blog Application + +Open a terminal, navigate to a folder where you have rights to create files, and type: + +[source, shell] +------------------------------------------------------- +$ rails blog +------------------------------------------------------- + +This will create a Rails application that uses a SQLite database for data storage. If you prefer to use MySQL, run this command instead: + +[source, shell] +------------------------------------------------------- +$ rails blog -d mysql +------------------------------------------------------- + +And if you're using PostgreSQL for data storage, run this command: + +[source, shell] +------------------------------------------------------- +$ rails blog -d postgresql +------------------------------------------------------- + +In any case, Rails will create a folder in your working directory called +blog+. Open up that folder and explore its contents. Most of the work in this tutorial will happen in the +app/+ folder, but here's a basic rundown on the function of each folder that Rails creates in a new application by default: [grid="all"] `-----------`----------------------------------------------------------------------------------------------------------------------------- File/Folder Purpose ------------------------------------------------------------------------------------------------------------------------------------------ -README This is a brief instruction manual for your application. Use it to tell others what it does, how to set it up, etc. -Rakefile -app/ Contains the controllers, models, and views for your application. We'll focus on the app folder in this guide -config/ Configure your application's runtime rules, routes, database, etc. -db/ Shows your current database schema, as well as the database migrations (we'll get into migrations shortly) -doc/ In-depth documentation for your application -lib/ Extended modules for your application (not covered in this guide) -log/ Application log files -public/ The only folder seen to the world as-is. This is where your images, javascript, stylesheets (CSS), and other static files go -script/ Scripts provided by Rails to do recurring tasks, benchmarking, plugin installation, starting the console or the web server -test/ Unit tests, fixtures, etc. (not covered in this guide) -tmp/ Temporary files -vendor/ Plugins folder ++README+ This is a brief instruction manual for your application. Use it to tell others what your application does, how to set it up, and so on. ++Rakefile+ This file contains batch jobs that can be run from the terminal. ++app/+ Contains the controllers, models, and views for your application. You'll focus on this folder for the remainder of this guide. ++config/+ Configure your application's runtime rules, routes, database, and more. ++db/+ Shows your current database schema, as well as the database migrations. You'll learn about migrations shortly. ++doc/+ In-depth documentation for your application. ++lib/+ Extended modules for your application (not covered in this guide). ++log/+ Application log files. ++public/+ The only folder seen to the world as-is. This is where your images, javascript, stylesheets (CSS), and other static files go. ++script/+ Scripts provided by Rails to do recurring tasks, such as benchmarking, plugin installation, and starting the console or the web server. ++test/+ Unit tests, fixtures, and other test apparatus. These are covered in link:../testing_rails_applications/testing_rails_applications.html[Testing Rails Applications] ++tmp/+ Temporary files ++vendor/+ A place for third-party code. In a typical Rails application, this includes Ruby Gems, the Rails source code (if you install it into your project) and plugins containing additional prepackaged functionality. ------------------------------------------------------------------------------------------------------------------------------------------- -=== Configure SQLite Database +=== Configuring a Database -Rails comes with built-in support for SQLite, which is a lightweight flat-file based database application. While it is not designed for a production environment, it works well for development and testing. Rails defaults to SQLite as the database adapter when creating a new project, but you can always change it later. +Just about every Rails application will interact with a database. The database to use is specified in a configuration file, +config/database.yml+. +If you open this file in a new Rails application, you'll see a default database configuration using SQLite. The file contains sections for three different environments in which Rails can run by default: -Open up +config/database.yml+ and you'll see the following: +* The +development+ environment is used on your development computer as you interact manually with the application +* The +test+ environment is used to run automated tests +* The +production+ environment is used when you deploy your application for the world to use. --------------------------------------------------------------------- -# SQLite version 3.x -# gem install sqlite3-ruby (not necessary on OS X Leopard) +==== Configuring a SQLite Database + +Rails comes with built-in support for SQLite, which is a lightweight flat-file based database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later. + +Here's the section of the default configuration file with connection information for the development environment: + +[source, ruby] +------------------------------------------------------- development: adapter: sqlite3 database: db/development.sqlite3 timeout: 5000 +------------------------------------------------------- -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - adapter: sqlite3 - database: db/test.sqlite3 - timeout: 5000 - -production: - adapter: sqlite3 - database: db/production.sqlite3 - timeout: 5000 --------------------------------------------------------------------- +If you don't have any database set up, SQLite is the easiest to get installed. If you're on OS X 10.5 or greater on a Mac, you already have it. Otherwise, you can install it using RubyGems: If you're not running OS X 10.5 or greater, you'll need to install the SQLite gem. Similar to installing Rails you just need to run: -`gem install sqlite3-ruby` +[source, shell] +------------------------------------------------------- +$ gem install sqlite3-ruby +------------------------------------------------------- -Because we're using SQLite, there's really nothing else you need to do to setup your database! +==== Configuring a MySQL Database -=== Configure MySQL Database +If you choose to use MySQL, your +config/database.yml+ will look a little different. Here's the development section: -.MySQL Tip -******************************* -If you want to skip directly to using MySQL on your development machine, typing the following will get you setup with a MySQL configuration file that assumes MySQL is running locally and that the root password is blank: - -`rails blog -d mysql` - -You'll need to make sure you have MySQL up and running on your system with the correct permissions. MySQL installation and configuration is outside the scope of this document. -******************************* - -If you choose to use MySQL, your +config/database.yml+ will look a little different: - --------------------------------------------------------------------- -# MySQL. Versions 4.1 and 5.0 are recommended. -# -# Install the MySQL driver: -# gem install mysql -# On Mac OS X: -# sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql -# On Mac OS X Leopard: -# sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config -# This sets the ARCHFLAGS environment variable to your native architecture -# On Windows: -# gem install mysql -# Choose the win32 build. -# Install MySQL and put its /bin directory on your path. -# -# And be sure to use new-style password hashing: -# http://dev.mysql.com/doc/refman/5.0/en/old-client.html +[source, ruby] +------------------------------------------------------- development: adapter: mysql encoding: utf8 @@ -119,92 +214,144 @@ development: username: root password: socket: /tmp/mysql.sock +------------------------------------------------------- +If your development computer's MySQL installation includes a root user with an empty password, this configuration should work for you. Otherwise, change the username and password in the +development+ section as appropriate. -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - adapter: mysql - encoding: utf8 - database: blog_test - username: root - password: - socket: /tmp/mysql.sock +==== Configuring a PostgreSQL Database -production: - adapter: mysql - encoding: utf8 - database: blog_production - username: root +If you choose to use PostgreSQL, your +config/database.yml+ will be customized to use PostgreSQL databases: + +[source, ruby] +------------------------------------------------------- +development: + adapter: postgresql + encoding: unicode + database: blog_development + username: blog password: - socket: /tmp/mysql.sock ----------------------------------------------------------------------- +------------------------------------------------------- -== Starting the web server -Rails comes bundled with the lightweight Webrick web server, which (like SQLite) works great in development mode, but is not designed for a production environment. If you install Mongrel with `gem install mongrel`, Rails will use the Mongrel web server as the default instead (recommended). -******************* -If you're interested in alternative web servers for development and/or production, check out mod_rails (a.k.a Passenger) -******************* -Rails lets you run in development, test, and production environments (you can also add an unlimited number of additional environments if necessary). In this guide, we're going to work with the development environment only, which is the default when starting the server. From the root of your application folder, simply type the following to startup the web server: +Change the username and password in the +development+ section as appropriate. -`./script/server` +== Hello, Rails! -This will start a process that allows you to connect to your application via a web browser on port 3000. Open up a browser to +http://localhost:3000/+ +One of the traditional places to start with a new language is by getting some text up on screen quickly. To do that in Rails, you need to create at minimum a controller and a view. Fortunately, you can do that in a single command. Enter this command in your terminal: -You can hit Ctrl+C anytime from the terminal to stop the web server. +[source, shell] +------------------------------------------------------- +$ script/generate controller home index +------------------------------------------------------- -You should see the "Welcome Aboard" default Rails screen, and can click on the "About your application's environment" link to see a brief summary of your current configuration. If you've gotten this far, you're riding rails! Let's dive into the code! +TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +script+ commands to Ruby: +ruby script/generate controller home index+. -== Models, Views, and Controllers -Rails uses Model, View, Controller (MVC) architecture because it isolates business logic from the user interface, ensuring that changes to a template will not affect the underlying code that makes it function. It also helps keep your code clean and DRY (Don't Repeat Yourself!) by making it perfectly clear where different types of code belong. +Rails will create several files for you, including +app/views/home/index.html.erb+. This is the template that will be used to display the results of the +index+ action (method) in the +home+ controller. Open this file in your text editor and edit it to contain a single line of code: -=== The Model -The model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. Assume that for every table in your database, you will have a corresponding model (not necessarily the other way around, but that's beyond the scope of this guide). +[source, html] +------------------------------------------------------- +<h1>Hello, Rails!</h1> +------------------------------------------------------- -Models in Rails use a singular name, and their corresponding database tables use a plural name. In the case of our "Blog" application, we're going to need a table for our blog posts. Because we're generating a model, we want to use the singular name: +=== Starting up the Web Server -`./script/generate model Post` +You actually have a functional Rails application already - after running only two commands! To see it, you need to start a web server on your development machine. You can do this by running another command: -You'll see that this generates several files, we're going to focus on two. First, let's take a look at +app/models/post.rb+ +[source, shell] +------------------------------------------------------- +$ script/server +------------------------------------------------------- -------------------------------- -class Post < ActiveRecord::Base -end -------------------------------- +This will fire up the lightweight Webrick web server by default. To see your application in action, open a browser window and navigate to +http://localhost:3000+. You should see Rails' default information page: -This is what each model you create will look like by default. Here Rails is making the assumption that your Post model will be tied to a database, because it is telling the Post class to descend from the ActiveRecord::Base class, which is where all the database magic happens. Let's leave the model alone for now and move onto migrations. +image:images/rails_welcome.png[Welcome Aboard screenshot] -==== Migrations -Database migrations make it simple to add/remove/modify tables, columns, and indexes while allowing you to roll back or forward between states with ease. +TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. In development mode, Rails does not generally require you to stop the server; changes you make in files will be automatically picked up by the server. -Have a look at +db/migrate/2008XXXXXXXXXX_create_posts.rb+ (Yours will have numbers specific to the time that the file was generated), which was generated when creating our Post model: +The "Welcome Aboard" page is the smoke test for a new Rails application: it makes sure that you have your software configured correctly enough to serve a page. To view the page you just created, navigate to +http://localhost:3000/home/index+. -------------------------------------------- -class CreatePosts < ActiveRecord::Migration - def self.up - create_table :posts do |t| +=== Setting the Application Home Page - t.timestamps - end - end +You'd probably like to replace the "Welcome Aboard" page with your own application's home page. The first step to doing this is to delete the default page from your application: - def self.down - drop_table :posts - end -end -------------------------------------------- +[source, shell] +------------------------------------------------------- +$ rm public/index.html +------------------------------------------------------- + +Now, you have to tell Rails where your actual home page is located. Open the file +config/routes.rb+ in your editor. This is your application's, _routing file_, which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. At the bottom of the file you'll see the _default routes_: + +[source, ruby] +------------------------------------------------------- +map.connect ':controller/:action/:id' +map.connect ':controller/:action/:id.:format' +------------------------------------------------------- + +The default routes handle simple requests such as +/home/index+: Rails translates that into a call to the +index+ action in the +home+ controller. As another example, +/posts/edit/1+ would run the +edit+ action in the +posts+ controller with an +id+ of 1. + +To hook up your home page, you need to add another line to the routing file, above the default routes: + +[source, ruby] +------------------------------------------------------- +map.root :controller => "home" +------------------------------------------------------- + +This line illustrates one tiny bit of the "convention over configuration" approach: if you don't specify an action, Rails assumes the +index+ action. + +Now if you navigate to +http://localhost:3000+ in your browser, you'll see the +home/index+ view. + +NOTE: For more information about routing, refer to link:../routing/routing_outside_in.html[Rails Routing from the Outside In]. + +== Getting Up and Running Quickly With Scaffolding + +Rails _scaffolding_ is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job. + +== Creating a Resource -By default, Rails creates a database migration that will create the table for "posts" (plural name of model). The +create_table+ method takes a ruby block, and by default you'll see +t.timestamps+ in there, which automatically creates and automatically handles +created_at+ and +updated_at+ datetime columns. The +self.up+ section handles progression of the database, whereas the +self.down+ handles regression (or rollback) of the migration. +In the case of the blog application, you can start by generating a scaffolded Post resource: this will represent a single blog posting. To do this, enter this command in your terminal: -Let's add some more columns to our migration that suit our post table. We'll create a +name+ column for the person who wrote the post, a +title+ column for the title of the post, and a +content+ column for the actual post content. +[source, shell] +------------------------------------------------------- +$ script/generate scaffold Post name:string title:string content:text +------------------------------------------------------- -------------------------------------------- +NOTE: While scaffolding will get you up and running quickly, the "one size fits all" code that it generates is unlikely to be a perfect fit for your application. In most cases, you'll need to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch. + +The scaffold generator will build 13 files in your application, along with some folders, and edit one more. Here's a quick overview of what it creates: + +[grid="all"] +`---------------------------------------------`-------------------------------------------------------------------------------------------- +File Purpose +------------------------------------------------------------------------------------------------------------------------------------------ +app/models/post.rb The Post model +db/migrate/20081013124235_create_posts.rb Migration to create the posts table in your database (your name will include a different timestamp) +app/views/posts/index.html.erb A view to display an index of all posts +app/views/posts/show.html.erb A view to display a single post +app/views/posts/new.html.erb A view to create a new post +app/views/posts/edit.html.erb A view to edit an existing post +app/views/layouts/posts.html.erb A view to control the overall look and feel of the other posts views +public/stylesheets/scaffold.css Cascading style sheet to make the scaffolded views look better +app/controllers/posts_controller.rb The Posts controller +test/functional/posts_controller_test.rb Functional testing harness for the posts controller +app/helpers/posts_helper.rb Helper functions to be used from the posts views +config/routes.rb Edited to include routing information for posts +test/fixtures/posts.yml Dummy posts for use in testing +test/unit/post_test.rb Unit testing harness for the posts model +------------------------------------------------------------------------------------------------------------------------------------------- + +=== Running a Migration + +One of the products of the +script/generate scaffold+ command is a _database migration_. Migrations are Ruby classes that are designed to make it simple to create and modify database tables. Rails uses rake commands to run migrations, and it's possible to undo a migration after it's been applied to your database. Migration filenames include a timestamp to ensure that they're processed in the order that they were created. + +If you look in the +db/migrate/20081013124235_create_posts.rb+ file (remember, yours will have a slightly different name), here's what you'll find: + +[source, ruby] +------------------------------------------------------- class CreatePosts < ActiveRecord::Migration def self.up create_table :posts do |t| - t.string :name - t.string :title - t.text :content + t.string :name + t.string :title + t.text :content + t.timestamps end end @@ -213,77 +360,107 @@ class CreatePosts < ActiveRecord::Migration drop_table :posts end end -------------------------------------------- +------------------------------------------------------- -Now that we have our migration just right, we can run the migration (the +self.up+ portion) by returning to the terminal and running: +If you were to translate that into words, it says something like: when this migration is run, create a table named +posts+ with two string columns (+name+ and +title+) and a text column (+content+), and generate timestamp fields to track record creation and updating. You can learn the detailed syntax for migrations in the link:../migrations/migrations.html[Rails Database Migrations] guide. -`rake db:migrate` +At this point, you need to do two things: create the database and run the migration. You can use rake commands at the terminal for both of those tasks: -This command will always run any migrations that have not yet been run. +[source, shell] +------------------------------------------------------- +$ rake db:create +$ rake db:migrate +------------------------------------------------------- -.Singular and Plural Inflections -************************************************************************************************************** -Rails is very smart, it knows that if you have a model "Person," the database table should be called "people". If you have a model "Company", the database table will be called "companies". There are a few circumstances where it will not know the correct singular and plural of a model name, but you should have no problem with this as long as you are using common English words. Fixing these rare circumstances is beyond the scope of this guide. -************************************************************************************************************** +NOTE: Because you're working in the development environment by default, both of these commands will apply to the database defined in the +development+ section of your +config/database.yml+ file. -=== The Controller -The controller communicates input from the user (the view) to the model. +=== Adding a Link -==== RESTful Design -The REST idea will likely take some time to wrap your brain around if you're new to the concept. But know the following: +To hook the posts up to the home page you've already created, you can add a link to the home page. Open +/app/views/home/index.html.erb+ and modify it as follows: -* It is best to keep your controllers RESTful at all times if possible -* Resources must be defined in +config/routes.rb+ in order for the RESTful architecture to work properly, so let's add that now: +[source, ruby] +------------------------------------------------------- +<h1>Hello, Rails!</h1> --------------------- -map.resources :posts --------------------- +<%= link_to "My Blog", posts_path %> +------------------------------------------------------- -* The seven actions that are automatically part of the RESTful design in Rails are +index+, +show+, +new+, +create+, +edit+, +update+, and +destroy+. +The +link_to+ method is one of Rails' built-in view helpers. It creates a hyperlink based on text to display and where to go - in this case, to the path for posts. -Let's generate a controller: +=== Working with Posts in the Browser -`./script/generate controller Posts` +Now you're ready to start working with posts. To do that, navigate to +http://localhost:3000+ and then click the "My Blog" link: -Open up the controller that it generates in +app/controllers/posts_controller.rb+. It should look like: +image:images/posts_index.png[Posts Index screenshot] ---------------------------------------------- -class PostsController < ApplicationController -end ---------------------------------------------- +This is the result of Rails rendering the +index+ view of your posts. There aren't currently any posts in the database, but if you click the +New Post+ link you can create one. After that, you'll find that you can edit posts, look at their details, or destroy them. All of the logic and HTML to handle this was built by the single +script/generate scaffold+ command. + +TIP: In development mode (which is what you're working in by default), Rails reloads your application with every browser request, so there's no need to stop and restart the web server. + +Congratulations, you're riding the rails! Now it's time to see how it all works. + +=== The Model + +The model file, +app/models/post.rb+ is about as simple as it can get: -Because of the +map.resources :posts+ line in your +config/routes.rb+ file, this controller is ready to take on all seven actions listed above. But we're going to need some logic in this controller in order to interact with the model, and we're going to need to generate our view files so the user can interact with your application from their browser. +[source, ruby] +------------------------------------------------------- +class Post < ActiveRecord::Base +end +------------------------------------------------------- -We're going to use the scaffold generator to create all the files and basic logic to make this work, now that you know how to generate models and controllers manually. +There isn't much to this file - but note that the +Post+ class inherits from +ActiveRecord::Base+. Active Record supplies a great deal of functionality to your Rails models for free, including basic database CRUD (Create, Read, Update, Destroy) operations, data validation, as well as sophisticated search support and the ability to relate multiple models to one another. -To do that, let's completely start over. Back out of your Rails project folder, and *remove it completely* (`rm -rf blog`). -Create the project again and enter the directory by running the commands: +=== Adding Some Validation -`rails blog` +Rails includes methods to help you validate the data that you send to models. Open the +app/models/post.rb+ file and edit it: -`cd blog` +[source, ruby] +------------------------------------------------------- +class Comment < ActiveRecord::Base + belongs_to :post + validates_presence_of :commenter, :body + validates_length_of :commenter, :minimum => 5 +end +------------------------------------------------------- +These changes will ensure that all comments have a body and a commenter, and that the commenter is at least five characters long. Rails can validate a variety of conditions in a model, including the presence or uniqueness of columns, their format, and the existence of associated objects. -=== Rails Scaffold -Whenever you are dealing with a resource and you know you'll need a way to manage that resource in your application, you can start by generating a scaffold. The reason that this guide did not start with generating the scaffold is because it is not all that useful once you are using Rails on a regular basis. For our blog, we want a "Post" resource, so let's generate that now: +=== Using the Console -`./script/generate scaffold Post name:string title:string content:text` +To see your validations in action, you can use the console. The console is a command-line tool that lets you execute Ruby code in the context of your application: -This generates the model, controller, migration, views, tests, and routes for this resource. It also populates these files with default data to get started. +[source, shell] +------------------------------------------------------- +$ script/console +------------------------------------------------------- -First, let's make sure our database is up to date by running `rake db:migrate`. That may generate an error if your database still has the tables from our earlier migration. In this case, let's completely reset the database and run all migrations by running `rake db:reset`. +After the console loads, you can use it to work with your application's models: -Start up the web server with `./script/server` and point your browser to `http://localhost:3000/posts`. +[source, shell] +------------------------------------------------------- +>> c = Comment.create(:body => "A new comment") +=> #<Comment id: nil, commenter: nil, body: "A new comment", +post_id: nil, created_at: nil, updated_at: nil> +>> c.save +=> false +>> c.errors +=> #<ActiveRecord::Errors:0x227be7c @base=#<Comment id: nil, +commenter: nil, body: "A new comment", post_id: nil, created_at: nil, +updated_at: nil>, @errors={"commenter"=>["can't be blank", +"is too short (minimum is 5 characters)"]}> +------------------------------------------------------- -Here you'll see an example of the instant gratification of Rails where you can completely manage the Post resource. You'll be able to create, edit, and delete blog posts with ease. Go ahead, try it out. +This code shows creating a new +Comment+ instance, attempting to save it and getting +false+ for a return value (indicating that the save failed), and inspecting the +errors+ of the comment. -Now let's see how all this works. Open up `app/controllers/posts_controller.rb`, and you'll see this time it is filled with code. +TIP: Unlike the development web server, the console does not automatically load your code afresh for each line. If you make changes, type +reload!+ at the console prompt to load them. -==== Index +=== Listing All Posts -Let's take a look at the `index` action: +The easiest place to start looking at functionality is with the code that lists all posts. Open the file +app/controllers/posts_controller.rb + and look at the +index+ action: ------------------------------------------ +[source, ruby] +------------------------------------------------------- def index @posts = Post.find(:all) @@ -292,34 +469,83 @@ def index format.xml { render :xml => @posts } end end ------------------------------------------ +------------------------------------------------------- -In this action, we're setting the `@posts` instance variable to a hash of all posts in the database. `Post.find(:all)` or `Post.all` (in Rails 2.1) calls on our model to return all the Posts in the database with no additional conditions. +This code sets the +@posts+ instance variable to an array of all posts in the database. +Post.find(:all)+ or +Post.all+ calls the +Post+ model to return all of the posts that are currently in the database, with no limiting conditions. -The `respond_to` block handles both HTML and XML calls to this action. If we call `http://localhost:3000/posts.xml`, we'll see all our posts in XML format. The HTML format looks for our corresponding view in `app/views/posts/index.html.erb`. You can add any number of formats to this block to allow actions to be processed with different file types. +TIP: For more information on finding records with Active Record, see link:../activerecord/finders.html[Active Record Finders]. -==== Show +The +respond_to+ block handles both HTML and XML calls to this action. If you borwse to +http://localhost:3000/posts.xml+, you'll see all of the posts in XML format. The HTML format looks for a view in +app/views/posts/+ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's +app/view/posts/index.html.erb+: -Back in your browser, click on the "New post" link and create your first post if you haven't done so already. Return back to the index, and you'll see the details of your post listed, along with three actions to the right of the post: `show`, `edit`, and `destroy`. Click the `show` link, which will bring you to the URL `http://localhost:3000/posts/1`. Now let's look at the `show` action in `app/controllers/posts_controller.rb`: +[source, ruby] +------------------------------------------------------- +<h1>Listing posts</h1> ------------------------------------------ -def show - @post = Post.find(params[:id]) +<table> + <tr> + <th>Name</th> + <th>Title</th> + <th>Content</th> + </tr> - respond_to do |format| - format.html # show.html.erb - format.xml { render :xml => @post } - end -end ------------------------------------------ +<% for post in @posts %> + <tr> + <td><%=h post.name %></td> + <td><%=h post.title %></td> + <td><%=h post.content %></td> + <td><%= link_to 'Show', post %></td> + <td><%= link_to 'Edit', edit_post_path(post) %></td> + <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td> + </tr> +<% end %> +</table> + +<br /> + +<%= link_to 'New post', new_post_path %> +------------------------------------------------------- + +This view iterates over the contents of the +@posts+ array to display content and links. A few things to note in the view: + +* +h+ is a Rails helper method to sanitize displayed data, preventing cross-site scripting attacks +* +link_to+ builds a hyperlink to a particular destination +* +edit_post_path+ is a helper that Rails provides as part of RESTful routing. You’ll see a variety of these helpers for the different actions that the controller includes. + +TIP: For more details on the rendering process, see link:../actionview/layouts_and_rendering.html[Layouts and Rendering in Rails]. + +=== Customizing the Layout -This time, we're setting `@post` to a single record in the database that is searched for by its `id`, which is provided to the controller by the "1" in `http://localhost:3000/posts/1`. The `show` action is ready to handle HTML or XML with the `respond_to` block: XML can be accessed at: `http://localhost:3000/posts/1.xml`. +The view is only part of the story of how HTML is displayed in your web browser. Rails also has the concept of +layouts+, which are containers for views. When Rails renders a view to the browser, it does so by putting the view's HTML into a layout's HTML. The +script/generate scaffold+ command automatically created a default layout, +app/views/layouts/posts.html.erb+, for the posts. Open this layout in your editor and modify the +body+ tag: -==== New & Create +[source, ruby] +------------------------------------------------------- +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -In your controller, you'll see the `new` and `create` actions, which are used together to create a new record. Our `new` action simply instantiates a new Post object without any parameters: +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> + <title>Posts: <%= controller.action_name %></title> + <%= stylesheet_link_tag 'scaffold' %> +</head> +<body style="background: #EEEEEE;"> ------------------------------------------ +<p style="color: green"><%= flash[:notice] %></p> + +<%= yield %> + +</body> +</html> +------------------------------------------------------- + +Now when you refresh the +/posts+ page, you'll see a gray background to the page. This same gray background will be used throughout all the views for posts. + +=== Creating New Posts + +Creating a new post involves two actions. The first is the +new+ action, which instantiates an empty +Post+ object: + +[source, ruby] +------------------------------------------------------- def new @post = Post.new @@ -328,16 +554,45 @@ def new format.xml { render :xml => @post } end end ----------------------------------------- +------------------------------------------------------- + +The +new.html.erb+ view displays this empty Post to the user: + +[source, ruby] +------------------------------------------------------- +<h1>New post</h1> -Our `create` action, on the other hand, instantiates a new Post object while setting its attributes to the parameters that we specify in our form. It then uses a `flash[:notice]` to inform the user of the status of the action. If the Post is saved successfully, the action will redirect to the `show` action containing our new Post simply by calling the simple `redirect_to(@post)`. +<% form_for(@post) do |f| %> + <%= f.error_messages %> -.The Flash -************************************************************************************************************** -Rails provides the Flash so that messages can be carried over to another action, providing the user with useful information on the status of their request. In our `create` example, the user never actually sees any page rendered during the Post creation process, because it immediately redirects to the new Post as soon as the record is saved. The Flash allows us to carry over a message to the next action, so once the user is redirected back to the `show` action, they are presented with a message saying "Post was successfully created." -************************************************************************************************************** + <p> + <%= f.label :name %><br /> + <%= f.text_field :name %> + </p> + <p> + <%= f.label :title %><br /> + <%= f.text_field :title %> + </p> + <p> + <%= f.label :content %><br /> + <%= f.text_area :content %> + </p> + <p> + <%= f.submit "Create" %> + </p> +<% end %> ----------------------------------------- +<%= link_to 'Back', posts_path %> +------------------------------------------------------- + +The +form_for+ block is used to create an HTML form. Within this block, you have access to methods to build various controls on the form. For example, +f.text_field :name+ tells Rails to create a text input on the form, and to hook it up to the +name+ attribute of the instance being displayed. You can only use these methods with attributes of the model that the form is based on (in this case +name+, +title+, and +content+). Rails uses +form_for+ in preference to having your write raw HTML because the code is more succinct, and because it explicitly ties the form to a particular model instance. + +TIP: If you need to create an HTML form that displays arbitrary fields, not tied to a model, you should use the +form_tag+ method, which provides shortcuts for building forms that are not necessarily tied to a model instance. + +When the user clicks the +Create+ button on this form, the browser will send information back to the +create+ method of the controller (Rails knows to call the +create+ method because the form is sent with an HTTP POST request; that's one of the conventions that I mentioned earlier): + +[source, ruby] +------------------------------------------------------- def create @post = Post.new(params[:post]) @@ -352,20 +607,493 @@ def create end end end ---------------------------------------- +------------------------------------------------------- + +The +create+ action instantiates a new Post object from the data supplied by the user on the form, which Rails makes available in the +params+ hash. After saving the new post, it uses +flash[:notice]+ to create an informational message for the user, and redirects to the show action for the post. If there's any problem, the +create+ action just shows the +new+ view a second time, with any error messages. + +Rails provides the +flash+ hash (usually just called the Flash) so that messages can be carried over to another action, providing the user with useful information on the status of their request. In the case of +create+, the user never actually sees any page rendered during the Post creation process, because it immediately redirects to the new Post as soon Rails saves the record. The Flash carries over a message to the next action, so that when the user is redirected back to the +show+ action, they are presented with a message saying "Post was successfully created." + +=== Showing an Individual Post + +When you click the +show+ link for a post on the index page, it will bring you to a URL like +http://localhost:3000/posts/1+. Rails interprets this as a call to the +show+ action for the resource, and passes in +1+ as the +:id+ parameter. Here's the +show+ action: + +[source, ruby] +------------------------------------------------------- +def show + @post = Post.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @post } + end +end +------------------------------------------------------- + +The +show+ action uses +Post.find+ to search for a single record in the database by its id value. After finding the record, Rails displays it by using +show.html.erb+: + +[source, ruby] +------------------------------------------------------- +<p> + <b>Name:</b> + <%=h @post.name %> +</p> + +<p> + <b>Title:</b> + <%=h @post.title %> +</p> + +<p> + <b>Content:</b> + <%=h @post.content %> +</p> + + +<%= link_to 'Edit', edit_post_path(@post) %> | +<%= link_to 'Back', posts_path %> +------------------------------------------------------- + +=== Editing Posts + +Like creating a new post, editing a post is a two-part process. The first step is a request to +edit_post_path(@post)+ with a particular post. This calls the +edit+ action in the controller: + +[source, ruby] +------------------------------------------------------- +def edit + @post = Post.find(params[:id]) +end +------------------------------------------------------- + +After finding the requested post, Rails uses the +edit.html.erb+ view to display it: + +[source, ruby] +------------------------------------------------------- +<h1>Editing post</h1> + +<% form_for(@post) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :name %><br /> + <%= f.text_field :name %> + </p> + <p> + <%= f.label :title %><br /> + <%= f.text_field :title %> + </p> + <p> + <%= f.label :content %><br /> + <%= f.text_area :content %> + </p> + <p> + <%= f.submit "Update" %> + </p> +<% end %> + +<%= link_to 'Show', @post %> | +<%= link_to 'Back', posts_path %> +------------------------------------------------------- + +Submitting the form created by this view will invoke the +update+ action within the controller: + +[source, ruby] +------------------------------------------------------- +def update + @post = Post.find(params[:id]) + + respond_to do |format| + if @post.update_attributes(params[:post]) + flash[:notice] = 'Post was successfully updated.' + format.html { redirect_to(@post) } + format.xml { head :ok } + else + format.html { render :action => "edit" } + format.xml { render :xml => @post.errors, :status => :unprocessable_entity } + end + end +end +------------------------------------------------------- + +In the +update+ action, Rails first uses the +:id+ parameter passed back from the edit view to locate the database record that's being edited. The +update_attributes+ call then takes the rest of the parameters from the request and applies them to this record. If all goes well, the user is redirected to the post's +show+ view. If there are any problems, it's back to +edit+ to correct them. + +NOTE: Sharp-eyed readers will have noticed that the +form_for+ declaration is identical for the +create+ and +edit+ views. Rails generates different code for the two forms because it's smart enough to notice that in the one case it's being passed a new record that has never been saved, and in the other case an existing record that has already been saved to the database. In a production Rails application, you would ordinarily eliminate this duplication by moving identical code to a _partial template_, which you could then include in both parent templates. But the scaffold generator tries not to make too many assumptions, and generates code that’s easy to modify if you want different forms for +create+ and +edit+. + +=== Destroying a Post + +Finally, clicking one of the +destroy+ links sends the associated id to the +destroy+ action: + +[source, ruby] +------------------------------------------------------- +def destroy + @post = Post.find(params[:id]) + @post.destroy + + respond_to do |format| + format.html { redirect_to(posts_url) } + format.xml { head :ok } + end +end +------------------------------------------------------- + +The +destroy+ method of an Active Record model instance removes the corresponding record from the database. After that's done, there isn't any record to display, so Rails redirects the user's browser to the index view for the model. -==== Edit & Update +== Adding a Second Model -For the `edit`, `update`, and `destroy` actions, we will use the same `@post = Post.find(params[:id])` to find the appropriate record. +Now that you've seen what's in a model built with scaffolding, it's time to add a second model to the application. The second model will handle comments on blog posts. + +=== Generating a Model + +Models in Rails use a singular name, and their corresponding database tables use a plural name. For the model to hold comments, the convention is to use the name Comment. Even if you don't want to use the entire apparatus set up by scaffolding, most Rails developers still use generators to make things like models and controllers. To create the new model, run this command in your terminal: + +[source, shell] +------------------------------------------------------- +$ script/generate model Comment commenter:string body:text post:references +------------------------------------------------------- + +This command will generate four files: + +* +app/models/comment.rb+ - The model +* +db/migrate/20081013214407_create_comments.rb - The migration +* +test/unit/comment_test.rb+ and +test/fixtures/comments.yml+ - The test harness. + +First, take a look at +comment.rb+: + +[source, ruby] +------------------------------------------------------- +class Comment < ActiveRecord::Base + belongs_to :post +end +------------------------------------------------------- -==== Destroy +This is very similar to the +post.rb+ model that you saw earlier. The difference is the line +belongs_to :post+, which sets up an Active Record _association_. You'll learn a little about associations in the next section of this guide. -Description of the destroy action +In addition to the model, Rails has also made a migration to create the corresponding database table: -=== The View -The view is where you put all the code that gets seen by the user: divs, tables, text, checkboxes, etc. Think of the view as the home of your HTML. If done correctly, there should be no business logic in the view. +[source, ruby] +------------------------------------------------------- +class CreateComments < ActiveRecord::Migration + def self.up + create_table :comments do |t| + t.string :commenter + t.text :body + t.references :post + + t.timestamps + end + end + + def self.down + drop_table :comments + end +end +------------------------------------------------------- + +The +t.references+ line sets up a foreign key column for the association between the two models. Go ahead and run the migration: + +[source, shell] +------------------------------------------------------- +$ rake db:migrate +------------------------------------------------------- + +Rails is smart enough to only execute the migrations that have not already been run against this particular database. + +=== Associating Models + +Active Record associations let you declaratively quantify the relationship between two models. In the case of comments and posts, you could write out the relationships this way: + +* Each comment belongs to one post +* One post can have many comments + +In fact, this is very close to the syntax that Rails uses to declare this association. You've already seen the line of code inside the Comment model that makes each comment belong to a Post: + +[source, ruby] +------------------------------------------------------- +class Comment < ActiveRecord::Base + belongs_to :post +end +------------------------------------------------------- + +You'll need to edit the +post.rb+ file to add the other side of the association: + +[source, ruby] +------------------------------------------------------- +class Post < ActiveRecord::Base + has_many :comments +end +------------------------------------------------------- + +These two declarations enable a good bit of automatic behavior. For example, if you have an instance variable +@post+ containing a post, you can retrieve all the comments belonging to that post as the array +@post.comments+. + +TIP: For more information on Active Record associations, see the link:../activerecord/association_basics.html+[Active Record Associations] guide. + +=== Adding a Route + +_Routes_ are entries in the +config/routes.rb+ file that tell Rails how to match incoming HTTP requests to controller actions. Open up that file and find the existing line referring to +posts+. Then edit it as follows: + +[source, ruby] +------------------------------------------------------- +map.resources :posts do |post| + post.resources :comments +end +------------------------------------------------------- + +This creates +comments+ as a _nested resource_ within +posts+. This is another part of capturing the hierarchical relationship that exists between posts and comments. + +TIP: For more information on routing, see the link:../routing/routing_outside_in[Rails Routing from the Outside In] guide. + +=== Generating a Controller + +With the model in hand, you can turn your attention to creating a matching controller. Again, there's a generator for this: + +[source, shell] +------------------------------------------------------- +$ script/generate controller Comments index show new edit +------------------------------------------------------- + +This creates seven files: + +* +app/controllers/comments_controller.rb+ - The controller +* +app/helpers/comments_helper.rb - A view helper file +* +app/views/comments/index.html.erb - The view for the index action +* +app/views/comments/show.html.erb - The view for the show action +* +app/views/comments/new.html.erb - The view for the new action +* +app/views/comments/edit.html.erb - The view for the edit action +* +test/functional/comments_controller_test.rb - The functional tests for the controller + +The controller will be generated with empty methods for each action that you specified in the call to +script/generate controller+: + +[source, ruby] +------------------------------------------------------- +class CommentsController < ApplicationController + def index + end + + def show + end + + def new + end + + def edit + end + +end +------------------------------------------------------- + +You'll need to flesh this out with code to actually process requests appropriately in each method. Here's a version that (for simplicity's sake) only responds to requests that require HTML: + +[source, ruby] +------------------------------------------------------- +class CommentsController < ApplicationController + def index + @post = Post.find(params[:post_id]) + @comments = @post.comments + end + + def show + @post = Post.find(params[:post_id]) + @comment = Comment.find(params[:id]) + end + + def new + @post = Post.find(params[:post_id]) + @comment = @post.comments.build + end + + def create + @post = Post.find(params[:post_id]) + @comment = @post.comments.build(params[:comment]) + if @comment.save + redirect_to post_comment_path(@post, @comment) + else + render :action => "new" + end + end + + def edit + @post = Post.find(params[:post_id]) + @comment = Comment.find(params[:id]) + end + + def update + @post = Post.find(params[:post_id]) + @comment = Comment.find(params[:id]) + if @comment.update_attributes(params[:comment]) + redirect_to post_comment_path(@post, @comment) + else + render :action => "edit" + end + end + +end +------------------------------------------------------- + +You'll see a bit more complexity here than you did in the controller for posts. That's a side-effect of the nesting that you've set up; each request for a comment has to keep track of the post to which the comment is attached. + +=== Building Views + +Because you skipped scaffolding, you'll need to build views for comments "by hand." Invoking +script/generate controller+ will give you skeleton views, but they'll be devoid of actual content. Here's a first pass at fleshing out the comment views. + +The +index.html.erb+ view: + +[source, ruby] +------------------------------------------------------- +<h1>Comments for <%= @post.title %></h1> +<table> + <tr> + <th>Commenter</th> + <th>Body</th> + </tr> + +<% for comment in @comments %> + <tr> + <td><%=h comment.commenter %></td> + <td><%=h comment.body %></td> + <td><%= link_to 'Show', post_comment_path(@post, comment) %></td> + <td><%= link_to 'Edit', edit_post_comment_path(@post, comment) %></td> + <td><%= link_to 'Destroy', post_comment_path(@post, comment), :confirm => 'Are you sure?', :method => :delete %></td> + </tr> +<% end %> +</table> + +<br /> + +<%= link_to 'New comment', new_post_comment_path(@post) %> +<%= link_to 'Back to Post', @post %> +------------------------------------------------------- + +The +new.html.erb+ view: + +[source, ruby] +------------------------------------------------------- +<h1>New comment</h1> + +<% form_for([@post, @comment]) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :commenter %><br /> + <%= f.text_field :commenter %> + </p> + <p> + <%= f.label :body %><br /> + <%= f.text_area :body %> + </p> + <p> + <%= f.submit "Create" %> + </p> +<% end %> + +<%= link_to 'Back', post_comments_path(@post) %> +------------------------------------------------------- + +The +show.html.erb+ view: + +[source, ruby] +------------------------------------------------------- +<h1>Comment on <%= @post.title %></h1> + +<p> + <b>Commenter:</b> + <%=h @comment.commenter %> +</p> + +<p> + <b>Comment:</b> + <%=h @comment.body %> +</p> + +<%= link_to 'Edit', edit_post_comment_path(@post, @comment) %> | +<%= link_to 'Back', post_comments_path(@post) %> +------------------------------------------------------- + +The +edit.html.erb+ view: + +[source, ruby] +------------------------------------------------------- +<h1>Editing comment</h1> + +<% form_for([@post, @comment]) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :commenter %><br /> + <%= f.text_field :commenter %> + </p> + <p> + <%= f.label :body %><br /> + <%= f.text_area :body %> + </p> + <p> + <%= f.submit "Update" %> + </p> +<% end %> + +<%= link_to 'Show', post_comment_path(@post, @comment) %> | +<%= link_to 'Back', post_comments_path(@post) %> +------------------------------------------------------- + +Again, the added complexity here (compared to the views you saw for managing comments) comes from the necessity of juggling a post and its comments at the same time. + +=== Hooking Comments to Posts + +As a final step, I'll modify the +show.html.erb+ view for a post to show the comments on that post, and to allow managing those comments: + +[source, ruby] +------------------------------------------------------- +<p> + <b>Name:</b> + <%=h @post.name %> +</p> + +<p> + <b>Title:</b> + <%=h @post.title %> +</p> + +<p> + <b>Content:</b> + <%=h @post.content %> +</p> + +<h2>Comments</h2> +<% @post.comments.each do |c| %> + <p> + <b>Commenter:</b> + <%=h c.commenter %> + </p> + + <p> + <b>Comment:</b> + <%=h c.body %> + </p> +<% end %> + +<%= link_to 'Edit', edit_post_path(@post) %> | +<%= link_to 'Back', posts_path %> +<%= link_to 'Manage Comments', post_comments_path(@post) %> +------------------------------------------------------- + +Note that each post has its own individual comments collection, accessible as +@post.comments+. That's a consequence of the declarative associations in the models. Path helpers such as +post_comments_path+ come from the nested route declaration in +config/routes.rb+. + +== What's Next? + +Now that you've seen your first Rails application, you should feel free to update it and experiment on your own. But you don't have to do everything without help. As you need assistance getting up and running with Rails, feel free to consult these support resources: + +* The [http://manuals.rubyonrails.org/]Ruby On Rails guides +* The link:http://groups.google.com/group/rubyonrails-talk[Ruby on Rails mailing list] +* The #rubyonrails channel on irc.freenode.net +* The link:http://wiki.rubyonrails.org/rails[Rails wiki] + +== Changelog == +http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/2[Lighthouse ticket] + +* October 16, 2008: Revised based on feedback from Pratik Naik by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) +* October 13, 2008: First complete draft by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) +* October 12, 2008: More detail, rearrangement, editing by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) +* September 8, 2008: initial version by James Miller (not yet approved for publication) diff --git a/railties/doc/guides/index.txt b/railties/doc/guides/index.txt index ad82aea3ec..dfbb3d2799 100644 --- a/railties/doc/guides/index.txt +++ b/railties/doc/guides/index.txt @@ -43,8 +43,6 @@ This guide covers the find method defined in ActiveRecord::Base, as well as name .link:actionview/layouts_and_rendering.html[Layouts and Rendering in Rails] *********************************************************** -CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/15[Lighthouse Ticket] - This guide covers the basic layout features of Action Controller and Action View, including rendering and redirecting, using +content_for_ blocks, and working with partials. @@ -111,7 +109,7 @@ ways of achieving this and how to understand what is happening "behind the scene of your code. *********************************************************** -.link:benchmarking_and_profiling/preamble.html[Benchmarking and Profiling Rails Applications] +.link:benchmarking_and_profiling/index.html[Benchmarking and Profiling Rails Applications] *********************************************************** CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/4[Lighthouse Ticket] diff --git a/railties/doc/guides/routing/routing_outside_in.txt b/railties/doc/guides/routing/routing_outside_in.txt index c3dc60c8bf..ff41bc0257 100644 --- a/railties/doc/guides/routing/routing_outside_in.txt +++ b/railties/doc/guides/routing/routing_outside_in.txt @@ -384,6 +384,8 @@ Routes recognized by this entry would include: NOTE: In most cases, it's simpler to recognize URLs of this sort by creating nested resources, as discussed in the next section. +NOTE: You can also use +:path_prefix+ with non-RESTful routes. + ==== Using :name_prefix You can use the :name_prefix option to avoid collisions between routes. This is most useful when you have two resources with the same name that use +:path_prefix+ to map differently. For example: @@ -396,6 +398,8 @@ map.resources :photos, :path_prefix => '/agencies/:agency_id', :name_prefix => ' This combination will give you route helpers such as +photographer_photos_path+ and +agency_edit_photo_path+ to use in your code. +NOTE: You can also use +:name_prefix+ with non-RESTful routes. + === Nested Resources It's common to have resources that are logically children of other resources. For example, suppose your application includes these models: @@ -435,7 +439,7 @@ PUT /magazines/1/ads/1 Ads update update a specific ad be DELETE /magazines/1/ads/1 Ads destroy delete a specific ad belonging to a specific magazine -------------------------------------------------------------------------------------------- -This will also create routing helpers such as +magazine_ads_url+ and +magazine_edit_ad_path+. +This will also create routing helpers such as +magazine_ads_url+ and +edit_magazine_ad_path+. ==== Using :name_prefix diff --git a/railties/doc/guides/securing_rails_applications/security.txt b/railties/doc/guides/securing_rails_applications/security.txt index f0db7a7ac2..aa1fcf4171 100644 --- a/railties/doc/guides/securing_rails_applications/security.txt +++ b/railties/doc/guides/securing_rails_applications/security.txt @@ -79,7 +79,7 @@ This will also be a good idea, if you modify the structure of an object and old -- _Rails provides several storage mechanisms for the session hashes, the most important are ActiveRecordStore and CookieStore._ -There are a number of session storages, i.e. where Rails saves the session hash and session id. Mot real-live applications choose ActiveRecordStore (or one of its derivatives) over file storage due to performance and maintenance reasons. ActiveRecordStore keeps the session id and hash in a database table and saves and retrieves the hash on every request. +There are a number of session storages, i.e. where Rails saves the session hash and session id. Most real-live applications choose ActiveRecordStore (or one of its derivatives) over file storage due to performance and maintenance reasons. ActiveRecordStore keeps the session id and hash in a database table and saves and retrieves the hash on every request. Rails 2 introduced a new default session storage, CookieStore. CookieStore saves the session hash directly in a cookie on the client-side. The server retrieves the session hash from the cookie and eliminates the need for a session id. That will greatly increase the speed of the application, but it is a controversial storage option and you have to think about the security implications of it: @@ -507,7 +507,7 @@ It is interesting that only 4% of these passwords were dictionary words and the A good password is a long alphanumeric combination of mixed cases. As this is quite hard to remember, it is advisable to enter only the [,#fffcdb]#first letters of a sentence that you can easily remember#. For example "The quick brown fox jumps over the lazy dog" will be "Tqbfjotld". Note that this is just an example, you should not use well known phrases like these, as they might appear in cracker dictionaries, too. === Regular expressions --- _A common pitfall in Ruby's regular expressions is to match the string's end and beginning by $ and ^, instead of \z and \A._ +-- _A common pitfall in Ruby's regular expressions is to match the string's beginning and end by ^ and $, instead of \A and \z._ Ruby uses a slightly different approach to match the end and the beginning of a string. That is why even many Ruby and Rails books make this wrong. So how is this a security threat? Imagine you have a File model and you validate the file name by a regular expression like this: @@ -523,7 +523,7 @@ This means, upon saving, the model will validate the file name to consist only o file.txt%0A<script>alert('hello')</script> .......... -Whereas %0A is a line feed and %0D is a carriage return, in URL encoding. This file name passes the filter because the regular expression matches – up to the line end, the rest does not matter. The correct expression should read: +Whereas %0A is a line feed in URL encoding, so Rails automatically converts it to "file.txt\n<script>alert('hello')</script>". This file name passes the filter because the regular expression matches – up to the line end, the rest does not matter. The correct expression should read: .......... /\A[\w\.\-\+]+\z/ @@ -859,4 +859,4 @@ The security landscape shifts and it is important to keep up to date, because mi - Subscribe to the Rails security http://groups.google.com/group/rubyonrails-security[mailing list] - http://secunia.com/[Keep up to date on the other application layers] (they have a weekly newsletter, too) - A http://ha.ckers.org/blog/[good security blog] including the http://ha.ckers.org/xss.html[Cross-Site scripting Cheat Sheet] -- Another http://www.0x000000.com/[good security blog] with some Cheat Sheets, too
\ No newline at end of file +- Another http://www.0x000000.com/[good security blog] with some Cheat Sheets, too diff --git a/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt b/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt index 11ff2e6a41..dc7635eff9 100644 --- a/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt +++ b/railties/doc/guides/testing_rails_applications/testing_rails_applications.txt @@ -3,55 +3,42 @@ A Guide to Testing Rails Applications This guide covers built-in mechanisms offered by Rails to test your application. By referring to this guide, you will be able to: -* Understand Rails testing terminologies +* Understand Rails testing terminology * Write unit, functional and integration tests for your application -* Read about other popular testing approaches and plugins +* Identify other popular testing approaches and plugins -Assumptions: +This guide won't teach you to write a Rails application; it assumes basic familiarity with the Rails way of doing things. - * You have spent more than 15 minutes in building your first application - * The guide has been written for Rails 2.1 and above +== Why Write Tests for your Rails Applications? == -== Why write tests for your Rails applications? == - - * Since Ruby code that you write in your Rails application is interpreted, you may only find that its broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code and catching syntactical and logic errors. - * Rails tests can also simulate browser requests and thus you can test your applications response without having to test it through your browser. + * Because Ruby code that you write in your Rails application is interpreted, you may only find that it's broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code in advance and catching syntactical and logic errors. + * Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser. * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring. - * Rails makes it super easy to write your tests. Its starts producing skeleton 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 background while you are creating your models and controllers. -== Before you start writing tests == +== Before you Start Writing Tests == -=== The 3 Environments === +Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data. -Testing support was woven into the Rails fabric from the beginning. It wasn't a ``oh! let's bolt on support for running tests because they're new and cool'' epiphany. +=== The 3 Environments === -Each Rails application you build has 3 sides. A side for production, a side for development and a side for testing. +Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. One of the consequences of this design decision is that every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing. -Let's take a closer look at the Rails 'config/database.yml' file. This YAML configuration file has 3 different sections defining 3 unique database setups: +One place you'll find this distinction is in the +config/database.yml+ file. This YAML configuration file has 3 different sections defining 3 unique database setups: * production * development * test -===== Why 3 different databases? ===== - -Well, there's one for testing where you can use sample data, there's one for development where you'll be most of the time as you develop your application, and then production for the ``real deal'', or when it goes live. - -Every new Rails application should have these 3 sections filled out. They should point to different databases. You may end up not having a local database for your production environment, but development and test should both exist and be different. - -===== Why Make This Distinction? ===== - -If you stop and think about it for a second, it makes sense. +This allows you to set up and interact with test data without any danger of your tests altering data from your production environment. -By segregating your development database and your testing database, you're not in any danger of losing any data where it matters. +For example, suppose you need to test your new +delete_this_user_and_every_everything_associated_with_it+ function. Wouldn't you want to run this in an environment where it makes no difference if you destroy data or not? -For example, you need to test your new `delete_this_user_and_every_everything_associated_with_it` function. Wouldn't you want to run this in an environment which makes no difference if you destroy data or not? +When you do end up destroying your testing database (and it will happen, trust me), you can rebuild it from scratch according to the specs defined in the development database. You can do this by running +rake db:test:prepare+. -When you do end up destroying your testing database (and it will happen, trust me), simply run a task in your rakefile to rebuild it from scratch according to the specs defined in the development database. You can do this by running `rake db:test:prepare`. +=== Rails Sets up for Testing from the Word Go === -=== Rails kicks-in right from the word go === - -Rails creates a test folder for you as soon as you initiate a Rails project using `rails application_name`. If you list the contents of this folder then you shall see: +Rails creates a +test+ folder for you as soon as you create a Rails project using +rails _application_name_+. If you list the contents of this folder then you shall see: [source,shell] ------------------------------------------------------ @@ -60,22 +47,25 @@ $ ls -F test/ fixtures/ functional/ integration/ test_helper.rb unit/ ------------------------------------------------------ -The 'unit' folder is meant to hold tests for your models, 'functional' folder is meant to hold tests for your controllers and 'integration' folder is meant to hold tests that involves any number of controllers. Fixtures are a way of organizing data that you want to test against and reside in the 'fixtures' folder. 'test_helper.rb' holds default configuration for your tests. +The +unit+ folder is meant to hold tests for your models, the +functional+ folder is meant to hold tests for your controllers, and the +integration+ folder is meant to hold tests that involve any number of controllers interacting. Fixtures are a way of organizing test data; they reside in the +fixtures+ folder. The +test_helper.rb+ file holds the default configuration for your tests. + +=== The Low-Down on Fixtures === -=== The Lo-Down on Fixtures === +For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures. -==== What They Are ==== +==== What Are Fixtures? ==== -Fixtures is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*. +_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*. -You'll find fixtures under your 'test/fixtures' directory. When you run `script/generate model` to create a new model, fixture stubs will be automatically created and placed in this directory. +You'll find fixtures under your +test/fixtures+ directory. When you run +script/generate model+ to create a new model, fixture stubs will be automatically created and placed in this directory. ==== YAML the Camel is a Mammal with Enamel ==== -YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the *.yml* file extension (as in 'users.yml'). +YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the *.yml* file extension (as in +users.yml+). -On any given day, a YAML fixture file may look like this: +Here's a sample YAML fixture file: +[source,ruby] --------------------------------------------- # low & behold! I am a YAML comment! david: @@ -91,14 +81,15 @@ steve: profession: guy with keyboard --------------------------------------------- -Each fixture is given a 'name' followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments by using the # character in the first column. +Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column. ==== Comma Seperated ==== -Fixtures can also be described using the all-too-familiar comma-separated value file format. These files, just like YAML fixtures are placed in the 'test/fixtures' directory, but these end with the *.csv* file extension (as in 'celebrity_holiday_figures.csv'). +Fixtures can also be described using the all-too-familiar comma-separated value (CSV) file format. These files, just like YAML fixtures, are placed in the 'test/fixtures' directory, but these end with the +.csv+ file extension (as in +celebrity_holiday_figures.csv+). A CSV fixture looks like this: +[source, log] -------------------------------------------------------------- id, username, password, stretchable, comments 1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!"" @@ -108,28 +99,27 @@ id, username, password, stretchable, comments The first line is the header. It is a comma-separated list of fields. The rest of the file is the payload: 1 record per line. A few notes about this format: - * each cell is stripped of outward facing spaces - * if you use a comma as data, the cell must be encased in quotes - * if you use a quote as data, you must escape it with a 2nd quote - * don't use blank lines - * nulls can be achived by just placing a comma, for example, (1,sclaus,,false,) minus the parenthesis of course. + * Leading and trailing spaces are trimmed from each value when it is imported + * If you use a comma as data, the cell must be encased in quotes + * If you use a quote as data, you must escape it with a 2nd quote + * Don't use blank lines + * Nulls can be defined by including no data between a pair of commas -Unlike the YAML format where you give each fixture a name, CSV fixture names are automatically generated. They follow a pattern of ``model-name-counter''. In the above example, you would have: +Unlike the YAML format where you give each record in a fixture a name, CSV fixture names are automatically generated. They follow a pattern of "model-name-counter". In the above example, you would have: --------------------------------------------------------------- -celebrity-holiday-figures-1 -celebrity-holiday-figures-2 -celebrity-holiday-figures-3 --------------------------------------------------------------- +* +celebrity-holiday-figures-1+ +* +celebrity-holiday-figures-2+ +* +celebrity-holiday-figures-3+ The CSV format is great to use if you have existing data in a spreadsheet or database and you are able to save it (or export it) as a CSV. ==== ERb'in It Up ==== -ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb. This allows you to use Ruby to help you generate some sample data. +ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data. I'll demonstrate with a YAML file: +[source, ruby] -------------------------------------------------------------- <% earth_size = 20 -%> mercury: @@ -147,38 +137,32 @@ mars: Anything encased within the -------------- -<% -%> -------------- - -tag is considered Ruby code. To actually print something out, you must use the - -------------- -<%= %> -------------- +[source, ruby] +------------------------ +<% %> +------------------------ -tag. +tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. ==== Fixtures in Action ==== -Rails by default automatically loads all fixtures from the 'test/fixtures' folder for your unit and functional test. Along with which it does 3 things. Let's see an example for 'users' fixture file: - * it nukes any existing data living in the users table - * it loads the fixture data (if any) into the users table - * it dumps the data into a variable in case you want to access it directly +Rails by default automatically loads all fixtures from the 'test/fixtures' folder for your unit and functional test. Loading involves three steps: + + * Remove any existing data from the table corresponding to the fixture + * Load the fixture data into the table + * Dump the fixture data into a variable in case you want to access it directly ==== Hashes with Special Powers ==== -Fixtures are basically Hash objects. As mentioned in point #3 above, you can access the hash object directly because it is automatically setup as a local variable of the test case. +Fixtures are basically Hash objects. As mentioned in point #3 above, you can access the hash object directly because it is automatically setup as a local variable of the test case. For example: [source, ruby] -------------------------------------------------------------- -... - # this will return the Hash for the fixture named david - users(:david) +# this will return the Hash for the fixture named david +users(:david) - # this will return the property for david called id - users(:david).id -... +# this will return the property for david called id +users(:david).id -------------------------------------------------------------- But, by there's another side to fixtures... at night, if the moon is full and the wind completely still, fixtures can also transform themselves into the form of the original class! @@ -187,35 +171,33 @@ Now you can get at the methods only available to that class. [source, ruby] -------------------------------------------------------------- -... - # using the find method, we grab the "real" david as a User - david = users(:david).find +# using the find method, we grab the "real" david as a User +david = users(:david).find - # an now we have access to methods only available to a User class - email( david.girlfriend.email, david.illegitimate_children ) -... +# and now we have access to methods only available to a User class +email(david.girlfriend.email, david.location_tonight) -------------------------------------------------------------- -== Unit tests for your Models == +== Unit Testing Your Models == In Rails, unit tests are what you write to test your models. -When you create a model using `script/generate`, among other things it creates a test stub in the 'test/unit' folder. +When you create a model using +script/generate+, among other things it creates a test stub in the +test/unit+ folder, as well as a fixture for the model: +[source, log] ------------------------------------------------------- $ script/generate model Post ... - create app/models/post.rb - create test/unit/post_test.rb - create test/fixtures/posts.yml +create app/models/post.rb +create test/unit/post_test.rb +create test/fixtures/posts.yml ... ------------------------------------------------------- -The default test stub in 'test/unit/post_test.rb' should look like: +The default test stub in +test/unit/post_test.rb+ looks like this: [source,ruby] -------------------------------------------------- - require 'test_helper' class PostTest < ActiveSupport::TestCase @@ -226,30 +208,48 @@ class PostTest < ActiveSupport::TestCase end -------------------------------------------------- -Let's examine this file line by line so that you have a clear understanding of the involved terminologies. +A line by line examination of this file will help get you oriented to Rails testing code and terminology. -`require 'test_helper'` +[source,ruby] +-------------------------------------------------- +require 'test_helper' +-------------------------------------------------- + +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 that `test_helper.rb` specifies the default configuration to run our tests. This is included with all the tests. Thus any methods added to this file are available to all your tests. +[source,ruby] +-------------------------------------------------- +class PostTest < ActiveSupport::TestCase +-------------------------------------------------- -`class PostTest < ActiveSupport::TestCase` +The +PostTest+ class defines a _test case_ because it inherits from +ActiveSupport::TestCase+. +PostTest+ thus has all the methods available from +ActiveSupport::TestCase+. You'll see those methods a little later in this guide. -Class 'PostTest' is called a test case as it inherits from `ActiveSupport::TestCase`. 'PostTest' thus has all the methods available for ActiveSupport::TestCase. We shall look into the methods available a little later in this guide. +[source,ruby] +-------------------------------------------------- +def test_truth +-------------------------------------------------- -`def test_truth` +Any method defined within a test case that begins with +test+ (case sensitive) is simply called a test. So, +test_password+, +test_valid_password+ and +testValidPassword+ all are legal test names and are run automatically when the test case is run. -Any method defined within a Test Case that begins with 'test' (case sensitive) is simply called a test. So, test_password, test_valid_password and testValidPassword all are legal test names and are run automatically when the test case is run. +[source,ruby] +-------------------------------------------------- +assert true +-------------------------------------------------- -`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: -This line of code is called an assertion. An Assertion is 1 line of code that evaluates an object (or expression) for expected results. For example, is 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? The assert method is available as 'PostTest' inherits from `ActiveSupport::TestCase` +* is 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? -A test consists of 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 the test passes. -=== Running your test === +=== Running Tests === -Running a test is as simple as invoking the file through Ruby. +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 @@ -262,10 +262,11 @@ Finished in 0.023513 seconds. 1 tests, 1 assertions, 0 failures, 0 errors ------------------------------------------------------- -This would run all the test methods from the test case. +This will run all the test methods from the test case. -You could also run a particular test method from the test case by using the `-n` switch with the 'test method name' +You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+. +[source, log] ------------------------------------------------------- $ ruby unit/post_test.rb -n test_truth @@ -277,25 +278,21 @@ 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 a F or if there is an error you see an E in its place. The last line of the output is the summary. +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, lets write a test which reports a failure. +To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case: [source,ruby] -------------------------------------------------- -# test/unit/post_test.rb -... - def test_should_have_atleast_one_post - post = Post.find(:first) - assert_not_nil post - end -... +def test_should_have_atleast_one_post + post = Post.find(:first) + assert_not_nil post +end -------------------------------------------------- -Here I am assuming you have still not added fixture data in posts.yml - -Let's run this test. +If you haven't added any data to the test fixture for posts, this test will fail. You can see this by running it: +[source, log] ------------------------------------------------------- $ ruby unit/post_test.rb Loaded suite unit/post_test @@ -313,21 +310,19 @@ test_should_have_atleast_one_post(PostTest) 2 tests, 2 assertions, 1 failures, 0 errors ------------------------------------------------------- -Above, 'F' denotes a failure and its corresponding trace is shown under '1)' along with the name of the test failing, which is: test_should_have_atleast_one_post(PostTest). The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. Though, it is not highly readable it does provide us with just enough information at most times. To make the assertion failure message more readable every assertion provides an optional message parameter. Let's see the same assertion with a message parameter. +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] -------------------------------------------------- -# test/unit/post_test.rb -... - def test_should_have_atleast_one_post - post = Post.find(:first) - assert_not_nil post, "Should not be nil as Posts table should have atleast one post" - end -... +def test_should_have_atleast_one_post + post = Post.find(:first) + assert_not_nil post, "Should not be nil as Posts table should have atleast one post" +end -------------------------------------------------- -Let's run this test in the console. +Running this test shows the friendlier assertion message: +[source, log] ------------------------------------------------------- $ ruby unit/post_test.rb Loaded suite unit/post_test @@ -346,24 +341,20 @@ Should not be nil as Posts table should have atleast one post. 2 tests, 2 assertions, 1 failures, 0 errors ------------------------------------------------------- -Now you can see an additional message in the test failure report which makes much more sense while troubleshooting. - -To see how an error is reported, let's add a test to our test case that introduces an error. +To see how an error gets reported, here's a test containing an error: [source,ruby] -------------------------------------------------- -# test/unit/post_test.rb -... - def test_should_report_error - # some_undefined_variable is not defined elsewhere in the test case - some_undefined_variable - assert true - end -... +def test_should_report_error + # some_undefined_variable is not defined elsewhere in the test case + some_undefined_variable + assert true +end -------------------------------------------------- -Let's run this test in our console. +Now you can see even more output in the console from running the tests: +[source, log] ------------------------------------------------------- $ ruby unit/post_test.rb Loaded suite unit/post_test @@ -392,128 +383,86 @@ NameError: undefined local variable or method `some_undefined_variable' for #<Po Notice the 'E' in the output. It denotes a test with error. -A thing to note here is that the execution of the test method is stopped as soon as an 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 probably break. Its a good practice to have a test for each of your validations and at least 1 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 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 [msg] is an optional string message you can specify to make your test failure messages clearer. It's not required. - -`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`. +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. -`assert_respond_to( obj, symbol, [msg] )`:: -Ensures that obj has a method called symbol. +=== What to Include in Your Unit Tests === -`assert_operator( obj1, operator, obj2, [msg] )`:: -Ensures that `obj1.operator(obj2)` is true. +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. -`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? +TIP: Many Rails developers practice _test-driven development_ (TDD), in which the tests are written _before_ the code that they are testing. This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with link:http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html[15 TDD steps to create a Rails application]. -`flunk( [msg] )`:: -Ensures failure... like me and high school chemistry exams. +=== Assertions Available === -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 has some specialized assertions to make your life easier. +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. -Creating your own assertions is more of an advanced topic we won't cover in this tutorial. +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. +------------------------------------------------------------------------------------------------------------------------------------------ + +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 === -`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)`:: -Assertion 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. +Rails adds some custom assertions of its own to the +test/unit+ framework: -`assert_response(type, message = nil)`:: -Asserts that the response is one of the following types: - * :success - Status code was 200 - * :redirect - Status code was in the 300-399 range - * :missing - Status code was 404 - * :error - Status code was in 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. +[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. +------------------------------------------------------------------------------------------------------------------------------------------ -You would get to see the usage of some of these assertions in the next chapter. +You'll see the usage of some of these assertions in the next chapter. -== Functional tests for your Controllers == +== Functional Tests for Your Controllers == -In Rails, testing various actions of a single controller is termed as writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view. +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? - * were we redirected to the right page? - * were we successfully authenticated? + * 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 -When you use `script/generate` to create a controller, it automatically creates a functional test for that controller in 'test/functional'. Let's create a post controller: +When you use +script/generate+ to create a controller, it automatically creates a functional test for that controller in +test/functional+. For example, if you create a post controller: +[source, shell] ------------------------------------------------------- $ script/generate controller post ... @@ -522,7 +471,7 @@ $ script/generate controller post ... ------------------------------------------------------- -Now if you take a look at the file 'posts_controller_test.rb' in the 'test/functional' directory, you should see: +Now if you take a look at the file +posts_controller_test.rb+ in the +test/functional+ directory, you should see: [source,ruby] -------------------------------------------------- @@ -536,106 +485,107 @@ class PostsControllerTest < ActionController::TestCase end -------------------------------------------------- - -Example functional tests for posts controller: +Of course, you need to replace the simple assertion with real testing. Here's a starting example of a functional test: [source,ruby] -------------------------------------------------- - def test_should_get_index - get :index - assert_response :success - assert_not_nil assigns(:posts) - end +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. -In the test_should_get_index test, we are simulating 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 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. - * The action of the controller you are requesting. It 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 to stash your goulash. - -Example: Calling the :show action, passing an id of 12 as the params and setting user_id of 5 in the session. +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}) +-------------------------------------------------- -Another example: Calling the :view action, passing an id of 12 as the params, this time with no session, but with a flash message. +Another example: Calling the +:view+ action, passing an +id+ of 12 as the +params+, this time with no session, but with a flash message. +[source,ruby] +-------------------------------------------------- get(:view, {'id' => '12'}, nil, {'message' => 'booya!'}) +-------------------------------------------------- -=== Available request types at your disposal === +=== Available Request Types for Functional Tests=== -For those of you familiar with HTTP protocol, you'll know that get is a type of request. There are 5 request types supported in Rails: +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 +* +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 Apocolypse === - -After the request has been made by using one of the 5 methods (get, post, etc…), you will have 4 Hash objects ready for use. - -They are (starring in alphabetical order): +=== The 4 Hashes of the Apocalypse === -`assigns`:: -Any objects that are stored as instance variables in actions for use in views. +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: -`cookies`:: -Any objects cookies that are set. +* +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. -`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 assigns. Check it out: +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) +-------------------------------------------------- + +=== Instance Variables Available === + +You also have access to three instance variables in your functional tests: -=== Instance variables available === +* +@controller+ - The controller processing the request +* +@request+ - The request +* +@response+ - The response - * `@controller` - * `@request` - * `@response` +=== A Fuller Functional Test Example -Another example that uses flash, assert_redirected_to, assert_difference +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] +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 -------------------------------------------------- === Testing Views === -Testing the response to your request by asserting the presence of key html elements and their content is a good practice. `assert_select` allows you to do all this by using a simple yet powerful syntax. +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+. -[NOTE] -`assert_tag` 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(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. ++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: @@ -644,7 +594,7 @@ For example, you could verify the contents on the title element in your response 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. +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] -------------------------------------------------- @@ -653,12 +603,23 @@ assert_select 'ul.navigation' do end -------------------------------------------------- -`assert_select` is really powerful and I would recommend you to go through its http://api.rubyonrails.com/classes/ActionController/Assertions/SelectorAssertions.html#M000749[documentation] for its advanced usage. +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]. -==== Additional view based assertions ==== +==== Additional View-based Assertions ==== -`assert_select_email`:: -Allows you to make assertions on the body of an e-mail. +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. +------------------------------------------------------------------------------------------------------------------------------------------ + +Here's an example of using +assert_select_email+: [source,ruby] -------------------------------------------------- @@ -667,35 +628,26 @@ assert_select_email do end -------------------------------------------------- -`assert_select_rjs`:: -Allows you to make assertions on RJS response. `assert_select_rjs` has variants which allow you to narrow down upon the updated element or event 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)`:: -`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. - == Integration Testing == -Integration tests are used to test interaction among any number of controllers. They are generally used to test important work flows within your application. +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 they have to be explicitly created under the 'test/integration' folder within our application. Rails provides a generator to create an integration test skeleton for you. - -Example: +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. +[source, shell] -------------------------------------------------- -$ script/generate integration_test create_blog_and_then_post_comments +$ script/generate integration_test user_flows exists test/integration/ - create test/integration/create_blog_and_then_post_comments_test.rb + create test/integration/user_flows_test.rb -------------------------------------------------- +Here's what a freshly-generated integration test looks like: + [source,ruby] -------------------------------------------------- require 'test_helper' -class CreateBlogAndThenPostCommentsTest < ActionController::IntegrationTest +class UserFlowsTest < ActionController::IntegrationTest # fixtures :your, :models # Replace this with your real tests. @@ -705,234 +657,238 @@ class CreateBlogAndThenPostCommentsTest < ActionController::IntegrationTest end -------------------------------------------------- -=== Differences in comparison to unit and functional tests === - -* You will have to include fixtures explicitly unlike unit and functional tests in which all the fixtures are loaded by default (through test_helper) -* Additional helpers: https?, https!, host!, follow_redirect!, post/get_via_redirect, open_session, reset +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. -== Rake Tasks for Testing +=== Helpers Available for Integration tests === -The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project. +In addition to the standard testing helpers, there are some additional helpers available to integration tests: -.Default Rake tasks [grid="all"] -------------------------- -Tasks Description -------------------------- -`rake test` Runs all unit, functional and integration tests. You can also simply run `rake` as _test_ target is default. -`rake test:units` Runs all the unit tests from 'test/unit' -`rake test:functionals` Runs all the functional tests from 'test/functional' -`rake test:integration` Runs all the integration tests from 'test/integration' -`rake test:recent` Tests recent changes -`rake test:uncommitted` Runs all the tests which are uncommitted. Only supports Subversion -`rake test:plugins` Run all the plugin tests from vendor/plugins/*/**/test (or specify with `PLUGIN=_name_`) -`rake db:test:clone` Recreate the test database from the current environment's database schema -`rake db:test:clone_structure` Recreate the test databases from the development structure -`rake db:test:load` Recreate the test database from the current schema.rb -`rake db:test:prepare` Check for pending migrations and load the test schema -`rake db:test:purge` Empty the test database. -------------------------- - -TIP: You can see all these rake task and their descriptions by running `rake --tasks --describe` +`----------------------------------------------------------------------------------`------------------------------------------------------- +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 === + +A simple integration test that exercises multiple controllers: -== Testing Your Mailers == +[source,ruby] +-------------------------------------------------- +require 'test_helper' -=== Keeping the postman in check === +class UserFlowsTest < ActionController::IntegrationTest + fixtures :users -Your ActionMailer -- like every other part of your Rails application -- should be tested to ensure that it is working as expected. + 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 +-------------------------------------------------- -The goal of testing your ActionMailer is to ensure that: +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. - * emails are being processed (created and sent) - * the email content is correct (subject, sender, body, etc) - * the right emails are being sent at the righ times +Here's an example of multiple sessions and custom DSL in an integration test -==== From all sides ==== +[source,ruby] +-------------------------------------------------- +require 'test_helper' -There are two aspects of testing your mailer, the unit tests and the functional tests. -Unit tests +class UserFlowsTest < ActionController::IntegrationTest + fixtures :users -In the unit tests, we run the mailer in isolation with tightly controlled inputs and compare the output to a known-value -- a fixture -- yay! more fixtures! + 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 +-------------------------------------------------- -==== Functional tests ==== +== Testing Your Mailers == -In the functional tests we 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. We test to prove that the right email was sent at the right time. +Testing mailer classes requires some specific tools to do a thorough job. -=== Unit Testing === +=== Keeping the Postman in Check === -In order to test that your mailer is working as expected, we can use unit tests to compare the actual results of the mailer with pre-writen examples of what should be produced. +Your +ActionMailer+ classes -- like every other part of your Rails application -- should be tested to ensure that it is working as expected. -==== Revenge of the fixtures ==== +The goals of testing your +ActionMailer+ classes are to ensure that: -For the purposes of unit testing a mailer, fixtures are used to provide an example of how output ``should'' look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory from the other fixtures. Don't tease them about it though, they hate that. +* emails are being processed (created and sent) +* the email content is correct (subject, sender, body, etc) +* the right emails are being sent at the right times -When you generated your mailer (you did that right?) the generator created stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself. +==== From All Sides ==== -==== The basic test case ==== +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. -Here is an example of what you start with. +=== Unit Testing === -[source, ruby] -------------------------------------------------- -require File.dirname(__FILE__) + '/. ./test_helper' +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. -class MyMailerTest < Test::Unit::TestCase - FIXTURES_PATH = File.dirname(__FILE__) + '/. ./fixtures' +==== Revenge of the Fixtures ==== - def setup - ActionMailer::Base.delivery_method = :test - ActionMailer::Base.perform_deliveries = true - ActionMailer::Base.deliveries = [] +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. - @expected = TMail::Mail.new - end +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. - def test_signup - @expected.subject = 'MyMailer#signup' - @expected.body = read_fixture('signup') - @expected.date = Time.now +==== The Basic Test case ==== - assert_equal @expected.encoded, MyMailer.create_signup(@expected.date).encoded - end - - private - def read_fixture(action) - IO.readlines("#{FIXTURES_PATH}/my_mailer/#{action}") - end -end -------------------------------------------------- - -The `setup` method is mostly concerned with setting up a blank slate for the next test. However it is worth describing what each statement does +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. [source, ruby] ------------------------------------------------- -ActionMailer::Base.delivery_method = :test -------------------------------------------------- - -sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (ActionMailer::Base.deliveries). +require 'test_helper' -[source, ruby] -------------------------------------------------- -ActionMailer::Base.perform_deliveries = true -------------------------------------------------- +class UserMailerTest < ActionMailer::TestCase + tests UserMailer + def test_invite + @expected.from = 'me@example.com' + @expected.to = 'friend@example.com' + @expected.subject = "You have been invited by #{@expected.from}" + @expected.body = read_fixture('invite') + @expected.date = Time.now -Ensures the mail will be sent using the method specified by ActionMailer::Base.delivery_method, and finally + assert_equal @expected.encoded, UserMailer.create_invite('me@example.com', 'friend@example.com', @expected.date).encoded + end -[source, ruby] -------------------------------------------------- -ActionMailer::Base.deliveries = [] +end ------------------------------------------------- -sets the array of sent messages to an empty array so we can be sure that anything we find there was sent as part of our current test. +In this test, +@expected+ is an instance of +TMail::Mail+ that you can use in your tests. It is defined in +ActionMailer::TestCase+. The test above uses +@expected+ to construct an email, which it then asserts with email created by the custom mailer. The +invite+ fixture is the body of the email and is used as the sample content to assert against. The helper +read_fixture+ is used to read in the content from this file. -However often in unit tests, mails will not actually be sent, simply constructed, as in the example above, where the precise content of the email is checked against what it should be. Dave Thomas suggests an alternative approach, which is just to check the part of the email that is likely to break, i.e. the dynamic content. The following example assumes we have some kind of user table, and we might want to mail those users new passwords: +Here's the content of the +invite+ fixture: -[source, ruby] +[source, log] ------------------------------------------------- -require File.dirname(__FILE__) + '/../test_helper' -require 'my_mailer' - -class MyMailerTest < Test::Unit::TestCase - fixtures :users - FIXTURES_PATH = File.dirname(__FILE__) + '/../fixtures' - CHARSET = "utf-8" - - include ActionMailer::Quoting - - def setup - ActionMailer::Base.delivery_method = :test - ActionMailer::Base.perform_deliveries = true - ActionMailer::Base.deliveries = [] - - @expected = TMail::Mail.new - @expected.set_content_type "text", "plain", { "charset" => CHARSET } - end - - def test_reset_password - user = User.find(:first) - newpass = 'newpass' - response = MyMailer.create_reset_password(user,newpass) - assert_equal 'Your New Password', response.subject - assert_match /Dear #{user.full_name},/, response.body - assert_match /New Password: #{newpass}/, response.body - assert_equal user.email, response.to[0] - end +Hi friend@example.com, - private - def read_fixture(action) - IO.readlines("#{FIXTURES_PATH}/community_mailer/#{action}") - end +You have been invited. - def encode(subject) - quoted_printable(subject, CHARSET) - end -end +Cheers! ------------------------------------------------- -and here we check the dynamic parts of the mail, specifically that we use the users' correct full name and that we give them the correct password. +This is the right time to understand a little more about writing tests for your mailers. The line +ActionMailer::Base.delivery_method = :test+ in +config/environments/test.rb+ sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (+ActionMailer::Base.deliveries+). + +However often in unit tests, mails will not actually be sent, simply constructed, as in the example above, where the precise content of the email is checked against what it should be. === Functional Testing === -Functional testing involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests we 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 -- what we are probably more interested in is whether our own business logic is sending emails when we expect them to. For example the password reset operation we used an example in the previous section will probably be called in response to a user requesting a password reset through some sort of controller. +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: [source, ruby] ---------------------------------------------------------------- -require File.dirname(__FILE__) + '/../test_helper' -require 'my_controller' +require 'test_helper' -# Raise errors beyond the default web-based presentation -class MyController; def rescue_action(e) raise e end; end +class UserControllerTest < ActionController::TestCase + def test_invite_friend + assert_difference 'ActionMailer::Base.deliveries.size', +1 do + post :invite_friend, :email => 'friend@example.com' + end + invite_email = ActionMailer::Base.deliveries.first + + assert_equal invite_email.subject, "You have been invited by me@example.com" + assert_equal invite_email.to[0], 'friend@example.com' + assert_match /Hi friend@example.com/, invite_email.body + end +end +---------------------------------------------------------------- -class MyControllerTest < Test::Unit::TestCase +== Rake Tasks for Testing - def setup - @controller = MyController.new - @request, @response = ActionController::TestRequest.new, ActionController::TestResponse.new - end +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. - def test_reset_password - num_deliveries = ActionMailer::Base.deliveries.size - post :reset_password, :email => 'bob@test.com' +[grid="all"] +--------------------------------`---------------------------------------------------- +Tasks Description +------------------------------------------------------------------------------------ ++rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default. ++rake test:units+ Runs all the unit tests from +test/unit+ ++rake test:functionals+ Runs all the functional tests from +test/functional+ ++rake test:integration+ Runs all the integration tests from +test/integration+ ++rake test:recent+ Tests recent changes ++rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion ++rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+) ++rake db:test:clone+ Recreate the test database from the current environment's database schema ++rake db:test:clone_structure+ Recreate the test databases from the development structure ++rake db:test:load+ Recreate the test database from the current +schema.rb+ ++rake db:test:prepare+ Check for pending migrations and load the test schema ++rake db:test:purge+ Empty the test database. +------------------------------------------------------------------------------------ - assert_equal num_deliveries+1, ActionMailer::Base.deliveries.size - end +TIP: You can see all these rake task and their descriptions by running +rake --tasks --describe+ -end ----------------------------------------------------------------- +== Other Testing Approaches -=== Filtering emails in development === +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: -Sometimes you want to be somewhere inbetween the `:test` and `:smtp` settings. Say you're working on your development site, and you have a few testers working with you. The site isn't in production yet, but you'd like the testers to be able to receive emails from the site, but no one else. Here's a handy way to handle that situation, add this to your 'environment.rb' or 'development.rb' file +* link:http://avdi.org/projects/nulldb/[NullDB], a way to speed up testing by avoiding database use. +* link:http://github.com/thoughtbot/factory_girl/tree/master[Factory Girl], as replacement for fixtures. +* link:http://www.thoughtbot.com/projects/shoulda[Shoulda], an extension to +test/unit+ with additional helpers, macros, and assertions. +* link: http://rspec.info/[RSpec], a behavior-driven development framework -[source, ruby] ----------------------------------------------------------------- -class ActionMailer::Base - - def perform_delivery_fixed_email(mail) - destinations = mail.destinations - if destinations.nil? - destinations = ["mymail@me.com"] - mail.subject = '[TEST-FAILURE]:'+mail.subject - else - mail.subject = '[TEST]:'+mail.subject - end - approved = ["testerone@me.com","testertwo@me.com"] - destinations = destinations.collect{|x| approved.collect{|y| (x==y ? x : nil)}}.flatten.compact - mail.to = destinations - if destinations.size > 0 - mail.ready_to_send - Net::SMTP.start(server_settings[:address], server_settings[:port], server_settings[:domain], - server_settings[:user_name], server_settings[:password], server_settings[:authentication]) do |smtp| - smtp.sendmail(mail.encoded, mail.from, destinations) - end - end +== Changelog == - end +http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8[Lighthouse ticket] -end ----------------------------------------------------------------- +* October 14, 2008: Edit and formatting pass by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) +* October 12, 2008: First draft by link:../authors.html#asurve[Akashay Surve] (not yet approved for publication) -== Guide TODO == - * Describe _setup_ and _teardown_ - * Examples for integration test - * Updating the section on testing mailers diff --git a/railties/environments/environment.rb b/railties/environments/environment.rb index abdb863130..f27ccc6bb8 100644 --- a/railties/environments/environment.rb +++ b/railties/environments/environment.rb @@ -22,8 +22,10 @@ Rails::Initializer.run do |config| # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. + # You have to specify the <tt>:lib</tt> option for libraries, where the Gem name (<em>sqlite3-ruby</em>) differs from the file itself (_sqlite3_) # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" + # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" # Only load the plugins named here, in the order given. By default, all plugins diff --git a/railties/lib/console_sandbox.rb b/railties/lib/console_sandbox.rb index 5d57679c43..65a3d68619 100644 --- a/railties/lib/console_sandbox.rb +++ b/railties/lib/console_sandbox.rb @@ -1,6 +1,6 @@ -ActiveRecord::Base.send :increment_open_transactions +ActiveRecord::Base.connection.increment_open_transactions ActiveRecord::Base.connection.begin_db_transaction at_exit do ActiveRecord::Base.connection.rollback_db_transaction - ActiveRecord::Base.send :decrement_open_transactions + ActiveRecord::Base.connection.decrement_open_transactions end diff --git a/railties/lib/rails/gem_dependency.rb b/railties/lib/rails/gem_dependency.rb index 3b2f4846a6..80481859e1 100644 --- a/railties/lib/rails/gem_dependency.rb +++ b/railties/lib/rails/gem_dependency.rb @@ -82,6 +82,10 @@ module Rails File.join(base_directory, specification.full_name) end + def spec_filename(base_directory) + File.join(gem_dir(base_directory), '.specification') + end + def load return if @loaded || @load_paths_added == false require(@lib || name) unless @lib == false @@ -108,6 +112,8 @@ module Rails @loaded ||= begin if vendor_rails? true + elsif specification.nil? + false else # check if the gem is loaded by inspecting $" # specification.files lists all the files contained in the gem @@ -144,17 +150,42 @@ module Rails Gem::GemRunner.new.run(unpack_command) end + # Gem.activate changes the spec - get the original + real_spec = Gem::Specification.load(spec.loaded_from) + write_spec(directory, real_spec) + + end + + def write_spec(directory, spec) # copy the gem's specification into GEMDIR/.specification so that # we can access information about the gem on deployment systems # without having the gem installed - spec_filename = File.join(gem_dir(directory), '.specification') - # Gem.activate changes the spec - get the original - spec = Gem::Specification.load(specification.loaded_from) - File.open(spec_filename, 'w') do |file| + File.open(spec_filename(directory), 'w') do |file| file.puts spec.to_yaml end end + def refresh_spec(directory) + real_gems = Gem.source_index.installed_source_index + exact_dep = Gem::Dependency.new(name, "= #{specification.version}") + matches = real_gems.search(exact_dep) + installed_spec = matches.first + if installed_spec + # we have a real copy + # get a fresh spec - matches should only have one element + # note that there is no reliable method to check that the loaded + # spec is the same as the copy from real_gems - Gem.activate changes + # some of the fields + real_spec = Gem::Specification.load(matches.first.loaded_from) + write_spec(directory, real_spec) + puts "Reloaded specification for #{name} from installed gems." + else + # the gem isn't installed locally - write out our current specs + write_spec(directory, specification) + puts "Gem #{name} not loaded locally - writing out current spec." + end + end + def ==(other) self.name == other.name && self.requirement == other.requirement end diff --git a/railties/lib/rails/mongrel_server/commands.rb b/railties/lib/rails/mongrel_server/commands.rb index 0a92f418ad..d29b18712f 100644 --- a/railties/lib/rails/mongrel_server/commands.rb +++ b/railties/lib/rails/mongrel_server/commands.rb @@ -44,7 +44,7 @@ module Rails env_location = "#{defaults[:cwd]}/config/environment" require env_location - ActionController::AbstractRequest.relative_url_root = defaults[:prefix] + ActionController::Base.relative_url_root = defaults[:prefix] uri prefix, :handler => Rails::MongrelServer::RailsHandler.new end end diff --git a/railties/lib/rails/vendor_gem_source_index.rb b/railties/lib/rails/vendor_gem_source_index.rb index c8701101e2..dc821693ac 100644 --- a/railties/lib/rails/vendor_gem_source_index.rb +++ b/railties/lib/rails/vendor_gem_source_index.rb @@ -13,6 +13,16 @@ module Rails attr_reader :installed_source_index attr_reader :vendor_source_index + @@silence_spec_warnings = false + + def self.silence_spec_warnings + @@silence_spec_warnings + end + + def self.silence_spec_warnings=(v) + @@silence_spec_warnings = v + end + def initialize(installed_index, vendor_dir=Rails::GemDependency.unpacked_path) @installed_source_index = installed_index @vendor_dir = vendor_dir @@ -33,38 +43,75 @@ module Rails # load specifications from vendor/gems Dir[File.join(Rails::GemDependency.unpacked_path, '*')].each do |d| + dir_name = File.basename(d) + dir_version = version_for_dir(dir_name) spec = load_specification(d) - next unless spec - # NOTE: this is a bit of a hack - the gem system expects a different structure - # than we have. - # It's looking for: - # repository - # -> specifications - # - gem_name.spec <= loaded_from points to this - # -> gems - # - gem_name <= gem files here - # and therefore goes up one directory from loaded_from, then adds gems/gem_name - # to the path. - # But we have: - # vendor - # -> gems - # -> gem_name <= gem files here - # - .specification - # so we set loaded_from to vendor/gems/.specification (not a real file) to - # get the correct behavior. - spec.loaded_from = File.join(Rails::GemDependency.unpacked_path, '.specification') + if spec + if spec.full_name != dir_name + # mismatched directory name and gem spec - produced by 2.1.0-era unpack code + if dir_version + # fix the spec version - this is not optimal (spec.files may be wrong) + # but it's better than breaking apps. Complain to remind users to get correct specs. + # use ActiveSupport::Deprecation.warn, as the logger is not set yet + $stderr.puts("config.gem: Unpacked gem #{dir_name} in vendor/gems has a mismatched specification file."+ + " Run 'rake gems:refresh_specs' to fix this.") unless @@silence_spec_warnings + spec.version = dir_version + else + $stderr.puts("config.gem: Unpacked gem #{dir_name} in vendor/gems is not in a versioned directory"+ + "(should be #{spec.full_name}).") unless @@silence_spec_warnings + # continue, assume everything is OK + end + end + else + # no spec - produced by early-2008 unpack code + # emulate old behavior, and complain. + $stderr.puts("config.gem: Unpacked gem #{dir_name} in vendor/gems has no specification file."+ + " Run 'rake gems:refresh_specs' to fix this.") unless @@silence_spec_warnings + if dir_version + spec = Gem::Specification.new + spec.version = dir_version + spec.require_paths = ['lib'] + ext_path = File.join(d, 'ext') + spec.require_paths << 'ext' if File.exist?(ext_path) + spec.name = /^(.*)-[^-]+$/.match(dir_name)[1] + files = ['lib'] + # set files to everything in lib/ + files += Dir[File.join(d, 'lib', '*')].map { |v| v.gsub(/^#{d}\//, '') } + files += Dir[File.join(d, 'ext', '*')].map { |v| v.gsub(/^#{d}\//, '') } if ext_path + spec.files = files + else + $stderr.puts("config.gem: Unpacked gem #{dir_name} in vendor/gems not in a versioned directory."+ + " Giving up.") unless @silence_spec_warnings + next + end + end + spec.loaded_from = File.join(d, '.specification') + # finally, swap out full_gem_path + # it would be better to use a Gem::Specification subclass, but the YAML loads an explicit class + class << spec + def full_gem_path + path = File.join installation_path, full_name + return path if File.directory? path + File.join installation_path, original_name + end + end vendor_gems[File.basename(d)] = spec end @vendor_source_index = Gem::SourceIndex.new(vendor_gems) end + def version_for_dir(d) + matches = /-([^-]+)$/.match(d) + Gem::Version.new(matches[1]) if matches + end + def load_specification(gem_dir) spec_file = File.join(gem_dir, '.specification') YAML.load_file(spec_file) if File.exist?(spec_file) end - def find_name(gem_name, version_requirement = Gem::Requirement.default) - search(/^#{gem_name}$/, version_requirement) + def find_name(*args) + @installed_source_index.find_name(*args) + @vendor_source_index.find_name(*args) end def search(*args) diff --git a/railties/lib/rails_generator/commands.rb b/railties/lib/rails_generator/commands.rb index 59af7308fe..6b9a636847 100644 --- a/railties/lib/rails_generator/commands.rb +++ b/railties/lib/rails_generator/commands.rb @@ -169,6 +169,7 @@ HELP # Ruby or Rails. In the future, expand to check other namespaces # such as the rest of the user's app. def class_collisions(*class_names) + path = class_names.shift class_names.flatten.each do |class_name| # Convert to string to allow symbol arguments. class_name = class_name.to_s diff --git a/railties/lib/rails_generator/generators/components/controller/controller_generator.rb b/railties/lib/rails_generator/generators/components/controller/controller_generator.rb index c37ff45836..77b2220d57 100644 --- a/railties/lib/rails_generator/generators/components/controller/controller_generator.rb +++ b/railties/lib/rails_generator/generators/components/controller/controller_generator.rb @@ -2,7 +2,7 @@ class ControllerGenerator < Rails::Generator::NamedBase def manifest record do |m| # Check for class naming collisions. - m.class_collisions class_path, "#{class_name}Controller", "#{class_name}ControllerTest", "#{class_name}Helper" + m.class_collisions "#{class_name}Controller", "#{class_name}ControllerTest", "#{class_name}Helper" # Controller, helper, views, and test directories. m.directory File.join('app/controllers', class_path) diff --git a/railties/lib/rails_generator/generators/components/integration_test/integration_test_generator.rb b/railties/lib/rails_generator/generators/components/integration_test/integration_test_generator.rb index 90fa96938b..44323f28ca 100644 --- a/railties/lib/rails_generator/generators/components/integration_test/integration_test_generator.rb +++ b/railties/lib/rails_generator/generators/components/integration_test/integration_test_generator.rb @@ -4,7 +4,7 @@ class IntegrationTestGenerator < Rails::Generator::NamedBase def manifest record do |m| # Check for class naming collisions. - m.class_collisions class_path, class_name, "#{class_name}Test" + m.class_collisions class_name, "#{class_name}Test" # integration test directory m.directory File.join('test/integration', class_path) diff --git a/railties/lib/rails_generator/generators/components/mailer/mailer_generator.rb b/railties/lib/rails_generator/generators/components/mailer/mailer_generator.rb index dc1202d7c8..ba6d60cac6 100644 --- a/railties/lib/rails_generator/generators/components/mailer/mailer_generator.rb +++ b/railties/lib/rails_generator/generators/components/mailer/mailer_generator.rb @@ -2,7 +2,7 @@ class MailerGenerator < Rails::Generator::NamedBase def manifest record do |m| # Check for class naming collisions. - m.class_collisions class_path, class_name, "#{class_name}Test" + m.class_collisions class_name, "#{class_name}Test" # Mailer, view, test, and fixture directories. m.directory File.join('app/models', class_path) diff --git a/railties/lib/rails_generator/generators/components/model/model_generator.rb b/railties/lib/rails_generator/generators/components/model/model_generator.rb index 9be9cad8bf..582a28922f 100644 --- a/railties/lib/rails_generator/generators/components/model/model_generator.rb +++ b/railties/lib/rails_generator/generators/components/model/model_generator.rb @@ -4,7 +4,7 @@ class ModelGenerator < Rails::Generator::NamedBase def manifest record do |m| # Check for class naming collisions. - m.class_collisions class_path, class_name, "#{class_name}Test" + m.class_collisions class_name, "#{class_name}Test" # Model, test, and fixture directories. m.directory File.join('app/models', class_path) diff --git a/railties/lib/rails_generator/generators/components/observer/observer_generator.rb b/railties/lib/rails_generator/generators/components/observer/observer_generator.rb index 18fbd32b75..3c4b330a80 100644 --- a/railties/lib/rails_generator/generators/components/observer/observer_generator.rb +++ b/railties/lib/rails_generator/generators/components/observer/observer_generator.rb @@ -2,7 +2,7 @@ class ObserverGenerator < Rails::Generator::NamedBase def manifest record do |m| # Check for class naming collisions. - m.class_collisions class_path, "#{class_name}Observer", "#{class_name}ObserverTest" + m.class_collisions "#{class_name}Observer", "#{class_name}ObserverTest" # Observer, and test directories. m.directory File.join('app/models', class_path) diff --git a/railties/lib/rails_generator/generators/components/performance_test/performance_test_generator.rb b/railties/lib/rails_generator/generators/components/performance_test/performance_test_generator.rb index fbcc1cf683..83ce8ac674 100644 --- a/railties/lib/rails_generator/generators/components/performance_test/performance_test_generator.rb +++ b/railties/lib/rails_generator/generators/components/performance_test/performance_test_generator.rb @@ -4,7 +4,7 @@ class PerformanceTestGenerator < Rails::Generator::NamedBase def manifest record do |m| # Check for class naming collisions. - m.class_collisions class_path, class_name, "#{class_name}Test" + m.class_collisions class_name, "#{class_name}Test" # performance test directory m.directory File.join('test/performance', class_path) diff --git a/railties/lib/rails_generator/generators/components/plugin/plugin_generator.rb b/railties/lib/rails_generator/generators/components/plugin/plugin_generator.rb index 7a619825a2..615c575e6e 100644 --- a/railties/lib/rails_generator/generators/components/plugin/plugin_generator.rb +++ b/railties/lib/rails_generator/generators/components/plugin/plugin_generator.rb @@ -10,7 +10,7 @@ class PluginGenerator < Rails::Generator::NamedBase def manifest record do |m| # Check for class naming collisions. - m.class_collisions class_path, class_name + m.class_collisions class_name m.directory "#{plugin_path}/lib" m.directory "#{plugin_path}/tasks" diff --git a/railties/lib/rails_generator/generators/components/resource/resource_generator.rb b/railties/lib/rails_generator/generators/components/resource/resource_generator.rb index d5491ece36..ea6dd65bde 100644 --- a/railties/lib/rails_generator/generators/components/resource/resource_generator.rb +++ b/railties/lib/rails_generator/generators/components/resource/resource_generator.rb @@ -30,8 +30,8 @@ class ResourceGenerator < Rails::Generator::NamedBase def manifest record do |m| # Check for class naming collisions. - m.class_collisions(controller_class_path, "#{controller_class_name}Controller", "#{controller_class_name}Helper") - m.class_collisions(class_path, "#{class_name}") + m.class_collisions("#{controller_class_name}Controller", "#{controller_class_name}Helper") + m.class_collisions(class_name) # Controller, helper, views, and test directories. m.directory(File.join('app/models', class_path)) diff --git a/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb b/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb index 5fecfe0167..ff0381da2a 100644 --- a/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb +++ b/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb @@ -36,8 +36,8 @@ class ScaffoldGenerator < Rails::Generator::NamedBase def manifest record do |m| # Check for class naming collisions. - m.class_collisions(controller_class_path, "#{controller_class_name}Controller", "#{controller_class_name}Helper") - m.class_collisions(class_path, "#{class_name}") + m.class_collisions("#{controller_class_name}Controller", "#{controller_class_name}Helper") + m.class_collisions(class_name) # Controller, helper, views, test and stylesheets directories. m.directory(File.join('app/models', class_path)) diff --git a/railties/lib/tasks/gems.rake b/railties/lib/tasks/gems.rake index 9abdfc56b6..c65dfc7dd4 100644 --- a/railties/lib/tasks/gems.rake +++ b/railties/lib/tasks/gems.rake @@ -65,4 +65,14 @@ namespace :gems do end end end + + desc "Regenerate gem specifications in correct format." + task :refresh_specs => :base do + require 'rubygems' + require 'rubygems/gem_runner' + Rails.configuration.gems.each do |gem| + next unless gem.frozen? && (ENV['GEM'].blank? || ENV['GEM'] == gem.name) + gem.refresh_spec(Rails::GemDependency.unpacked_path) if gem.loaded? + end + end end
\ No newline at end of file diff --git a/railties/test/gem_dependency_test.rb b/railties/test/gem_dependency_test.rb index 89e25341d1..5f026b2616 100644 --- a/railties/test/gem_dependency_test.rb +++ b/railties/test/gem_dependency_test.rb @@ -1,3 +1,6 @@ +require 'lib/rails/vendor_gem_source_index' +Rails::VendorGemSourceIndex.silence_spec_warnings = true + require 'plugin_test_helper' class Rails::GemDependency @@ -110,5 +113,22 @@ uses_mocha "Plugin Tests" do assert_equal '0.6.0', DUMMY_GEM_C_VERSION end + def test_gem_load_missing_specification + dummy_gem = Rails::GemDependency.new "dummy-gem-d" + dummy_gem.add_load_paths + dummy_gem.load + assert_not_nil DUMMY_GEM_D_VERSION + assert_equal '1.0.0', DUMMY_GEM_D_VERSION + assert_equal ['lib', 'lib/dummy-gem-d.rb'], dummy_gem.specification.files + end + + def test_gem_load_bad_specification + dummy_gem = Rails::GemDependency.new "dummy-gem-e", :version => "= 1.0.0" + dummy_gem.add_load_paths + dummy_gem.load + assert_not_nil DUMMY_GEM_E_VERSION + assert_equal '1.0.0', DUMMY_GEM_E_VERSION + end + end end diff --git a/railties/test/generators/rails_controller_generator_test.rb b/railties/test/generators/rails_controller_generator_test.rb index 8304fb5a01..f839ea97e6 100644 --- a/railties/test/generators/rails_controller_generator_test.rb +++ b/railties/test/generators/rails_controller_generator_test.rb @@ -1,5 +1,8 @@ require 'generators/generator_test_helper' +module Admin +end + class RailsControllerGeneratorTest < GeneratorTestCase def test_controller_generates_controller diff --git a/railties/test/vendor/gems/dummy-gem-d-1.0.0/lib/dummy-gem-d.rb b/railties/test/vendor/gems/dummy-gem-d-1.0.0/lib/dummy-gem-d.rb new file mode 100644 index 0000000000..e5cb007e5f --- /dev/null +++ b/railties/test/vendor/gems/dummy-gem-d-1.0.0/lib/dummy-gem-d.rb @@ -0,0 +1 @@ +DUMMY_GEM_D_VERSION="1.0.0" diff --git a/railties/test/vendor/gems/dummy-gem-e-1.0.0/.specification b/railties/test/vendor/gems/dummy-gem-e-1.0.0/.specification new file mode 100644 index 0000000000..ce4443c8be --- /dev/null +++ b/railties/test/vendor/gems/dummy-gem-e-1.0.0/.specification @@ -0,0 +1,28 @@ +--- !ruby/object:Gem::Specification +name: dummy-gem-e +version: !ruby/object:Gem::Version + version: 1.3.0 +platform: ruby +authors: +- "Nobody" +date: 2008-10-03 00:00:00 -04:00 +files: +- lib +- lib/dummy-gem-e.rb +require_paths: +- lib +required_ruby_version: !ruby/object:Gem::Requirement + requirements: + - - ">=" + - !ruby/object:Gem::Version + version: "0" + version: +required_rubygems_version: !ruby/object:Gem::Requirement + requirements: + - - ">=" + - !ruby/object:Gem::Version + version: "0" + version: +requirements: [] +specification_version: 2 +summary: Dummy Gem E diff --git a/railties/test/vendor/gems/dummy-gem-e-1.0.0/lib/dummy-gem-e.rb b/railties/test/vendor/gems/dummy-gem-e-1.0.0/lib/dummy-gem-e.rb new file mode 100644 index 0000000000..48bf91a701 --- /dev/null +++ b/railties/test/vendor/gems/dummy-gem-e-1.0.0/lib/dummy-gem-e.rb @@ -0,0 +1 @@ +DUMMY_GEM_E_VERSION="1.0.0" |