Skip to content

Instantly share code, notes, and snippets.

@ahoward
Created August 31, 2012 15:22
Show Gist options
  • Save ahoward/3554498 to your computer and use it in GitHub Desktop.
Save ahoward/3554498 to your computer and use it in GitHub Desktop.
don't truncate, return to known good state with specific test seeds
# general support for dumping the post db:seed db to a hash
#
def App.db_names
result =
Mongoid.session(:default).
with(database: :admin).
command({listDatabases:1})
result['databases'].map{|hash| hash['name']}
end
def App.db_name
Mongoid::Sessions.default.send(:current_database).name
end
def App.db_collections
Mongoid::Sessions.default.collections
end
def App.db_snapshot
$db_collections = Map.new
db_collections.each do |collection|
name = collection.name
next if name =~ /\bsystem\b|\$/
documents = collection.find().to_a
unless documents.blank?
$db_collections[name] = documents
end
end
$db_collections
end
def App.db_restore(snapshot = $db_collections)
collections = db_collections
(snapshot || Map.new).each do |name, documents|
collection = collections.detect{|collection| collection.name == name}
unless collection.blank? or documents.blank?
collection.drop
documents.each{|document| collection.insert(document)}
end
end
end
## due to lack of transactions in mongoid we snapshot the db before any test
# is run and then restore to this snapshot before each test *suite* is run. we
# would like to restore before each test but it is simple too slow. the side
# effect is that tests can pollute one another, but test suites cannot. live
# with it.
#
#App.db_snapshot()
#at_exit{ App.db_restore() }
test_db_yml = File.join(Rails.root, 'test/db.yml')
abort('rake db:test:prepare ### did you forget?') unless test(?e, test_db_yml)
TestDb = YAML.load(IO.read(test_db_yml))
class MiniTest::Unit::TestCase
before_all do
App.db_restore(TestDb)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment