CouchDBでRuby/RailsのTestUnitを使う

必要なデータは test/fixtures/couchdb/**/*.yml にいれておきます。以下のスクリプトRAILS_ROOT/lib あたりにおいときます。

class CouchFixture
  def self.load(basedir = File.join(RAILS_ROOT, "test/fixtures/couchdb/"))
    Dir.glob("#{basedir}/**/*.yml") do |f|
      # resolve class
      file = f.gsub(/^#{basedir}\//, '').gsub(/\.yml$/, '')
      klass = file.singularize.camelize.constantize
      # load yaml file
      content = YAML.load(ERB.new(File.read(f)).result)
      if content
        content.each do |key, value|
          value.symbolize_keys!
          value[:_id] = key unless value[:_id]
          obj = klass.find(value[:_id]) rescue nil
          obj.destroy if obj
          obj = klass.new(value)
          obj.save!
        end
      end
    end
  end
end

RAILS_ROOT/test/test_helper.rb で fixture :all というところがあるはずなので、こんな感じでCouchFixture.load を追加しておきます。

  # -- they do not yet inherit this setting
  fixtures :all

  # Add more helper methods to be used by all tests here...
  CouchFixture.load
end

なお、ActiveRecord の Fixture との違いは、、、テーブルという概念がないので、DELETE FROM table_name 相当のクリア処理が発行されないことです。データベース管理でなんとかしましょうか、ということで次のエントリ。