Skip to content

Instantly share code, notes, and snippets.

@maciejmajewski
Last active November 5, 2018 17:32
Show Gist options
  • Save maciejmajewski/2bfcce94c8ead4d62fc3aa42971c0739 to your computer and use it in GitHub Desktop.
Save maciejmajewski/2bfcce94c8ead4d62fc3aa42971c0739 to your computer and use it in GitHub Desktop.

To run example:

bundle install

bundle exec ruby mongoid_test.rb
gem "minitest", "~> 5.11"
gem "mongoid", "~> 7.0"
GEM
specs:
activemodel (5.2.0)
activesupport (= 5.2.0)
activesupport (5.2.0)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 0.7, < 2)
minitest (~> 5.1)
tzinfo (~> 1.1)
bson (4.3.0)
concurrent-ruby (1.0.5)
i18n (1.0.1)
concurrent-ruby (~> 1.0)
minitest (5.11.3)
mongo (2.5.3)
bson (>= 4.3.0, < 5.0.0)
mongoid (7.0.1)
activemodel (>= 5.1, < 6.0.0)
mongo (>= 2.5.1, < 3.0.0)
thread_safe (0.3.6)
tzinfo (1.2.5)
thread_safe (~> 0.1)
PLATFORMS
ruby
DEPENDENCIES
minitest (~> 5.11)
mongoid (~> 7.0)
BUNDLED WITH
1.16.3
test:
clients:
default:
database: mongoid_test
hosts:
- dockerhost:27017
require 'rubygems'
require 'bundler/setup'
require 'mongoid'
require 'minitest/autorun'
Mongoid.load!('mongoid.yml', 'test')
class Band
include Mongoid::Document
has_and_belongs_to_many :tags
end
class Tag
include Mongoid::Document
has_and_belongs_to_many :bands
end
class TestHABTM < Minitest::Test
def setup
Band.delete_all
Tag.delete_all
@band = Band.new.save
@tag = Tag.new
end
# This example fails
def test_band_habtm_is_persisted_automatically_after_tag_is_saved
@tag.bands = Band.all
@tag.save!
assert_equal [@tag], Band.first.tags
end
def test_multiple_bands_are_persisted_automatically_after_tag_is_saved
Band.new.save
@tag.bands = Band.all
@tag.save!
assert_equal [@tag], Band.all[0].tags
assert_equal [@tag], Band.all[1].tags
end
def test_band_habtm_is_persisted_after_tag_is_saved
@tag.save!
@tag.bands = Band.all
assert_equal [@tag], Band.first.tags
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment