Ruby-on-Rails
  Home arrow Ruby-on-Rails arrow Page 3 - Error Checking and Debugging with Ruby on ...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Moblin 
JMSL Numerical Library 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
RUBY-ON-RAILS

Error Checking and Debugging with Ruby on Rails
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 3
    2007-04-26

    Table of Contents:
  • Error Checking and Debugging with Ruby on Rails
  • 15.21 Documenting Your Web Site
  • 15.22 Unit Testing Your Web Site
  • 15.23 Using breakpoint in Your Web Application

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Error Checking and Debugging with Ruby on Rails - 15.22 Unit Testing Your Web Site


    (Page 3 of 4 )

    Problem

    You want to create a suite of automated tests that test the functionality of your Rails application.

    Solution

    Rails can't write your test code any more than it can write your views and controllers for you, but it does make it easy to organize and run your automated tests.

    Rails can't write your test code any more than it can write your views and controllers for you, but it does make it easy to organize and run your automated tests.

    When you use the ./script/generate command to create controllers and models, not only do you save time, but you also get a generated framework for unit and functional tests. You can get pretty good test coverage by filling in the framework with tests for the functionality you write.

    So far, all the examples in this chapter have run against a Rails application's development database, so you only needed to make sure that the development section of your config/database.yml file was set up correctly. Unit test code runs on your application's test database, so now you need to set up your test section as well. Your mywebapp_test database doesn't have to have any tables in it, but it must exist and be accessible to Rails.

    When you generate a model with the generate script, Rails also generates a unit test script for the model in the test directory. It also creates a fixture, a YAML file containing test data to be loaded into the mywebapp_test database. This is the data against which your unit tests will run:

      ./script/generate model User
           
    exists  app/models/
           
    exists  test/unit/
           
    exists  test/fixtures/
           
    create  app/models/user.rb
           
    create  test/unit/user_test.rb
           
    create  test/fixtures/users.yml
           
    create  db/migrate
           
    create  db/migrate/ 001_create_users.rb

    When you generate a controller with generate, Rails creates a functional test script for the controller:

      ./script/generate users list
           
    exists  app/controllers/
           
    exists  app/helpers/
           
    create  app/views/users
           
    exists  test/functional/
           
    create  app/controllers/ users_controller.rb
           
    create test/functional/ users_controller_test.rb 
          
    create  app/helpers/
    users_helper.r b
            create  app/views/users/list.rhtml

    As you write code in the model and controller classes, you'll write corresponding tests in these files.

    To run the unit and functional tests, invoke the rake command in your home directory. The default Rake task runs all of your tests. If you run it immediately after generating your test files, it'll look something like this:

      $ rake  
      (in /home/lucas/mywebapp)
      /usr/bin/ruby1.8 "test/unit/user_test.rb"
      Started
      .
      Finished in 0.048702 seconds.

      1 tests, 1 assertions, 0 failures, 0 errors
      /usr/bin/ruby1.8 "test/functional/users_controller_test.rb"
      Started
      .
      Finished in 0.024615 seconds.

      1 tests, 1 assertions, 0 failures, 0 errors

    Discussion

    All the lessons for writing unit tests in other languages and in other Ruby programs (see Recipe 17.7) apply to Rails. Rails does some accounting for you, and it defines some useful new assertions (see below), but you still have to do the work. The rewards are the same, too: you can modify and refactor your code with confidence, knowing that if something breaks, your tests will break. You'll hear about the problem immediately and you'll be able to fix it more quickly.

    Let's see what Rails has generated for us. Here's a generated test/unit/user_test.rb:

      require File.dirname(__FILE__) + '/../test_helper'

      class UserTest < Test::Unit::TestCase 
        fixtures :users

        # Replace this with your real tests.
        def test_truth
          assert true
        end
      end

    A good start, but test_truth is kind of tautological. Here's a slightly more realistic test:

      class UserTest
        def test_first
          assert_kind_of User, users(:first)
        end
      end

    This code fetches the first element from the users table, and asserts that ActiveRecord turns it into a User object. This isn't testing our User code (we haven't written any) so much as it's testing Rails and ActiveRecord, but it shows you the kind of assertion that makes for good unit tests.

    But how does users(:first) return anything? The test suite runs against the mywebapp_test database, and we didn't even put any tables in it, much less sample data.

    We didn't, but Rails did. When you run the test suite, Rails copies the schema of the development database to the test database. Instead of running every test against whatever data happens to exist in the development database, Rails loads special test data from YAML files called fixtures. The fixture files contain whatever database data you need to test: objects that only exist to be deleted by a test, strange relation ships between rows in different tables, or anything else you need.

    In the example above, the fixture for the users table was loaded by the line fixtures :users. Here's the generated fixture for the User model, in test/fixtures/users.yml:

      first:
        id: 1
      another:
       
    id: 2

    Before running the unit tests, Rails reads this file, creates two rows in the users table, and defines aliases for them (:first and :another) so you can refer to them in your unit tests. It then defines the users method (like so much else, this method name is based on the name of the model). In test_first, the call to users(:first) retrieves the User object corresponding to :first in the fixture: the object with ID 1.

    Here's another unit test:

      class UserTest
       
    def test_another
          assert_kind_of User, users(:another)
          assert_equal 2, users(:another).id
          assert_not_equal users(:first), users(:another)
       
    end
      end

    Rails adds the following Rails-specific assertions to Ruby's Test::Unit:

    1. assert_dom_equal
    2. assert_dom_not_equal
    3. assert_generates
    4. assert_no_tag
    5. assert_recognizes
    6. assert_redirected_to
    7. assert_response
    8. assert_routing
    9. assert_tag
    10. assert_template
    11. assert_valid

    See Also

    1. "Testing the Rails" is a guide to unit and functional testing in Rails (http:// manuals.rubyonrails.com/read/book/5)
    2. Rails 1.1 supports integration testing as well, for testing the interactions between controllers and actions; see http://rubyonrails.com/rails/classes/ActionController/ IntegrationTest.html and http://jamis.jamisbuck.org/articles/2006/03/09/ integration-testing-in-rails-1-1
    3. The ZenTest library inclues Test::Rails, which lets you write separate tests for your views and controllers (http://rubyforge.org/projects/zentest/)
    4. Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
    5. Read about the assertions that Rails adds to Test::Unit at http://rails.rubyonrails. com/classes/Test/Unit/Assertions.html
    6. Recipe 15.6, "Integrating a Database with Your Rails Application"
    7. Recipe 17.7, "Writing Unit Tests"
    8. Chapter 19

    More Ruby-on-Rails Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "Ruby Cookbook," published by O'Reilly. We...
     

    Buy this book now. This article is excerpted from chapter 15 of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Check it out today at your favorite bookstore. Buy this book now.

    RUBY-ON-RAILS ARTICLES

    - Comparing and Manipulating Strings in Ruby
    - Strings in Ruby
    - Ruby On Rails: Making Your First Dynamic Site
    - Ruby on Rails: Beginning Rails
    - Ruby: Modules, Mixins, Fixins, and Rails
    - Controlling Information Access with the Rail...
    - URLs, Filters and the Rails Action Controller
    - Flash and the Rails Action Controller
    - Rails Action Controller
    - Dropping and Sorting with AJAX and script.ac...
    - Drag and Drop with script.aculo.us and Rails
    - Introducing script.aculo.us
    - Ruby Classes and Objects
    - Ruby Loops
    - Ruby Conditionals







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway