paulcarey (owner)

Forks

Revisions

gist: 48658 Download_button fork
public
Public Clone URL: git://gist.github.com/48658.git
Embed All Files: show embed
player_spec.rb #
1
2
3
4
5
6
7
8
9
10
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
 
spec_helper.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# 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