Unit Testing in Ruby on 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 testapp_test database. This is the data against which your unit tests will run:
testapp > ruby script/generate model Book
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/book.rb
create test/unit/book_test.rb
create test/fixtures/books.yml
create db/migrate
create db/migrate/20080616164236_create_books.rb
As you write code in the model classes, you'll write corresponding tests in these files. So let's create two test book records using YAML in test/fixtures/books.yml as follows:
perl_cb:
id: 1
title: 'Ruby Tutorial'
price: 102.00
description : 'This is a nice Ruby tutorial'
java_cb:
id: 2
title: 'Java Programming'
price: 62.00
description : 'Java Programming for the beginners'
Now let's relace exsiting code in book unit test file test/unit/book_test.rb with the following code:
require File.dirname(__FILE__) + '/../test_helper'
class BookTest < ActiveSupport::TestCase
fixtures :books
def test_book
perl_book = Book.new :title => books(:perl_cb).title,
:price => books(:perl_cb).price,
:description => books(:perl_cb).description,
:created_at => books(:perl_cb).created_at
assert perl_book.save
perl_book_copy = Book.find(perl_book.id)
assert_equal perl_book.title, perl_book_copy.title
perl_book.title = "Ruby Tutorial"
assert perl_book.save
assert perl_book.destroy
end
end
Finally, run the test method as follows:
testapp > ruby test/unit/book_test.rb
Here's the output of running the successful test case:
testapp > ruby test/unit/book_test_crud.rb
Loaded suite ./test/unit/book_test
Started
.
Finished in 0.0625 seconds.
1 tests, 4 assertions, 0 failures, 0 errors
What has happend here:
The BookTest method starts off by creating a new Book object using the title and other fields from the first record in the text fixture/books.yml. The resulting object is stored in the perl_book instance variable.
The first assertion tests that saving the Book object was successful.
Next, the book object is retrieved using the find method and stored in another instance variable named perl_book_copy. The success of this retrieval is tested in the next assertion, which compares the titles of both book objects. At this point, we've tested the ability to create and read a database record.
The solution tests updating by assigning a new title to the object stored in perl_book and then asserts that saving the change is successful.
Finally, the ability to destroy a Book object is tested.
This is how we can test our Rails Models.

Comments :

0 comments to “Unit Testing in Ruby on Rails”

Post a Comment