Topic: Fixtures w/o a Database

At the risk of flogging a dead horse, I cobbled together some code that emulates the Rails fixtures. First, how it works:

# ... your test headers here ...

no_db_fixtures :foos, :bars

# ...

def TestFoo
  my_foo = foos(:first_foo)
  # ...
end


As you can see, what's being returned by this is a hash similar to the one you would use to populate AR via a new() call. It's quite useful for testing mailers.

My request: Please look over the code below (goes in test_helper.rb) and tell me if I got it right.

module Test
  module Unit
    class TestCase
     
      @@all_fixtures = {}
     
      def self.no_db_fixture(fixture)
        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

      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

Re: Fixtures w/o a Database

Looks very nice.  I think I have a task that will need something like this later this weekend.

I still wish Rails used more sane testing terminology, but that's neither here nor there...

My RoR journey  -- thoughts on learning RoR and lessons learned in applying TDD and agile practices.