Testing w/out DB connection

I have several plain ruby classes that do nothing but implement
algorithms. What is the prefferred way to run these w/out making a DB
connection every time?

Thanks,

Dennis Byrne

I have the same issue occasionally, and the issue is typically that
Rails
wants to load fixtures into the database as it is preparing to run the
tests. I have some code that I may package into a plugin if there is
interest. This allows you to use plugins but not hit the DB. Know,
however,
that this won’t take the database completely out of the loop; it just
allows
you to use fixtures in the absence of a database. Here’s some code you
can
drop into test_helper.rb:

module Test
module Unit
class TestCase

  @@all_fixtures = {}

  def self.no_db_fixture(fixture) #:nodoc:
    fixture_file = "#{RAILS_ROOT}/test/fixtures/#{fixture}.yml"
    raise FixtureClassNotFound(fixture) unless

File.exists?(fixture_file)

    docs = {}

    File.open(fixture_file) do |yf|
      YAML.load_documents(yf) do |ydoc|
        docs.merge! ydoc
      end
    end

    docs
  end

  # == Abstract
  #
  # This macro is used to mimic the normal Test::Unit::TestCase 

method
of populating a database
# from a fixture for cases where there is no database under test.
Examples of this are data-consuming
# functions in /lib, or forms derived from ActiveRecord with the
connection set to nil. In these cases,
# fixtures make testing more flexible, but you can’t just push the
fixture data into your default test
# database.
#
# == Example
#
# class ContactMailerTest
# no_db_fixtures :contacts
#
# …
#
# def test_sent
# contact = Contact.new contacts(:joe) # assuming
contacts.yml
contains a contact named “joe”
# assert_valid contact
# end
# end
#
# == Exceptions
#
# +FixtureClassNotFound+ if the fixture file does not exist in the
test/fixtures directory.
# +RuntimeError+ if the fixtures wind up nil or no method for a
given
fixture exists. If you get this error, it’s likely a bug.

  def self.no_db_fixtures(*args)
    @@all_fixtures = {}
    args.each do |arg|
      arg = arg.to_s
      @@all_fixtures[arg] = no_db_fixture(arg)
      define_method(arg) do |value|
        raise "all fixtures nil" if @@all_fixtures.nil?
        raise "no fixture method: #{value}" unless

@@all_fixtures[arg][value.to_s]
return @@all_fixtures[arg][value.to_s]
end
end
end
end
end
end


View this message in context:
http://www.nabble.com/Testing-w-out-DB-connection-tf1993050.html#a5469995
Sent from the RubyOnRails Users forum at Nabble.com.