require 'minitest/autorun' require 'minitest/unit' require 'mocha/mini_test' require './lib/couchpillow.rb' class TestDocument < Minitest::Test Document = CouchPillow::Document def mock_time return @time if @time @time = Time.now Time.stubs(:now).returns(@time) @time end def setup @db = mock('couchbaseserver') @db.stubs(:set) @db.stubs(:delete) @db.stubs(:replace) @db.stubs(:get) CouchPillow.db = @db end def test_create d = Document.new d.save! end def test_timestamp d = Document.new({}, "1") d.save! assert d.created_at assert d.updated_at end def test_type d = Document.new({}, "1") assert_equal "default", d._type end def test_type_subclasses d = Class.new(Document) do type 'test' end.new assert_equal "test", d._type end def test_validate_presence d = Class.new(Document) do validate_presence :xyz end.new assert_raises Document::ValidationError do d.save! end d.xyz = 10 d.save! end def test_validate_type d = Class.new(Document) do validate_type :abc, Hash end.new d.abc = "other type" assert_raises Document::ValidationError do d.save! end d.abc = { :hello => "world" } d.save! end def test_validate_custom d = Class.new(Document) do validate :xyz, "must be Numeric", lambda { |v| v.is_a? Numeric } end.new d.xyz = "string" assert_raises Document::ValidationError do d.save! end d.xyz = {} assert_raises Document::ValidationError do d.save! end d.xyz = 123 d.save! end def test_to_json mock_time d = Document.new({}, "1") assert_equal "{\"_id\":\"1\",\"created_at\":\"#{mock_time.to_s}\",\"_type\":\"default\"}", d.to_json end def test_brackets d = Document.new({}) d[123] = 'test' assert_equal 'test', d[123] d['foo'] = 'bar' assert_equal 'bar', d[:foo] d[:stuff] = [ 'john', 'mary' ] assert_equal ['john', 'mary'], d[:stuff] assert_equal nil, d[:something_else] end def test_rename_keys d = Class.new(Document) do rename :foo, :bar end.new( { :foo => 123, :other => 'abc' } ) assert_equal 123, d[:bar] assert_equal 123, d.bar assert_equal nil, d[:foo] refute d.respond_to?(:foo) assert_equal 'abc', d.other end end