Skip to content
alanjds edited this page May 30, 2012 · 11 revisions

The “doctest_require:” Directive

See the Special Directives for a full explanation of the

doctest_require:
directive. To get started quickly in rails, this is probably the directive you will want to use in order to load the environment.rb file before the file gets loaded.

Example Usage

doctest_require: "../../config/environment"

By putting the above line before anything in your file (say, app/model/book.rb) you will have DocTest load the Rails environment before it runs the tests in your documentation.

You can specify rails’ environment thus:

doctest_require: ENV['RAILS_ENV'] = 'test'; "../../config/environment"

Database cleanup between doctests

In the previous examples, in case you create some models in your database, they will not be deleted after the doctest is run. This is where database_cleaner (and some monkey patching) may help.

Create a “test/rubydoctest_helper.rb” file with:


ENV['RAILS_ENV'] = 'test'

require File.dirname(__FILE__) + '/../config/environment'
require 'database_cleaner'

DatabaseCleaner.strategy = :transaction

module RubyDocTest
  class Test
    alias :old_pass? :pass?

    def pass?
      DatabaseCleaner.start
      result = old_pass?
      DatabaseCleaner.clean
      result
    end
  end
end

Then, before each doctest:


# doctest_require: "../../test/rubydoctest_helper"

Now, each doctest will be wrapped into a transaction that will be rolled back once the test is done.