Monday, November 2, 2009

Recipe 15.22. Unit Testing Your Web Site










Recipe 15.22. Unit Testing Your Web Site







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.


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.rb
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 relationships 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:


  • assert_dom_equal

  • assert_dom_not_equal

  • assert_generates

  • assert_no_tag

  • assert_recognizes

  • assert_redirected_to

  • assert_response

  • assert_routing

  • assert_tag

  • assert_template

  • assert_valid




See Also


  • "Testing the Rails" is a guide to unit and functional testing in Rails (http://manuals.rubyonrails.com/read/book/5)

  • 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

  • The ZenTest library inclues Test::Rails, which lets you write separate tests for your views and controllers (http://rubyforge.org/projects/zentest/)

  • Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html

  • Read about the assertions that Rails adds to Test::Unit at http://rails.rubyonrails.com/classes/Test/Unit/Assertions.html

  • Recipe 15.6, "Integrating a Database with Your Rails Application"

  • Recipe 17.7, "Writing Unit Tests"

  • Chapter 19













No comments: