Sunday, January 11, 2009

Test rails with Mocha

Rails is a framework that came up with facilities for testing using fixtures. Testing using  fixture is a nice feature to have for a small project. But as the project grows some problems might be seen. Like,

  1. Difficult to manage fixture
  2. Takes long time to run the test

Difficult to manage fixture:

As it becomes hard to manage fixtures, people tends to add and do not intend to reuse existing, as that might break current test codes.

So the number of the entry in fixtures increase day by day. Eventually it becomes unmanageable.

Takes long time to run the test:

As fixture driven testing takes a lot time to run the test. People don't feel comfortable to run test for a large project. Even running one test file sometime takes 2/3 minutes. We use Continuous Integration(CI) to run test for the whole project in different server, while we do our regular tasks. But even that is not working out for us right now. Because, It takes about 30 minutes to test the whole project. CI looks up in repository and check for changes and if found any, it starts to build and run test. So If any code is checked in with in with in 30 minutes while the build is not completed, then that build goes into queue. And eventually we get the email notification from CI after 1/2 hours. Which is not satisfying the purpose of CI.

Solution:

I read about Mocha and really got interested. It is a solution to fixtures. You can use mock object to replace fixtures. At first I was confused about how should I mock my model objects. As it contains the business logic as well as the logic to save in database. Mocha gives you a solution as it gives facility to overwrite methods for an object without writing a real class. So you can mock save or find method of ActiveRecord and replace it with mock method with out creating a class. You can even mock a private method. Here is an example.

No comments: