Skip to content

Instantly share code, notes, and snippets.

@nmk
Created September 25, 2011 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nmk/1240835 to your computer and use it in GitHub Desktop.
Save nmk/1240835 to your computer and use it in GitHub Desktop.
Mongoid standalone/embedded
require 'mongoid'
require 'minitest/autorun'
Mongoid.configure do |config|
config.master = Mongo::Connection.new.db('basket_test')
end
class Basket
include Mongoid::Document
recursively_embeds_many
embeds_one :fruit
end
class Fruit
include Mongoid::Document
field :name
end
class BasketTest < MiniTest::Unit::TestCase
def test_an_embedded_basket_can_have_a_fruit
basket = Basket.create(fruit: Fruit.new(name: 'apple'), child_baskets: [Basket.new])
basket.reload
assert_equal 1, basket.child_baskets.size
embedded_basket = basket.child_baskets.first
embedded_basket.fruit = Fruit.new(name: 'banana')
embedded_basket.save!
basket.reload
assert ! basket.child_baskets.first.fruit.nil?,
'The embedded basket\'s fruit is lost.'
end
def test_fruits_can_be_standalone_as_well
Fruit.create(name: 'apple')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment