Skip to content

Instantly share code, notes, and snippets.

@royw
Created November 1, 2009 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save royw/223778 to your computer and use it in GitHub Desktop.
Save royw/223778 to your computer and use it in GitHub Desktop.
require 'mongo_mapper'
require 'spec'
MongoMapper.connection = Mongo::Connection.new('localhost')
MongoMapper.database = 'tmp'
class Cast
include MongoMapper::EmbeddedDocument
key :person, Integer
key :name, String
key :age, Integer, :default => 0
end
class Movie
include MongoMapper::Document
key :name, String
many :casts
end
describe 'Movie' do
before :each do
Movie.collection.clear
movie = Movie.create(:name => 'Support Your Local Gunfighter')
movie.casts << Cast.new(:name => 'James Garner', :person => 16896)
movie.casts << Cast.new(:name => 'Suzanne Pleshette', :person => 8231)
movie.casts << Cast.new(:name => 'Jack Elam', :person => 4965)
movie.casts << Cast.new(:name => 'Harry Morgan', :person => 4073)
movie.save
movie = Movie.create(:name => 'Support Your Local Sheriff')
movie.casts << Cast.new(:name => 'James Garner', :person => 16896)
movie.casts << Cast.new(:name => 'Joan Hackett', :person => 69947)
movie.casts << Cast.new(:name => 'Jack Elam', :person => 4965)
movie.casts << Cast.new(:name => 'Harry Morgan', :person => 4073)
movie.casts << Cast.new(:name => 'Walter Brennan', :persion => 4302)
movie.save
end
it "should update embedded documents" do
movie = Movie.first
cast = movie.casts.select{|cast| cast.name == 'Jack Elam'}
cast.first.age = 83
movie.save
Movie.all(:conditions => {'casts.age' => 83}).size.should == 1
end
it "should find embedded documents" do
Movie.all("casts.name" => 'Jack Elam').size.should == 2
Movie.all("casts.name" => 'Joan Hackett').size.should == 1
Movie.all("casts.name" => 'Billy Bob').should be_empty
end
it "should delete embedded documents" do
movie = Movie.all(:conditions => {:name => /Support Your Local/}).first
movie.should_not be_nil
movie.casts.size.should == 4
movie.casts.delete_if{|cast| cast.person == 4965}
movie.save
movie.casts.size.should == 3
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment