Testing in Rails
Rails test is very simple to write and run for your application. As Rails script generates models and controllers, in the same way test files are also generated. Rails also uses a separate database for testing. Test database in an application is rebuilt each time the application’s test run, and hence you always have a consistent database when your tests are run.
Rails uses Ruby Test::Unit testing library. Rails application test is usually run using Rake utility.
Rails Test Directory
The test directory contains all of the test files that Rails generates, which is used to build the tests for your application. Test directory has the following directory structure.
Rails basically supports three types of tests:
- unit tests
The fixtures in test directory allows you to set up test data that can be used by your applications. It saves a lot of time and effort while writing Rails tests.
For writing tests, you have to first write code that will create test data and get database into a known populated state. Rails fixtures do most of that work for you.
Mocks are classes that allow replacing dependencies that are difficult to deal with.
Functional tests: Functional tests are used to test an application’s controller methods. When a controller class is generated using script/generate command, Rails also generates functional test files that will be used to write functional tests.
Unit tests: Unit tests are used to test methods contained in the model classes. These tests are mainly used to test the business logic which are present in models. It is the most popular form of testing supported by Rails.
Integation tests: Integration tests allow test interaction between multiple controllers. The allow testing more complete user scenarios or cases from application. Another reason to use it is that it simulate a user clicking around and accessing various pages that make up your application.
Rails Test Lifecycle
When Rails application’s test is run, a standard lifecycle is followed each time. This lifecycle consists of following steps:
- load up test fixtures – This clears the database tables and loads your fixture data into database.
- If test accesses data, it is read from the database.
- After test run, database is rolled back to its starting state.
This whole lifecycle is carried out by Rails each time you run your tests using the Rake command.