require 'minitest/autorun' require 'minitest/unit' require 'mocha/mini_test' require './test/helper.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 CouchPillow.db = FakeCouchbaseServer.new 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 def test_rename_keys_reserved_keys assert_raises ArgumentError do d = Class.new(Document) do rename :_id, :bad end.new end assert_raises ArgumentError do d = Class.new(Document) do rename :_type, :err end.new end assert_raises ArgumentError do d = Class.new(Document) do rename :created_at, :err end.new end assert_raises ArgumentError do d = Class.new(Document) do rename :bla, :updated_at end.new end end def test_get_returns_nil CouchPillow.db.expects(:get).with('123').returns(nil) d = Document.get('123') assert_equal nil, d end end