Skip to content

Instantly share code, notes, and snippets.

@semanticart
Created November 1, 2009 17:43
Show Gist options
  • Select an option

  • Save semanticart/223631 to your computer and use it in GitHub Desktop.

Select an option

Save semanticart/223631 to your computer and use it in GitHub Desktop.
# run the script and pass the path to your mongo/bin
# i.e.
# ruby mongodb_import_test.rb ~/Downloads/mongodb-osx-x86_64-1.0.1/bin
require 'rubygems'
require 'test/unit'
require 'mongo'
include Mongo
db = Connection.new('localhost').db('test-import')
Artist = db.collection('artists')
BIN_PATH = ARGV[0] || ""
raise "please specify the path to your mongo/bin directory" unless File.exist?(BIN_PATH + "/mongoimportjson")
class MongoSanityTest < Test::Unit::TestCase
def setup
Artist.remove
@id = Artist.insert(:name => "SOME NAME")
end
def test_can_create_a_record
assert !Artist.find_one(:_id => @id).nil?
end
def test_can_update_a_record
Artist.update({:_id => @id}, {:_id => @id, :name => "new name"})
assert_equal Artist.find_one(:_id => @id)["name"], "new name"
# we have just one record since we did an update instead of an insert
assert_equal Artist.count, 1
end
end
class MongoImportTest < Test::Unit::TestCase
def setup
# drop our json import file which contains a single record
File.open('out.json', 'w') do |f|
f.puts %({ "_id" : "4aecaaa7f62c1923628c36a8", "name" : "IMPORTED RECORD" })
end
# do the actual importing and pass --drop to ensure the collection is emptied first
`#{BIN_PATH}/mongoimportjson -d test-import --drop -c artists out.json`
# ensure we imported our record properly
assert Artist.find_one(:name => "IMPORTED RECORD")
# and that there is only one
assert_equal Artist.count, 1
end
def test_can_create_a_record_after_import
id = Artist.insert(:name => "SOME NAME")
assert !Artist.find(:_id => id).nil?
assert_equal Artist.count, 2
end
def test_can_update_a_record_after_import
artist = Artist.find_one(:name => "IMPORTED RECORD")
assert artist
# we rename our artist
Artist.update({:_id => artist["_id"]}, {:_id => artist["_id"], :name => "new name"})
# we check that the name was updated
assert_equal Artist.find_one(:_id => artist["_id"])["name"], "new name"
assert_equal Artist.count, 1
end
def test_that_we_can_update_the_name_natively
# use the mongo binary to update the name
`#{BIN_PATH}/mongo test-import --eval "db.artists.update({name: 'IMPORTED RECORD'}, {name: 'new name'});"`
# we have a record matching 'new name'
assert_equal Artist.find_one["name"], 'new name'
# we only have one record
assert_equal Artist.count, 1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment