Ruby on Rails 2.1 Unit Testing - Ruby on Rails 2.1

What is Rails testing?


Testing is the process to make sure that everything is developed as required.

Components of testing

  • Tests − they are test applications that produce consistent result and prove that a Rails application does what it is expected to do. Tests are developed concurrently with the actual application.
  • Assertion − this is a one line of code that evaluates an object (or expression) for expected results. For example, is this value = that value? Is this object nil?
  • Test Case − this is a class inherited from Test::Unit::TestCase containing a testing strategy comprised of contextually related tests.
  • Test Suite − this is a collection of test cases. When user runs a test suite, it executes each test that belongs to it.

Rails Testing

Rails generate a framework for unit and functional tests, when user runs the helper script script/generate to create controllers and models. User gets automatic test coverage by adding in the framework with tests for the functionality written.

In Rails application there are two imported things to be tested, following

  • Testing the Models.
  • Testing the Controllers.

Before starts with testing, let's create testapp to understand the concept.

Database Setup

Let’s create testing database and set up config/database.yml file correctly.

Create both development and testing databases as shown below

Configuring database.yml

Configure required config/database.yml as shown below

Generate Migration

Migration can set up table for, books including their titles, price and description. The following migration sets up this table

Modify the testapp/db/migrate/20080616170315_books.rb file as following below

Above command will create books table in testapp_development database.

Once done creating above database, set up test database using rake command as following below

The given command makes a replica of testapp_development database into testapp_test database. Which means whatever you have in development database, will have it in test database as well.

Testing Models

Rails also generates a unit test script for the model in the test directory, when user generates a model with the generate script, which creates a fixture, a YAMLfile containing test data to be loaded into the testapp_test database. This is the data against which unit tests will run

Let's create two test book records using YAML in test/fixtures/books.yml to keep corresponding tests in these files.

Now replace the existing code in book unit test file test/unit/book_test.rb with the below code

Once done, run the test method by applying below

Here's the output for the test case ran successfully

What has done here?

  • A new Book object using the title and other fields from the first record in the text fixture/books.yml will be created by BookTest method and the results (object) 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. Testing the ability to create and read a database record is done.
  • 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.
  • At the end, ability to destroy a Book object is tested.

This is how we can test our Rails Models.

Testing Controllers

Functional testing will be done to test Controller, which concentrates on functional aspects of the Controller. Following are the functionalities of the controllers, which will be tested under functional testing

  • Is the response redirected as expected?
  • Is the expected template rendered?
  • Is the routing as expected
  • Does the response contain the expected tags?

Rails framework supports 5 types of requests to write a functional test, user needs to create any of the five HTTP request types, which user’s controller will process

  • get
  • post
  • put
  • head
  • delete

Request type "get" and "post" are the most commonly used in controller testing.

These methods take after four actions of controller, as shown below

  • Action of a controller
  • Optional hash of request parameters
  • Optional session hash
  • Optional flash hash

All these five methods work the same way. Let’s discuss one method here.

Here, we see how to use get method to test controller.

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

Let's define controller functions list, show, and searchinside app/controllers/book_controller.rb(See below), which contains corresponding tests files.

Please note, show and list method requires views templates. User can define those views and test them.

Here, lets continue without defining those views.

Now let's reuse our test fixture which is in test/fixtures/books.yml file as follows

Add the following test_search_book and test_search_not_found methods totest/functional/book_controller_test.rb to test the functionality of the Book Controller's search action.

And run test cases following below

This gives user following output

What has done here?

  • The setup method is a default method to create controller, request and response objects. They will be used by Rails internally.
  • The first test method test_search_book generates a get request to the search action, passing in a title parameter.
  • The next two assertions verify that a Book object was saved in an instance variable called @book and that the object passes any Active Record validations that might exist.
  • The final assertion inside first method tests that the request was redirected to the controller's show action.
  • The second test method, test_search_not_found, performs another getrequest but passes in an invalid title.
  • The first assertions test that a redirect to the list action was issued.
  • If the proceeding assertions passed, there should be a message in theflash hash which you can test with assert_equal.

Using Rake for testing

To test applications, User can also use rake utility.

Here are few important rake commands.

  • $rake test – Does all types of tests, like unit, integration and functional.
  • $rake test:functionals− Run all functional tests.
  • $rake test:units − Run all unit tests.
  • $rake test:integration − Run all integration tests.
  • $rake test:plugins − Run all test in ./vendor/plugins/**/test.
  • $rake test:recent − Run tests for models and controllers that have been modified in the last 10 minutes
  • $rake test:uncommitted − For projects in Subversion, run tests for models and controllers changes since last commit.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

Ruby on Rails 2.1 Topics