Home arrow Ruby-on-Rails arrow Page 3 - Error Checking and Debugging with Ruby on Rails
RUBY-ON-RAILS

Error Checking and Debugging with Ruby on Rails


In this conclusion to a six-part series covering web development and Ruby on Rails, you'll learn how to send error messages to your email and more. This article is excerpted from chapter 15 of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 5 stars5 stars5 stars5 stars5 stars / 3
April 26, 2007
TABLE OF CONTENTS:
  1. · Error Checking and Debugging with Ruby on Rails
  2. · 15.21 Documenting Your Web Site
  3. · 15.22 Unit Testing Your Web Site
  4. · 15.23 Using breakpoint in Your Web Application

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

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


blog comments powered by Disqus
RUBY-ON-RAILS ARTICLES

- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form
- Ruby on Rails Templates and Layouts
- Action Pack Controller Creation
- Writing an Action Pack Controller

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 7 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials