From bc75de8e4f60a774423290872aeb25d09561531b Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Thu, 13 Nov 2008 00:51:54 -0500 Subject: Plugin Guide: updated core_extensions section --- .../html/activerecord_validations_callbacks.html | 2 +- railties/doc/guides/html/command_line.html | 434 +++++++++++++++++ railties/doc/guides/html/creating_plugins.html | 151 +++--- railties/doc/guides/html/routing_outside_in.html | 2 +- .../guides/html/testing_rails_applications.html | 541 +++++++++++++-------- .../guides/source/creating_plugins/core_ext.txt | 126 +++++ .../doc/guides/source/creating_plugins/index.txt | 4 +- .../source/creating_plugins/odds_and_ends.txt | 34 -- .../guides/source/creating_plugins/preparation.txt | 222 --------- .../source/creating_plugins/string_to_squawk.txt | 102 ---- .../guides/source/creating_plugins/test_setup.txt | 222 +++++++++ 11 files changed, 1191 insertions(+), 649 deletions(-) create mode 100644 railties/doc/guides/html/command_line.html create mode 100644 railties/doc/guides/source/creating_plugins/core_ext.txt delete mode 100644 railties/doc/guides/source/creating_plugins/preparation.txt delete mode 100644 railties/doc/guides/source/creating_plugins/string_to_squawk.txt create mode 100644 railties/doc/guides/source/creating_plugins/test_setup.txt (limited to 'railties/doc/guides') diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html index 45eec6ffa1..0aa507a9b9 100644 --- a/railties/doc/guides/html/activerecord_validations_callbacks.html +++ b/railties/doc/guides/html/activerecord_validations_callbacks.html @@ -726,7 +726,7 @@ by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
class Invoice < ActiveRecord::Base
-  validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_be_more_than_total_value
+  validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value
 
   def expiration_date_cannot_be_in_the_past
     errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
diff --git a/railties/doc/guides/html/command_line.html b/railties/doc/guides/html/command_line.html
new file mode 100644
index 0000000000..2add20446e
--- /dev/null
+++ b/railties/doc/guides/html/command_line.html
@@ -0,0 +1,434 @@
+
+
+
+	
+	A Guide to The Rails Command Line
+	
+	
+	
+	
+	
+
+
+	
+
+	
+ + + +
+

A Guide to The Rails Command Line

+
+
+

Rails comes with every command line tool you'll need to

+
    +
  • +

    +Create a Rails application +

    +
  • +
  • +

    +Generate models, controllers, database migrations, and unit tests +

    +
  • +
  • +

    +Start a development server +

    +
  • +
  • +

    +Mess with objects through an interactive shell +

    +
  • +
  • +

    +Profile and benchmark your new creation +

    +
  • +
+

… and much, much more! (Buy now!)

+

This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide.

+
+
+

1. Command Line Basics

+
+

There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:

+
    +
  • +

    +console +

    +
  • +
  • +

    +server +

    +
  • +
  • +

    +rake +

    +
  • +
  • +

    +generate +

    +
  • +
  • +

    +rails +

    +
  • +
+

Let's create a simple Rails application to step through each of these commands in context.

+

1.1. rails

+

The first thing we'll want to do is create a new Rails application by running the rails command after installing Rails.

+
+ + + +
+Note +You know you need the rails gem installed by typing gem install rails first, right? Okay, okay, just making sure.
+
+
+
+
$ rails commandsapp
+
+     create
+     create  app/controllers
+     create  app/helpers
+     create  app/models
+     ...
+     ...
+     create  log/production.log
+     create  log/development.log
+     create  log/test.log
+
+

Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.

+
+ + + +
+Note +This output will seem very familiar when we get to the generate command. Creepy foreshadowing!
+
+

1.2. server

+

Let's try it! The server command launches a small web server written in Ruby named WEBrick which was also installed when you installed Rails. You'll use this any time you want to view your work through a web browser.

+
+ + + +
+Note +WEBrick isn't your only option for serving Rails. We'll get to that in a later section. [XXX: which section]
+
+

Here we'll flex our server command, which without any prodding of any kind will run our new shiny Rails app:

+
+
+
$ cd commandsapp
+$ ./script/server
+=> Booting WEBrick...
+=> Rails 2.2.0 application started on http://0.0.0.0:3000
+=> Ctrl-C to shutdown server; call with --help for options
+[2008-11-04 10:11:38] INFO  WEBrick 1.3.1
+[2008-11-04 10:11:38] INFO  ruby 1.8.5 (2006-12-04) [i486-linux]
+[2008-11-04 10:11:38] INFO  WEBrick::HTTPServer#start: pid=18994 port=3000
+
+

WHOA. With just three commands we whipped up a Rails server listening on port 3000. Go! Go right now to your browser and go to http://localhost:3000. I'll wait.

+

See? Cool! It doesn't do much yet, but we'll change that.

+

1.3. generate

+

The generate command uses templates to create a whole lot of things. You can always find out what's available by running generate by itself. Let's do that:

+
+
+
$ ./script/generate
+Usage: ./script/generate generator [options] [args]
+
+...
+...
+
+Installed Generators
+  Builtin: controller, integration_test, mailer, migration, model, observer, performance_test, plugin, resource, scaffold, session_migration
+
+...
+...
+
+
+ + + +
+Note +You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
+
+

Using generators will save you a large amount of time by writing boilerplate code for you — necessary for the darn thing to work, but not necessary for you to spend time writing. That's what we have computers for, right?

+

Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:

+
+ + + +
+Note +All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can just try the command without any parameters (like rails or ./script/generate). For others, you can try adding —help or -h to the end, as in ./script/server —help.
+
+
+
+
$ ./script/generate controller
+Usage: ./script/generate controller ControllerName [options]
+
+...
+...
+
+Example:
+    `./script/generate controller CreditCard open debit credit close`
+
+    Credit card controller with URLs like /credit_card/debit.
+        Controller: app/controllers/credit_card_controller.rb
+        Views:      app/views/credit_card/debit.html.erb [...]
+        Helper:     app/helpers/credit_card_helper.rb
+        Test:       test/functional/credit_card_controller_test.rb
+
+Modules Example:
+    `./script/generate controller 'admin/credit_card' suspend late_fee`
+
+    Credit card admin controller with URLs /admin/credit_card/suspend.
+        Controller: app/controllers/admin/credit_card_controller.rb
+        Views:      app/views/admin/credit_card/debit.html.erb [...]
+        Helper:     app/helpers/admin/credit_card_helper.rb
+        Test:       test/functional/admin/credit_card_controller_test.rb
+
+

Ah, the controller generator is expecting parameters in the form of generate controller ControllerName action1 action2. Let's make a Greetings controller with an action of hello, which will say something nice to us.

+
+
+
$ ./script/generate controller Greeting hello
+     exists  app/controllers/
+     exists  app/helpers/
+     create  app/views/greeting
+     exists  test/functional/
+     create  app/controllers/greetings_controller.rb
+     create  test/functional/greetings_controller_test.rb
+     create  app/helpers/greetings_helper.rb
+     create  app/views/greetings/hello.html.erb
+
+

Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. All from one command!

+
+ +
+
+ + diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 97e14965a5..bbb4719b0f 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -213,7 +213,16 @@ ul#navMain {
  • - Add a to_squawk method to String + Extending core classes +
  • Add an acts_as_yaffle method to ActiveRecord @@ -234,8 +243,6 @@ ul#navMain { Odds and ends
  • Now you are ready to test-drive your plugin!

    -

    2. Add a to_squawk method to String

    +

    2. Extending core classes

    -

    To update a core class you will have to:

    +

    This section will explain how to add a method to String that will be available anywhere in your rails app by:

    • -Write tests for the desired functionality. -

      -
    • -
    • -

      -Create a file for the code you wish to use. +Writing tests for the desired behavior

    • -Require that file from your init.rb. +Creating and requiring the correct files

    -

    Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from init.rb. The file you are going to add for this tutorial is lib/core_ext.rb.

    -

    First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this:

    -

    vendor/plugins/yaffle/test/core_ext_test.rb

    +

    2.1. Working with init.rb

    +

    When rails loads plugins it looks for the file named init.rb. However, the plugin initializer script init.rb is invoked via eval (not require) so it has slightly different behavior.

    +

    Under certain circumstances if you reopen classes or modules in init.rb itself, you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from init.rb.

    +

    If you must reopen a class in init.rb you can use module_eval or class_eval:

    +

    vendor/plugins/yaffle/init.rb

    -
    require 'test/unit'
    -
    -class CoreExtTest < Test::Unit::TestCase
    -  # Replace this with your real tests.
    -  def test_this_plugin
    -    flunk
    +
    Hash.class_eval do
    +  def is_a_special_hash?
    +    true
       end
     end
     
    -

    Start off by removing the default test, and adding a require statement for your test helper.

    +

    Another way is to explicitly define the top-level module space for all modules and classes, like ::Hash:

    +

    vendor/plugins/yaffle/init.rb

    +
    +
    +
    class ::Hash
    +  def is_a_special_hash?
    +    true
    +  end
    +end
    +
    +

    2.2. Creating the test

    +

    In this example you will add a method to String named to_squawk. To begin, create a new test file with a few assertions:

    vendor/plugins/yaffle/test/core_ext_test.rb

    require File.dirname(__FILE__) + '/test_helper.rb'
     
     class CoreExtTest < Test::Unit::TestCase
    +  def test_to_squawk_prepends_the_word_squawk
    +    assert_equal "squawk! Hello World", "Hello World".to_squawk
    +  end
     end
     

    Navigate to your plugin directory and run rake test:

    @@ -638,42 +656,45 @@ http://www.gnu.org/software/src-highlite -->
    cd vendor/plugins/yaffle
     rake test
    -

    Your test should fail with no such file to load — ./test/../lib/core_ext.rb (LoadError) because we haven't created any file yet. Create the file lib/core_ext.rb and re-run the tests. You should see a different error message:

    +

    The test above should fail with the message:

    -
    1.) Failure ...
    -No tests were specified
    +
     1) Error:
    +test_to_squawk_prepends_the_word_squawk(CoreExtTest):
    +NoMethodError: undefined method `to_squawk' for "Hello World":String
    +    ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'
    -

    Great - now you are ready to start development. The first thing we'll do is to add a method to String called to_squawk which will prefix the string with the word “squawk!”. The test will look something like this:

    +

    Great - now you are ready to start development.

    +

    2.3. Organize your files

    +

    A common pattern in rails plugins is to set up the file structure something like this:

    +
    +
    +
    |-- init.rb
    +|-- lib
    +|   |-- yaffle
    +|   |   `-- core_ext.rb
    +|   `-- yaffle.rb
    +
    +

    The first thing we need to to is to require our lib/yaffle.rb file from init.rb:

    vendor/plugins/yaffle/init.rb

    -
    class CoreExtTest < Test::Unit::TestCase
    -  def test_string_should_respond_to_squawk
    -    assert_equal true, "".respond_to?(:to_squawk)
    -  end
    -
    -  def test_string_prepend_empty_strings_with_the_word_squawk
    -    assert_equal "squawk!", "".to_squawk
    -  end
    -
    -  def test_string_prepend_non_empty_strings_with_the_word_squawk
    -    assert_equal "squawk! Hello World", "Hello World".to_squawk
    -  end
    -end
    +
    require 'yaffle'
     
    -

    vendor/plugins/yaffle/init.rb

    +

    Then in lib/yaffle.rb require lib/core_ext.rb:

    +

    vendor/plugins/yaffle/lib/yaffle.rb

    -
    require "core_ext"
    +
    require "yaffle/core_ext"
     
    -

    vendor/plugins/yaffle/lib/core_ext.rb

    +

    Finally, create the core_ext.rb file and add the to_squawk method:

    +

    vendor/plugins/yaffle/lib/yaffle/core_ext.rb

    end end
    -

    When monkey-patching existing classes it's often better to use class_eval instead of opening the class directly.

    -

    To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking:

    +

    To test that your method does what it says it does, run the unit tests with rake from your plugin directory. To see this in action, fire up a console and start squawking:

    $ ./script/console
     >> "Hello World".to_squawk
     => "squawk! Hello World"
    -

    If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class.

    3. Add an acts_as_yaffle method to ActiveRecord

    @@ -1230,37 +1249,7 @@ http://www.gnu.org/software/src-highlite -->

    8. Odds and ends

    -

    8.1. Work with init.rb

    -

    The plugin initializer script init.rb is invoked via eval (not require) so it has slightly different behavior.

    -

    If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. As a rule, it's better not to open any classes in init.rb, and it makes the plugin more difficult to turn into a gem.

    -

    A better alternative is to reopen the class in a different file, and require that file from init.rb.

    -

    If you must reopen a class in init.rb, there are various techniques. One way is to use module_eval or class_eval:

    -

    vendor/plugins/yaffle/init.rb

    -
    -
    -
    Hash.class_eval do
    -  def is_a_special_hash?
    -    true
    -  end
    -end
    -
    -

    Another way is to explicitly define the top-level module space for all modules and classes, like ::Hash:

    -

    vendor/plugins/yaffle/init.rb

    -
    -
    -
    class ::Hash
    -  def is_a_special_hash?
    -    true
    -  end
    -end
    -
    -

    8.2. Generate RDoc Documentation

    +

    8.1. Generate RDoc Documentation

    Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.

    The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:

      @@ -1292,7 +1281,7 @@ Warning, gotchas or tips that might help save users time.
      rake rdoc
    -

    8.3. Store models, views, helpers, and controllers in your plugins

    +

    8.2. Store models, views, helpers, and controllers in your plugins

    You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path:

    Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser.

    Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server.

    -

    8.4. Write custom Rake tasks in your plugin

    +

    8.3. Write custom Rake tasks in your plugin

    When you created the plugin with the built-in rails generator, it generated a rake file for you in vendor/plugins/yaffle/tasks/yaffle.rake. Any rake task you add here will be available to the app.

    Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:

    vendor/plugins/yaffle/tasks/yaffle.rake

    @@ -1332,7 +1321,7 @@ http://www.gnu.org/software/src-highlite -->
    yaffle:squawk             # Prints out the word 'Yaffle'

    You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up.

    -

    8.5. Store plugins in alternate locations

    +

    8.4. Store plugins in alternate locations

    You can store plugins wherever you want - you just have to add those plugins to the plugins path in environment.rb.

    Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now.

    You can even store plugins inside of other plugins for complete plugin madness!

    @@ -1343,9 +1332,9 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins")
     
    -

    8.6. Create your own Plugin Loaders and Plugin Locators

    +

    8.5. Create your own Plugin Loaders and Plugin Locators

    If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial.

    -

    8.7. Use Custom Plugin Generators

    +

    8.6. Use Custom Plugin Generators

    If you are an RSpec fan, you can install the rspec_plugin_generator gem, which will generate the spec folder and database for you. See http://github.com/pat-maddox/rspec-plugin-generator/tree/master.

    9. Appendix

    diff --git a/railties/doc/guides/html/routing_outside_in.html b/railties/doc/guides/html/routing_outside_in.html index 8add4e7789..947d0836ce 100644 --- a/railties/doc/guides/html/routing_outside_in.html +++ b/railties/doc/guides/html/routing_outside_in.html @@ -1448,7 +1448,7 @@ http://www.gnu.org/software/src-highlite -->
    map.resources :photos, :except => :destroy
     

    In this case, all of the normal routes except the route for destroy (a DELETE request to /photos/id) will be generated.

    -

    In addition to an action or a list of actions, you can also supply the special symbols :all or :none to the :only and :accept options.

    +

    In addition to an action or a list of actions, you can also supply the special symbols :all or :none to the :only and :except options.

    diff --git a/railties/doc/guides/html/testing_rails_applications.html b/railties/doc/guides/html/testing_rails_applications.html index 666d1dff85..b8a99767ee 100644 --- a/railties/doc/guides/html/testing_rails_applications.html +++ b/railties/doc/guides/html/testing_rails_applications.html @@ -202,7 +202,7 @@ ul#navMain { Why Write Tests for your Rails Applications?
  • - Before you Start Writing Tests + Introduction to Testing
  • - Unit Testing Your Models + Unit Testing your Models
  • + Rake Tasks for Running your Tests +
  • +
  • + Brief Note About Test::Unit +
  • +
  • + Setup and Teardown +
  • +
  • + Testing Routes +
  • +
  • Testing Your Mailers
      @@ -268,9 +282,6 @@ ul#navMain {
  • - Rake Tasks for Testing -
  • -
  • Other Testing Approaches
  • @@ -309,12 +320,7 @@ Identify other popular testing approaches and plugins
    • -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. +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.

    • @@ -324,16 +330,16 @@ By simply running your Rails tests you can ensure your code adheres to the desir
    • -Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers. +Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.

    -

    2. Before you Start Writing Tests

    +

    2. Introduction to Testing

    -

    Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.

    +

    Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.

    2.1. The 3 Environments

    -

    Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. One of the consequences of this design decision is that every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.

    +

    Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.

    One place you'll find this distinction is in the config/database.yml file. This YAML configuration file has 3 different sections defining 3 unique database setups:

    • @@ -370,9 +376,9 @@ fixtures/ functional2.3. The Low-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.

      2.3.1. What Are Fixtures?

      -

      Fixtures is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: YAML or CSV.

      +

      Fixtures is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: YAML or CSV. In this guide we will use YAML which is the preferred format.

      You'll find fixtures under your test/fixtures directory. When you run script/generate model to create a new model, fixture stubs will be automatically created and placed in this directory.

      -

      2.3.2. YAML the Camel is a Mammal with Enamel

      +

      2.3.2. YAML

      YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the .yml file extension (as in users.yml).

      Here's a sample YAML fixture file:

      @@ -382,78 +388,18 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
      # low & behold!  I am a YAML comment!
       david:
      - id: 1
        name: David Heinemeier Hansson
        birthday: 1979-10-15
        profession: Systems development
       
       steve:
      - id: 2
        name: Steve Ross Kellock
        birthday: 1974-09-27
        profession: guy with keyboard
       

    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.

    -

    2.3.3. Comma Seperated

    -

    Fixtures can also be described using the all-too-familiar comma-separated value (CSV) file format. These files, just like YAML fixtures, are placed in the test/fixtures directory, but these end with the .csv file extension (as in celebrity_holiday_figures.csv).

    -

    A CSV fixture looks like this:

    -
    -
    -
    id, username, password, stretchable, comments
    -1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!""
    -2, ebunny, ihateeggs, true, Hoppity hop y'all
    -3, tfairy, ilovecavities, true, "Pull your teeth, I will"
    -
    -

    The first line is the header. It is a comma-separated list of fields. The rest of the file is the payload: 1 record per line. A few notes about this format:

    -
      -
    • -

      -Leading and trailing spaces are trimmed from each value when it is imported -

      -
    • -
    • -

      -If you use a comma as data, the cell must be encased in quotes -

      -
    • -
    • -

      -If you use a quote as data, you must escape it with a 2nd quote -

      -
    • -
    • -

      -Don't use blank lines -

      -
    • -
    • -

      -Nulls can be defined by including no data between a pair of commas -

      -
    • -
    -

    Unlike the YAML format where you give each record in a fixture a name, CSV fixture names are automatically generated. They follow a pattern of "model-name-counter". In the above example, you would have:

    -
      -
    • -

      -celebrity-holiday-figures-1 -

      -
    • -
    • -

      -celebrity-holiday-figures-2 -

      -
    • -
    • -

      -celebrity-holiday-figures-3 -

      -
    • -
    -

    The CSV format is great to use if you have existing data in a spreadsheet or database and you are able to save it (or export it) as a CSV.

    -

    2.3.4. ERb'in It Up

    +

    2.3.3. ERb'in It Up

    ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data.

    -

    I'll demonstrate with a YAML file:

    <% earth_size = 20 -%>
     mercury:
    -  id: 1
       size: <%= earth_size / 50 %>
    +  brightest_on: <%= 113.days.ago.to_s(:db) %>
     
     venus:
    -  id: 2
       size: <%= earth_size / 2 %>
    +  brightest_on: <%= 67.days.ago.to_s(:db) %>
     
     mars:
    -  id: 3
       size: <%= earth_size - 69 %>
    +  brightest_on: <%= 13.days.from_now.to_s(:db) %>
     

    Anything encased within the

    @@ -480,8 +426,8 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    <% %>
     
    -

    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.

    -

    2.3.5. Fixtures in Action

    +

    tag is considered Ruby code. When this fixture is loaded, the size attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The brightest_on attribute will also be evaluated and formatted by Rails to be compatible with the database.

    +

    2.3.4. Fixtures in Action

    Rails by default automatically loads all fixtures from the test/fixtures folder for your unit and functional test. Loading involves three steps:

    • @@ -500,7 +446,7 @@ Dump the fixture data into a variable in case you want to access it directly

    -

    2.3.6. Hashes with Special Powers

    +

    2.3.5. 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. For example:

    +
    $ rake db:migrate
    +...
    +$ rake db:test:load
    +
    +

    Above rake db:migrate runs any pending migrations on the developemnt environment and updates db/schema.rb. rake db:test:load recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run db:test:prepare as it first checks for pending migrations and warns you appropriately.

    +
    + + + +
    +Note +db:test:prepare will fail with an error if db/schema.rb doesn't exists.
    +
    +

    3.1.1. Rake Tasks for Preparing you Application for Testing ==

    +

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

    +
    +
    +
    +rake db:test:clone+            Recreate the test database from the current environment's database schema
    ++rake db:test:clone_structure+  Recreate the test databases from the development structure
    ++rake db:test:load+             Recreate the test database from the current +schema.rb+
    ++rake db:test:prepare+          Check for pending migrations and load the test schema
    ++rake db:test:purge+            Empty the test database.
    +
    +
    + + + +
    +Tip +You can see all these rake tasks and their descriptions by running rake —tasks —describe
    +
    +

    3.2. Running Tests

    Running a test is as simple as invoking the file containing the test cases through Ruby:

    -
    def test_should_have_atleast_one_post
    -  post = Post.find(:first)
    -  assert_not_nil post
    +
    def test_should_not_save_post_without_title
    +  post = Post.new
    +  assert !post.save
     end
     
    -

    If you haven't added any data to the test fixture for posts, this test will fail. You can see this by running it:

    +

    Let us run this newly added test.

    -
    $ ruby unit/post_test.rb
    +
    $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
     Loaded suite unit/post_test
     Started
    -F.
    -Finished in 0.027274 seconds.
    +F
    +Finished in 0.197094 seconds.
     
       1) Failure:
    -test_should_have_atleast_one_post(PostTest)
    -    [unit/post_test.rb:12:in `test_should_have_atleast_one_post'
    +test_should_not_save_post_without_title(PostTest)
    +    [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
          /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
          /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
    -<nil> expected to not be nil.
    +<false> is not true.
     
    -2 tests, 2 assertions, 1 failures, 0 errors
    +1 tests, 1 assertions, 1 failures, 0 errors

    In the output, F denotes a failure. You can see the corresponding trace shown under 1) along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here:

    @@ -677,30 +670,60 @@ test_should_have_atleast_one_post(PostTest) by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite --> -
    def test_should_have_atleast_one_post
    -  post = Post.find(:first)
    -  assert_not_nil post, "Should not be nil as Posts table should have atleast one post"
    +
    def test_should_not_save_post_without_title
    +  post = Post.new
    +  assert !post.save, "Saved the post without a title"
     end
     

    Running this test shows the friendlier assertion message:

    -
    $ ruby unit/post_test.rb
    +
    $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
     Loaded suite unit/post_test
     Started
    -F.
    -Finished in 0.024727 seconds.
    +F
    +Finished in 0.198093 seconds.
     
       1) Failure:
    -test_should_have_atleast_one_post(PostTest)
    -    [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
    +test_should_not_save_post_without_title(PostTest)
    +    [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
          /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
          /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
    -Should not be nil as Posts table should have atleast one post.
    -<nil> expected to not be nil.
    +Saved the post without a title.
    +<false> is not true.
    +
    +1 tests, 1 assertions, 1 failures, 0 errors
    +
    +

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

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

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

    +
    +
    +
    $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
    +Loaded suite unit/post_test
    +Started
    +.
    +Finished in 0.193608 seconds.
     
    -2 tests, 2 assertions, 1 failures, 0 errors
    +1 tests, 1 assertions, 0 failures, 0 errors
    +

    Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as Test-Driven Development (TDD).

    +
    + + + +
    +Tip +Many Rails developers practice Test-Driven Development (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with 15 TDD steps to create a Rails application.
    +

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

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

    -
    $ ruby unit/post_test.rb
    +
    $ ruby unit/post_test.rb -n test_should_report_error
     Loaded suite unit/post_test
     Started
    -FE.
    -Finished in 0.108389 seconds.
    +E
    +Finished in 0.195757 seconds.
     
    -  1) Failure:
    -test_should_have_atleast_one_post(PostTest)
    -    [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
    -     /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
    -     /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
    -Should not be nil as Posts table should have atleast one post.
    -<nil> expected to not be nil.
    -
    -  2) Error:
    +  1) Error:
     test_should_report_error(PostTest):
    -NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x304a7b0>
    +NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x2cc9de8>
         /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing'
    -    unit/post_test.rb:15:in `test_should_report_error'
    +    unit/post_test.rb:16:in `test_should_report_error'
         /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
         /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'
     
    -3 tests, 2 assertions, 1 failures, 1 errors
    +1 tests, 0 assertions, 0 failures, 1 errors

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

    @@ -749,17 +764,9 @@ NameError: undefined local variable or method `some_undefined_variable' for #<
  • The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
    -

    3.2. What to Include in Your Unit Tests

    +

    3.3. What to Include in Your Unit Tests

    Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.

    -
    - - - -
    -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 15 TDD steps to create a Rails application.
    -
    -

    3.3. Assertions Available

    +

    3.4. Assertions Available

    By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.

    There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with test/unit, the testing library used by Rails. The [msg] parameter is an optional string message you can specify to make your test failure messages clearer. It's not required.

    @@ -943,7 +950,7 @@ cellspacing="0" cellpadding="4"> Creating your own assertions is an advanced topic that we won't cover in this tutorial.
    -

    3.4. Rails Specific Assertions

    +

    3.5. Rails Specific Assertions

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

    -

    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:

    -
    -
    -
    $ script/generate controller post
    -...
    -      create  app/controllers/post_controller.rb
    -      create  test/functional/post_controller_test.rb
    -...
    -
    -

    Now if you take a look at the file posts_controller_test.rb in the test/functional directory, you should see:

    -
    -
    -
    require 'test_helper'
    -
    -class PostsControllerTest < ActionController::TestCase
    -  # Replace this with your real tests.
    -  def test_truth
    -    assert true
    -  end
    -end
    -
    -

    Of course, you need to replace the simple assertion with real testing. Here's a starting example of a functional test:

    +

    Now that we have used Rails scaffold generator for our Post resource, it has already created the controller code and functional tests. You can take look at the file posts_controller_test.rb in the test/functional directory.

    +

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

    get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
     
    +
    +
    + + +
    +Note +If you try running test_should_create_post test from posts_controller_test.rb it will fail on account of the newly added model level validation and rightly so.
    +
    +

    Let us modify test_should_create_post test in posts_controller_test.rb so that all our test pass:

    +
    +
    +
    def test_should_create_post
    +  assert_difference('Post.count') do
    +    post :create, :post => { :title => 'Some title'}
    +  end
    +
    +  assert_redirected_to post_path(assigns(:post))
    +end
    +
    +

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

    4.2. Available Request Types for Functional Tests

    If you're familiar with the HTTP protocol, you'll know that get is a type of request. There are 5 request types supported in Rails functional tests:

      @@ -1564,10 +1568,159 @@ http://www.gnu.org/software/src-highlite --> end
    -

    6. Testing Your Mailers

    +

    6. Rake Tasks for Running your Tests

    +
    +

    You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.

    +

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

    +
    +
    +
    +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_+)
    +
    +
    +

    7. Brief Note About Test::Unit

    +
    +

    Ruby ships with a boat load of libraries. One little gem of a library is Test::Unit, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in Test::Unit::Assertions. The class ActiveSupport::TestCase which we have been using in our unit and functional tests extends Test::Unit::TestCase that it is how we can use all the basic assertions in our tests.

    +
    + + + +
    +Note +For more information on Test::Unit, refer to test/unit Documentation
    +
    +
    +

    8. Setup and Teardown

    +
    +

    If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in Posts controller:

    +
    +
    +
    require 'test_helper'
    +
    +class PostsControllerTest < ActionController::TestCase
    +
    +  # called before every single test
    +  def setup
    +    @post = posts(:one)
    +  end
    +
    +  # called after every single test
    +  def teardown
    +    # as we are re-initializing @post before every test
    +    # setting it to nil here is not essential but I hope
    +    # you understand how you can use the teardown method
    +    @post = nil
    +  end
    +
    +  def test_should_show_post
    +    get :show, :id => @post.id
    +    assert_response :success
    +  end
    +
    +  def test_should_destroy_post
    +    assert_difference('Post.count', -1) do
    +      delete :destroy, :id => @post.id
    +    end
    +
    +    assert_redirected_to posts_path
    +  end
    +
    +end
    +
    +

    Above, the setup method is called before each test and so @post is available for each of the tests. Rails implements setup and teardown as ActiveSupport::Callbacks. Which essentially means you need not only use setup and teardown as methods in your tests. You could specify them by using:

    +
      +
    • +

      +a block +

      +
    • +
    • +

      +a method (like in the earlier example) +

      +
    • +
    • +

      +a method name as a symbol +

      +
    • +
    • +

      +a lambda +

      +
    • +
    +

    Let's see the earlier example by specifying setup callback by specifying a method name as a symbol:

    +
    +
    +
    require '../test_helper'
    +
    +class PostsControllerTest < ActionController::TestCase
    +
    +  # called before every single test
    +  setup :initialize_post
    +
    +  # called after every single test
    +  def teardown
    +    @post = nil
    +  end
    +
    +  def test_should_show_post
    +    get :show, :id => @post.id
    +    assert_response :success
    +  end
    +
    +  def test_should_update_post
    +    put :update, :id => @post.id, :post => { }
    +    assert_redirected_to post_path(assigns(:post))
    +  end
    +
    +  def test_should_destroy_post
    +    assert_difference('Post.count', -1) do
    +      delete :destroy, :id => @post.id
    +    end
    +
    +    assert_redirected_to posts_path
    +  end
    +
    +  private
    +
    +  def initialize_post
    +    @post = posts(:one)
    +  end
    +
    +end
    +
    +
    +

    9. Testing Routes

    +
    +

    Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default show action of Posts controller above should look like:

    +
    +
    +
    def test_should_route_to_post
    +  assert_routing '/posts/1', { :controller => "posts", :action => "show", :id => "1" }
    +end
    +
    +
    +

    10. Testing Your Mailers

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

    -

    6.1. Keeping the Postman in Check

    +

    10.1. Keeping the Postman in Check

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

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

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

    -

    6.1.1. From All Sides

    +

    10.1.1. From All Sides

    There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a knownvalue (a fixture — yay! more fixtures!). In the functional tests you don't so much test the minute details produced by the mailer Instead we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.

    -

    6.2. Unit Testing

    +

    10.2. Unit Testing

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

    -

    6.2.1. Revenge of the Fixtures

    +

    10.2.1. Revenge of the Fixtures

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

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

    -

    6.2.2. The Basic Test case

    +

    10.2.2. The Basic Test case

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

    end
    -

    7. Rake Tasks for Testing

    -
    -

    You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.

    -

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

    -
    -
    -
    +rake test+                     Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
    -+rake test:units+               Runs all the unit tests from +test/unit+
    -+rake test:functionals+         Runs all the functional tests from +test/functional+
    -+rake test:integration+         Runs all the integration tests from +test/integration+
    -+rake test:recent+              Tests recent changes
    -+rake test:uncommitted+         Runs all the tests which are uncommitted. Only supports Subversion
    -+rake test:plugins+             Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
    -+rake db:test:clone+            Recreate the test database from the current environment's database schema
    -+rake db:test:clone_structure+  Recreate the test databases from the development structure
    -+rake db:test:load+             Recreate the test database from the current +schema.rb+
    -+rake db:test:prepare+          Check for pending migrations and load the test schema
    -+rake db:test:purge+            Empty the test database.
    -
    -
    - - - -
    -Tip -You can see all these rake task and their descriptions by running rake —tasks —describe
    -
    -
    -

    8. Other Testing Approaches

    +

    11. Other Testing Approaches

    The built-in test/unit based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:

      @@ -1707,18 +1831,23 @@ link: RSpec, a behavior-driven development fram
    -

    9. Changelog

    +

    12. Changelog

    • +November 13, 2008: Revised based on feedback from Pratik Naik by Akshay Surve (not yet approved for publication) +

      +
    • +
    • +

      October 14, 2008: Edit and formatting pass by Mike Gunderloy (not yet approved for publication)

    • -October 12, 2008: First draft by Akashay Surve (not yet approved for publication) +October 12, 2008: First draft by Akshay Surve (not yet approved for publication)

    diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt new file mode 100644 index 0000000000..33d3dc8ce7 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/core_ext.txt @@ -0,0 +1,126 @@ +== Extending core classes == + +This section will explain how to add a method to String that will be available anywhere in your rails app by: + + * Writing tests for the desired behavior + * Creating and requiring the correct files + + +=== Working with init.rb === + +When rails loads plugins it looks for the file named init.rb. However, the plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. + +Under certain circumstances if you reopen classes or modules in 'init.rb' itself, you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from `init.rb`. + +If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval`: + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +--------------------------------------------------- +Hash.class_eval do + def is_a_special_hash? + true + end +end +--------------------------------------------------- + +Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +--------------------------------------------------- +class ::Hash + def is_a_special_hash? + true + end +end +--------------------------------------------------- + +=== Creating the test === + +In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions: + +*vendor/plugins/yaffle/test/core_ext_test.rb* + +[source, ruby] +-------------------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' + +class CoreExtTest < Test::Unit::TestCase + def test_to_squawk_prepends_the_word_squawk + assert_equal "squawk! Hello World", "Hello World".to_squawk + end +end +-------------------------------------------------------- + +Navigate to your plugin directory and run `rake test`: + +-------------------------------------------------------- +cd vendor/plugins/yaffle +rake test +-------------------------------------------------------- + +The test above should fail with the message: + +-------------------------------------------------------- + 1) Error: +test_to_squawk_prepends_the_word_squawk(CoreExtTest): +NoMethodError: undefined method `to_squawk' for "Hello World":String + ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk' +-------------------------------------------------------- + +Great - now you are ready to start development. + +=== Organize your files === + +A common pattern in rails plugins is to set up the file structure something like this: + +-------------------------------------------------------- +|-- init.rb +|-- lib +| |-- yaffle +| | `-- core_ext.rb +| `-- yaffle.rb +-------------------------------------------------------- + +The first thing we need to to is to require our 'lib/yaffle.rb' file from 'init.rb': + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +-------------------------------------------------------- +require 'yaffle' +-------------------------------------------------------- + +Then in 'lib/yaffle.rb' require 'lib/core_ext.rb': + +*vendor/plugins/yaffle/lib/yaffle.rb* + +[source, ruby] +-------------------------------------------------------- +require "yaffle/core_ext" +-------------------------------------------------------- + +Finally, create the 'core_ext.rb' file and add the 'to_squawk' method: + +*vendor/plugins/yaffle/lib/yaffle/core_ext.rb* + +[source, ruby] +-------------------------------------------------------- +String.class_eval do + def to_squawk + "squawk! #{self}".strip + end +end +-------------------------------------------------------- + +To test that your method does what it says it does, run the unit tests with `rake` from your plugin directory. To see this in action, fire up a console and start squawking: + +-------------------------------------------------------- +$ ./script/console +>> "Hello World".to_squawk +=> "squawk! Hello World" +-------------------------------------------------------- + diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index d3042f8d56..91d7027323 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -29,9 +29,9 @@ This guide describes how to build a test-driven plugin that will: For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development. -include::preparation.txt[] +include::test_setup.txt[] -include::string_to_squawk.txt[] +include::core_ext.txt[] include::acts_as_yaffle.txt[] diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt index 88cd4fe9ed..a52e1c8fdb 100644 --- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt +++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt @@ -1,39 +1,5 @@ == Odds and ends == -=== Work with init.rb === - -The plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. - -If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. As a rule, it's better not to open any classes in `init.rb`, and it makes the plugin more difficult to turn into a gem. - -A better alternative is to reopen the class in a different file, and require that file from `init.rb`. - -If you must reopen a class in `init.rb`, there are various techniques. One way is to use `module_eval` or `class_eval`: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] ---------------------------------------------------- -Hash.class_eval do - def is_a_special_hash? - true - end -end ---------------------------------------------------- - -Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] ---------------------------------------------------- -class ::Hash - def is_a_special_hash? - true - end -end ---------------------------------------------------- - === Generate RDoc Documentation === Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. diff --git a/railties/doc/guides/source/creating_plugins/preparation.txt b/railties/doc/guides/source/creating_plugins/preparation.txt deleted file mode 100644 index dc9ef6bc29..0000000000 --- a/railties/doc/guides/source/creating_plugins/preparation.txt +++ /dev/null @@ -1,222 +0,0 @@ -== Preparation == - -=== Create the basic app === - -The examples in this guide require that you have a working rails application. To create a simple rails app execute: - ------------------------------------------------- -gem install rails -rails yaffle_guide -cd yaffle_guide -script/generate scaffold bird name:string -rake db:migrate -script/server ------------------------------------------------- - -Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. - -.Editor's note: -NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. - - -=== Generate the plugin skeleton === - -Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. - -This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. - -Examples: ----------------------------------------------- -./script/generate plugin yaffle -./script/generate plugin yaffle --with-generator ----------------------------------------------- - -To get more detailed help on the plugin generator, type `./script/generate plugin`. - -Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now: - ----------------------------------------------- -./script/generate plugin yaffle --with-generator ----------------------------------------------- - -You should see the following output: - ----------------------------------------------- -create vendor/plugins/yaffle/lib -create vendor/plugins/yaffle/tasks -create vendor/plugins/yaffle/test -create vendor/plugins/yaffle/README -create vendor/plugins/yaffle/MIT-LICENSE -create vendor/plugins/yaffle/Rakefile -create vendor/plugins/yaffle/init.rb -create vendor/plugins/yaffle/install.rb -create vendor/plugins/yaffle/uninstall.rb -create vendor/plugins/yaffle/lib/yaffle.rb -create vendor/plugins/yaffle/tasks/yaffle_tasks.rake -create vendor/plugins/yaffle/test/core_ext_test.rb -create vendor/plugins/yaffle/generators -create vendor/plugins/yaffle/generators/yaffle -create vendor/plugins/yaffle/generators/yaffle/templates -create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb -create vendor/plugins/yaffle/generators/yaffle/USAGE ----------------------------------------------- - - -=== Setup the plugin for testing === - -In this guide you will learn how to test your plugin against multiple different adapters using Active Record. This guide will not cover how to use fixtures in plugin tests. - -To setup your plugin to allow for easy testing you'll need to add 3 files: - - * A 'database.yml' file with all of your connection strings. - * A 'schema.rb' file with your table definitions. - * A test helper that sets up the database before your tests. - -*vendor/plugins/yaffle/test/database.yml:* - ----------------------------------------------- -sqlite: - :adapter: sqlite - :dbfile: yaffle_plugin.sqlite.db - -sqlite3: - :adapter: sqlite3 - :dbfile: yaffle_plugin.sqlite3.db - -postgresql: - :adapter: postgresql - :username: postgres - :password: postgres - :database: yaffle_plugin_test - :min_messages: ERROR - -mysql: - :adapter: mysql - :host: localhost - :username: rails - :password: - :database: yaffle_plugin_test ----------------------------------------------- - -For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: - -*vendor/plugins/yaffle/test/schema.rb:* - -[source, ruby] ----------------------------------------------- -ActiveRecord::Schema.define(:version => 0) do - create_table :hickwalls, :force => true do |t| - t.string :name - t.string :last_squawk - t.datetime :last_squawked_at - end - create_table :wickwalls, :force => true do |t| - t.string :name - t.string :last_tweet - t.datetime :last_tweeted_at - end -end ----------------------------------------------- - -*vendor/plugins/yaffle/test/test_helper.rb:* - -[source, ruby] ----------------------------------------------- -ENV['RAILS_ENV'] = 'test' -ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' - -require 'test/unit' -require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) - -config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) -ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") - -db_adapter = ENV['DB'] - -db_adapter ||= - begin - require 'rubygems' - require 'sqlite' - 'sqlite' - rescue MissingSourceFile - begin - require 'sqlite3' - 'sqlite3' - rescue MissingSourceFile - end - end - -if db_adapter.nil? - raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." -end - -ActiveRecord::Base.establish_connection(config[db_adapter]) - -load(File.dirname(__FILE__) + "/schema.rb") - -require File.dirname(__FILE__) + '/../init.rb' - -class Hickwall < ActiveRecord::Base -end - -class Wickwall < ActiveRecord::Base -end ----------------------------------------------- - -=== Run the plugin tests === - -Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: - -*vendor/plugins/yaffle/test/yaffle_test.rb:* - -[source, ruby] ----------------------------------------------- -require File.dirname(__FILE__) + '/test_helper.rb' - -class YaffleTest < Test::Unit::TestCase - - def test_active_record_classes_from_test_helper - assert_kind_of Hickwall, Hickwall.new - assert_kind_of Wickwall, Wickwall.new - end - -end ----------------------------------------------- - -To run this, go to the plugin directory and run `rake`: - ----------------------------------------------- -cd vendor/plugins/yaffle -rake ----------------------------------------------- - -You should see output like: - ----------------------------------------------- -/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" --- create_table(:hickwalls, {:force=>true}) - -> 0.0220s --- create_table(:wickwalls, {:force=>true}) - -> 0.0077s --- initialize_schema_migrations_table() - -> 0.0007s --- assume_migrated_upto_version(0) - -> 0.0007s -Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader -Started -. -Finished in 0.002236 seconds. - -1 test, 1 assertion, 0 failures, 0 errors ----------------------------------------------- - -By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake: - ----------------------------------------------- -rake DB=sqlite -rake DB=sqlite3 -rake DB=mysql -rake DB=postgresql ----------------------------------------------- - -Now you are ready to test-drive your plugin! diff --git a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt b/railties/doc/guides/source/creating_plugins/string_to_squawk.txt deleted file mode 100644 index 63f1131442..0000000000 --- a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt +++ /dev/null @@ -1,102 +0,0 @@ -== Add a `to_squawk` method to String == - -To update a core class you will have to: - - * Write tests for the desired functionality. - * Create a file for the code you wish to use. - * Require that file from your 'init.rb'. - -Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from 'init.rb'. The file you are going to add for this tutorial is 'lib/core_ext.rb'. - -First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this: - -*vendor/plugins/yaffle/test/core_ext_test.rb* - -[source, ruby] --------------------------------------------------------- -require 'test/unit' - -class CoreExtTest < Test::Unit::TestCase - # Replace this with your real tests. - def test_this_plugin - flunk - end -end --------------------------------------------------------- - -Start off by removing the default test, and adding a require statement for your test helper. - -*vendor/plugins/yaffle/test/core_ext_test.rb* - -[source, ruby] --------------------------------------------------------- -require File.dirname(__FILE__) + '/test_helper.rb' - -class CoreExtTest < Test::Unit::TestCase -end --------------------------------------------------------- - -Navigate to your plugin directory and run `rake test`: - --------------------------------------------------------- -cd vendor/plugins/yaffle -rake test --------------------------------------------------------- - -Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file 'lib/core_ext.rb' and re-run the tests. You should see a different error message: - --------------------------------------------------------- -1.) Failure ... -No tests were specified --------------------------------------------------------- - -Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word ``squawk!''. The test will look something like this: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] --------------------------------------------------------- -class CoreExtTest < Test::Unit::TestCase - def test_string_should_respond_to_squawk - assert_equal true, "".respond_to?(:to_squawk) - end - - def test_string_prepend_empty_strings_with_the_word_squawk - assert_equal "squawk!", "".to_squawk - end - - def test_string_prepend_non_empty_strings_with_the_word_squawk - assert_equal "squawk! Hello World", "Hello World".to_squawk - end -end --------------------------------------------------------- - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] --------------------------------------------------------- -require "core_ext" --------------------------------------------------------- - -*vendor/plugins/yaffle/lib/core_ext.rb* - -[source, ruby] --------------------------------------------------------- -String.class_eval do - def to_squawk - "squawk! #{self}".strip - end -end --------------------------------------------------------- - -When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly. - -To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking: - --------------------------------------------------------- -$ ./script/console ->> "Hello World".to_squawk -=> "squawk! Hello World" --------------------------------------------------------- - -If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class. diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt new file mode 100644 index 0000000000..dc9ef6bc29 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/test_setup.txt @@ -0,0 +1,222 @@ +== Preparation == + +=== Create the basic app === + +The examples in this guide require that you have a working rails application. To create a simple rails app execute: + +------------------------------------------------ +gem install rails +rails yaffle_guide +cd yaffle_guide +script/generate scaffold bird name:string +rake db:migrate +script/server +------------------------------------------------ + +Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. + +.Editor's note: +NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. + + +=== Generate the plugin skeleton === + +Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. + +This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. + +Examples: +---------------------------------------------- +./script/generate plugin yaffle +./script/generate plugin yaffle --with-generator +---------------------------------------------- + +To get more detailed help on the plugin generator, type `./script/generate plugin`. + +Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now: + +---------------------------------------------- +./script/generate plugin yaffle --with-generator +---------------------------------------------- + +You should see the following output: + +---------------------------------------------- +create vendor/plugins/yaffle/lib +create vendor/plugins/yaffle/tasks +create vendor/plugins/yaffle/test +create vendor/plugins/yaffle/README +create vendor/plugins/yaffle/MIT-LICENSE +create vendor/plugins/yaffle/Rakefile +create vendor/plugins/yaffle/init.rb +create vendor/plugins/yaffle/install.rb +create vendor/plugins/yaffle/uninstall.rb +create vendor/plugins/yaffle/lib/yaffle.rb +create vendor/plugins/yaffle/tasks/yaffle_tasks.rake +create vendor/plugins/yaffle/test/core_ext_test.rb +create vendor/plugins/yaffle/generators +create vendor/plugins/yaffle/generators/yaffle +create vendor/plugins/yaffle/generators/yaffle/templates +create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb +create vendor/plugins/yaffle/generators/yaffle/USAGE +---------------------------------------------- + + +=== Setup the plugin for testing === + +In this guide you will learn how to test your plugin against multiple different adapters using Active Record. This guide will not cover how to use fixtures in plugin tests. + +To setup your plugin to allow for easy testing you'll need to add 3 files: + + * A 'database.yml' file with all of your connection strings. + * A 'schema.rb' file with your table definitions. + * A test helper that sets up the database before your tests. + +*vendor/plugins/yaffle/test/database.yml:* + +---------------------------------------------- +sqlite: + :adapter: sqlite + :dbfile: yaffle_plugin.sqlite.db + +sqlite3: + :adapter: sqlite3 + :dbfile: yaffle_plugin.sqlite3.db + +postgresql: + :adapter: postgresql + :username: postgres + :password: postgres + :database: yaffle_plugin_test + :min_messages: ERROR + +mysql: + :adapter: mysql + :host: localhost + :username: rails + :password: + :database: yaffle_plugin_test +---------------------------------------------- + +For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: + +*vendor/plugins/yaffle/test/schema.rb:* + +[source, ruby] +---------------------------------------------- +ActiveRecord::Schema.define(:version => 0) do + create_table :hickwalls, :force => true do |t| + t.string :name + t.string :last_squawk + t.datetime :last_squawked_at + end + create_table :wickwalls, :force => true do |t| + t.string :name + t.string :last_tweet + t.datetime :last_tweeted_at + end +end +---------------------------------------------- + +*vendor/plugins/yaffle/test/test_helper.rb:* + +[source, ruby] +---------------------------------------------- +ENV['RAILS_ENV'] = 'test' +ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' + +require 'test/unit' +require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) + +config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) +ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") + +db_adapter = ENV['DB'] + +db_adapter ||= + begin + require 'rubygems' + require 'sqlite' + 'sqlite' + rescue MissingSourceFile + begin + require 'sqlite3' + 'sqlite3' + rescue MissingSourceFile + end + end + +if db_adapter.nil? + raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." +end + +ActiveRecord::Base.establish_connection(config[db_adapter]) + +load(File.dirname(__FILE__) + "/schema.rb") + +require File.dirname(__FILE__) + '/../init.rb' + +class Hickwall < ActiveRecord::Base +end + +class Wickwall < ActiveRecord::Base +end +---------------------------------------------- + +=== Run the plugin tests === + +Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: + +*vendor/plugins/yaffle/test/yaffle_test.rb:* + +[source, ruby] +---------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' + +class YaffleTest < Test::Unit::TestCase + + def test_active_record_classes_from_test_helper + assert_kind_of Hickwall, Hickwall.new + assert_kind_of Wickwall, Wickwall.new + end + +end +---------------------------------------------- + +To run this, go to the plugin directory and run `rake`: + +---------------------------------------------- +cd vendor/plugins/yaffle +rake +---------------------------------------------- + +You should see output like: + +---------------------------------------------- +/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" +-- create_table(:hickwalls, {:force=>true}) + -> 0.0220s +-- create_table(:wickwalls, {:force=>true}) + -> 0.0077s +-- initialize_schema_migrations_table() + -> 0.0007s +-- assume_migrated_upto_version(0) + -> 0.0007s +Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader +Started +. +Finished in 0.002236 seconds. + +1 test, 1 assertion, 0 failures, 0 errors +---------------------------------------------- + +By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake: + +---------------------------------------------- +rake DB=sqlite +rake DB=sqlite3 +rake DB=mysql +rake DB=postgresql +---------------------------------------------- + +Now you are ready to test-drive your plugin! -- cgit v1.2.3