UnitRecord

This plugin provides unit testing for ActiveRecord by disconnecting tests from the database.

The Benefits

Rationale: www.dcmanges.com/blog/rails-unit-record-test-without-the-database

One huge benefit to disconnecting unit tests from the database is having a faster test suite. Here is the benchmark from one of my current projects:

Finished in 11.541093 seconds.
3001 tests, 5325 assertions, 0 failures, 0 errors

Installation

gem install unit_record

Usage

Restructuring the Rails Test Directory

The Rails test directory typically places testing for models under test/unit and tests for controllers under test/functional. However, we need to change the definition of unit and functional. Controllers can be unit tested (mocking out models and not rendering the view). Models can be functionally tested (hitting the database). Also, each type of test needs its own test_helper. I recommend restructuring your test directory like this:

test
  test_helper.rb
  unit
    unit_test_helper.rb
    controllers
    models
  functional
    functional_test_helper.rb
    controllers
    models

You should move existing functional tests into functional/controllers. You will also need to change the require line at the top of those tests to require the functional_test_helper.rb file instead of the test_helper.rb file.

The functional_test_helper.rb file only needs to require test_helper.rb:

require File.dirname(__FILE__) + "/../test_helper"

For moving unit tests, you have a few options. I recommend moving them to unit/models and then disconnecting your unit tests from the database. Any tests that fail should then be modified to not hit the database or moved to functional/models.

Disconnecting

In the test/unit/unit_test_helper.rb file you created when restructuring your test directory, you should add these lines:

require File.dirname(__FILE__) + "/../test_helper"
require "unit_record"
ActiveRecord::Base.disconnect!

The disconnect! method will do everything necessary to run your unit tests without hitting the database.

Thanks

Thanks to Jay Fields for the original implementation: blog.jayfields.com/2007/03/rails-activerecord-unit-testing-part-ii.html

License

Released under Ruby’s license. www.ruby-lang.org/en/LICENSE.txt