Skip to content

Instantly share code, notes, and snippets.

@paulcarey
Created January 18, 2009 13:44
Show Gist options
  • Save paulcarey/48658 to your computer and use it in GitHub Desktop.
Save paulcarey/48658 to your computer and use it in GitHub Desktop.
it "should know one another" do
# Code in the cdb block is executed if and only if it hasn't already been run.
cdb do
p1, p2 = Player.stock(:name => "p1"), Player.stock(:name => "p2")
p1.acquaint p2
end
p1.should know(p2) # p1 and p2 are methods that load players by names p1 and p2
p2.should know(p1)
end
# require 'Ruby2Ruby' # if not already required
def cdb(&blk)
base_db = "base_db"
test_db = "test_db"
# prepend bespoke_db with a subdir if required e.g. "specs/#{inst...}"
bespoke_db = instance_variable_get(:@_defined_description).gsub(' ', '_')
LazyCouch::CouchDBDefs.add_method(bespoke_db, &blk)
method_def = RubyToRuby.translate(LazyCouch::CouchDBDefs, bespoke_db.to_sym)
c = LazyCouch::Creator.new(base_db, bespoke_db, test_db, method_def)
if !c.bespoke_db_up_to_date? || ENV["REBUILD"]
c.create_bespoke_db(&blk)
end
c
end
def cdb_rw(&blk)
cdb(&blk).setup_test_db
end
class CouchDBDef < RelaxDB::Document
property :method_def
end
module LazyCouch
class CouchDBDefs
def self.add_method(method_name, &blk)
class_eval do
define_method(method_name, &blk)
end
end
end
class Creator
def initialize(base_db, bespoke_db, test_db, method_def)
@base_db = base_db # db containing reference data
@bespoke_db = bespoke_db # adds test specific data to base_db - read only
@test_db = test_db # replica of bespoke_db - read write
@method_def = method_def # lambda as string of the test specific data
end
def bespoke_db_up_to_date?
RelaxDB.db.name = @bespoke_db
cdb_def = RelaxDB.load "couchdb_def"
cdb_def && cdb_def.method_def == @method_def
end
def create_bespoke_db(&blk)
RelaxDB.delete_db @bespoke_db rescue :ok
RelaxDB.replicate_db @base_db, @bespoke_db
RelaxDB.use_db @bespoke_db
CouchDBDef.new(:_id => "couchdb_def", :method_def => @method_def).save!
blk.call
end
def setup_test_db
RelaxDB.delete_db @test_db rescue :ok
RelaxDB.replicate_db @bespoke_db, @test_db
RelaxDB.use_db @test_db
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment