Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
60 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
require_relative 'test_helper' | ||
|
||
class JSONifiable | ||
def initialize(object) | ||
@object = object | ||
end | ||
def as_json | ||
@object | ||
end | ||
end | ||
|
||
describe JSI::Typelike do | ||
describe 'as_json' do | ||
it 'expresses as json' do | ||
assert_equal({}, JSI::Typelike.as_json({})) | ||
assert_equal([], JSI::Typelike.as_json([])) | ||
|
||
# symbols to string | ||
assert_equal(['a'], JSI::Typelike.as_json([:a])) | ||
|
||
# set | ||
assert_equal(['a'], JSI::Typelike.as_json(Set.new(['a']))) | ||
|
||
# responds to #to_hash / #to_ary but naught else | ||
assert_equal({'a' => 'b'}, JSI::Typelike.as_json(SortOfHash.new({'a' => 'b'}))) | ||
assert_equal(['a'], JSI::Typelike.as_json(SortOfArray.new(['a']))) | ||
|
||
# symbol keys to string | ||
assert_equal({'a' => 'b'}, JSI::Typelike.as_json({a: 'b'})) | ||
# non string/symbol key | ||
err = assert_raises(TypeError) { JSI::Typelike.as_json({nil => 0}) } | ||
assert_equal('json object (hash) cannot be keyed with: nil', err.message) | ||
|
||
# schema | ||
schema = JSI::Schema.from_object({'type' => 'array'}) | ||
assert_equal({'type' => 'array'}, JSI::Typelike.as_json(schema)) | ||
|
||
# JSI | ||
assert_equal(['a'], JSI::Typelike.as_json(JSI.class_for_schema(schema).new(['a']))) | ||
|
||
# JSON::Node | ||
assert_equal(['a'], JSI::Typelike.as_json(JSI::JSON::Node.new_doc(['a']))) | ||
|
||
# #as_json | ||
assert_equal(['a'], JSI::Typelike.as_json(JSONifiable.new(['a']))) | ||
|
||
# not jsonifiable | ||
object = Object.new | ||
err = assert_raises(TypeError) { JSI::Typelike.as_json(object) } | ||
assert_equal("cannot express object as json: #{object.pretty_inspect.chomp}", err.message) | ||
end | ||
end | ||
end |