diff --git a/test/as_test.rb b/test/as_test.rb index 6f4e2cad..bc95badb 100644 --- a/test/as_test.rb +++ b/test/as_test.rb @@ -1,42 +1,42 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class AsTest < MiniTest::Spec for_formats( - hash: [Representable::Hash, { 'title' => 'Wie Es Geht' }, { 'title' => 'Revolution' }] + hash: [Representable::Hash, {"title" => "Wie Es Geht"}, {"title" => "Revolution"}] # :xml => [Representable::XML, "\n \n Alive\n \n", "You've Taken Everything/open_struct>"], # :yaml => [Representable::YAML, "---\nsong:\n name: Alive\n", "---\nsong:\n name: You've Taken Everything\n"], ) do |format, mod, input, output| - let(:song) { representer.prepare(Song.new('Revolution')) } + let(:song) { representer.prepare(Song.new("Revolution")) } let(:format) { format } - describe 'as: with :symbol' do + describe "as: with :symbol" do representer!(module: mod) do property :name, as: :title end it { assert_equal_document render(song), output } - it { _(parse(song, input).name).must_equal 'Wie Es Geht' } + it { _(parse(song, input).name).must_equal "Wie Es Geht" } end - describe 'as: with lambda' do + describe "as: with lambda" do representer!(module: mod) do property :name, as: ->(*) { self.class.to_s } end - it { assert_equal_document(render(song), { 'Song' => 'Revolution' }) } - it { _(parse(song, { 'Song' => 'Wie Es Geht' }).name).must_equal 'Wie Es Geht' } + it { assert_equal_document(render(song), {"Song" => "Revolution"}) } + it { _(parse(song, {"Song" => "Wie Es Geht"}).name).must_equal "Wie Es Geht" } end - describe 'lambda arguments' do + describe "lambda arguments" do representer! do property :name, as: ->(options) { options[:user_options].inspect } end - it { assert_equal_document(render(song, user_options: { volume: 1 }), { '{:volume=>1}' => 'Revolution' }) } + it { assert_equal_document(render(song, user_options: {volume: 1}), {"{:volume=>1}" => "Revolution"}) } it { - _(parse(song, { '{:volume=>1}' => 'Wie Es Geht' }, user_options: { volume: 1 }).name).must_equal 'Wie Es Geht' + _(parse(song, {"{:volume=>1}" => "Wie Es Geht"}, user_options: {volume: 1}).name).must_equal "Wie Es Geht" } end end @@ -62,6 +62,6 @@ class AsXmlTest < MiniTest::Spec Offspring -", representer.new(Album.new(Band.new('Offspring'))).to_xml +", representer.new(Album.new(Band.new("Offspring"))).to_xml end end diff --git a/test/benchmarking.rb b/test/benchmarking.rb index db977ba7..e4464963 100644 --- a/test/benchmarking.rb +++ b/test/benchmarking.rb @@ -1,9 +1,9 @@ # frozen_string_literal: true -require 'test_helper' -require 'benchmark' +require "test_helper" +require "benchmark" -SONG_PROPERTIES = 1000.times.collect do |i| +SONG_PROPERTIES = Array.new(1000) do |i| "property_#{i}" end @@ -27,22 +27,22 @@ module AlbumRepresenter end def random_song - attrs = Hash[SONG_PROPERTIES.collect { |n| [n, n] }] + attrs = SONG_PROPERTIES.to_h { |n| [n, n] } OpenStruct.new(attrs) end times = [] 3.times.each do - album = OpenStruct.new(songs: 100.times.collect { random_song }) + album = OpenStruct.new(songs: Array.new(100) { random_song }) times << Benchmark.measure do - puts '================ next!' + puts "================ next!" album.extend(AlbumRepresenter).to_json end end -puts times.join('') +puts times.join # 100 songs, 100 attrs # 0.050000 0.000000 0.050000 ( 0.093157) diff --git a/test/binding_test.rb b/test/binding_test.rb index aa6fd3a9..538a0d28 100644 --- a/test/binding_test.rb +++ b/test/binding_test.rb @@ -1,16 +1,16 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class BindingTest < MiniTest::Spec Binding = Representable::Binding let(:render_nil_definition) { Representable::Definition.new(:song, render_nil: true) } - describe '#skipable_empty_value?' do + describe "#skipable_empty_value?" do let(:binding) { Binding.new(render_nil_definition) } # don't skip when present. - it { _(binding.skipable_empty_value?('Disconnect, Disconnect')).must_equal false } + it { _(binding.skipable_empty_value?("Disconnect, Disconnect")).must_equal false } # don't skip when it's nil and render_nil: true it { _(binding.skipable_empty_value?(nil)).must_equal false } @@ -19,21 +19,21 @@ class BindingTest < MiniTest::Spec it { _(Binding.new(Representable::Definition.new(:song)).skipable_empty_value?(nil)).must_equal true } # don't skip when nil and :render_nil undefined. - it { _(Binding.new(Representable::Definition.new(:song)).skipable_empty_value?('Fatal Flu')).must_equal false } + it { _(Binding.new(Representable::Definition.new(:song)).skipable_empty_value?("Fatal Flu")).must_equal false } end - describe '#default_for' do - let(:definition) { Representable::Definition.new(:song, default: 'Insider') } + describe "#default_for" do + let(:definition) { Representable::Definition.new(:song, default: "Insider") } let(:binding) { Binding.new(definition) } # return value when value present. - it { _(binding.default_for('Black And Blue')).must_equal 'Black And Blue' } + it { _(binding.default_for("Black And Blue")).must_equal "Black And Blue" } # return false when value false. it { _(binding.default_for(false)).must_equal false } # return default when value nil. - it { _(binding.default_for(nil)).must_equal 'Insider' } + it { _(binding.default_for(nil)).must_equal "Insider" } # return nil when value nil and render_nil: true. it { _(Binding.new(render_nil_definition).default_for(nil)).must_be_nil } @@ -44,7 +44,7 @@ class BindingTest < MiniTest::Spec Binding.new( Representable::Definition.new( :song, render_nil: true, - default: 'The Quest' + default: "The Quest" ) ).default_for(nil) ).must_be_nil diff --git a/test/cached_test.rb b/test/cached_test.rb index b27042ac..46263b33 100644 --- a/test/cached_test.rb +++ b/test/cached_test.rb @@ -1,33 +1,27 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class Profiler def self.profile(&block) case RUBY_ENGINE - when 'ruby' - require 'ruby-prof' - - output = StringIO.new - profile_result = RubyProf.profile(&block) - printer = RubyProf::FlatPrinter.new(profile_result) - printer.print(output) - output.string - when 'jruby' - require 'jruby/profiler' - - output_stream = java.io.ByteArrayOutputStream.new - print_stream = java.io.PrintStream.new(output_stream) - profile_result = JRuby::Profiler.profile(&block) - printer = JRuby::Profiler::FlatProfilePrinter.new(profile_result) - printer.printProfile(print_stream) - output_stream.toString - when 'truffleruby' - require 'truffleruby-tool' - - output = StringIO.new - TruffleRubyTool.profile(&block) - output.string + when "ruby" + require "ruby-prof" + + output = StringIO.new + profile_result = RubyProf.profile(&block) + printer = RubyProf::FlatPrinter.new(profile_result) + printer.print(output) + output.string + when "jruby" + require "jruby/profiler" + + output_stream = java.io.ByteArrayOutputStream.new + print_stream = java.io.PrintStream.new(output_stream) + profile_result = JRuby::Profiler.profile(&block) + printer = JRuby::Profiler::FlatProfilePrinter.new(profile_result) + printer.printProfile(print_stream) + output_stream.toString end end end @@ -59,29 +53,29 @@ class AlbumRepresenter < Representable::Decorator collection :songs, decorator: SongRepresenter, class: Model::Song end - describe 'serialization' do + describe "serialization" do let(:album_hash) do { - 'name' => 'Louder And Even More Dangerous', - 'songs' => [{ 'title' => 'Southbound:{:volume=>10}' }, { 'title' => 'Jailbreak:{:volume=>10}' }] + "name" => "Louder And Even More Dangerous", + "songs" => [{"title" => "Southbound:{:volume=>10}"}, {"title" => "Jailbreak:{:volume=>10}"}] } end - let(:song) { Model::Song.new('Jailbreak') } - let(:song2) { Model::Song.new('Southbound') } - let(:album) { Model::Album.new('Live And Dangerous', [song, song2, Model::Song.new('Emerald')]) } + let(:song) { Model::Song.new("Jailbreak") } + let(:song2) { Model::Song.new("Southbound") } + let(:album) { Model::Album.new("Live And Dangerous", [song, song2, Model::Song.new("Emerald")]) } let(:representer) { AlbumRepresenter.new(album) } it do # album2 = Model::Album.new("Louder And Even More Dangerous", [song2, song]) # makes sure options are passed correctly. - _(representer.to_hash(user_options: { volume: 9 })).must_equal( + _(representer.to_hash(user_options: {volume: 9})).must_equal( { - 'name' => 'Live And Dangerous', - 'songs' => [ - { 'title' => 'Jailbreak:{:volume=>9}' }, { 'title' => 'Southbound:{:volume=>9}' }, - { 'title' => 'Emerald:{:volume=>9}' } + "name" => "Live And Dangerous", + "songs" => [ + {"title" => "Jailbreak:{:volume=>9}"}, {"title" => "Southbound:{:volume=>9}"}, + {"title" => "Emerald:{:volume=>9}"} ] } ) # called in Deserializer/Serializer @@ -95,6 +89,7 @@ class AlbumRepresenter < Representable::Decorator # profiling it do + skip("TruffleRuby profiler is not implemented yet") if RUBY_ENGINE == "truffleruby" representer.to_hash data = Profiler.profile { representer.to_hash } @@ -109,24 +104,24 @@ class AlbumRepresenter < Representable::Decorator # 3 nested decorator is instantiated for 3 Songs, though. _(data).must_match(/3\s*(?[\#.]prepare/m) # no Binding is instantiated at runtime. - _(data).wont_match 'Representable::Binding#initialize' + _(data).wont_match "Representable::Binding#initialize" # 2 mappers for Album, Song # data.must_match "2 Representable::Mapper::Methods#initialize" # title, songs, 3x title, composer _(data).must_match(/8\s*Representable::Binding[#.]render_pipeline/m) - _(data).wont_match 'render_functions' - _(data).wont_match 'Representable::Binding::Factories#render_functions' + _(data).wont_match "render_functions" + _(data).wont_match "Representable::Binding::Factories#render_functions" end end - describe 'deserialization' do + describe "deserialization" do let(:album_hash) do { - 'name' => 'Louder And Even More Dangerous', - 'songs' => [ - { 'title' => 'Southbound', 'composer' => { 'name' => 'Lynott' } }, - { 'title' => 'Jailbreak', 'composer' => { 'name' => 'Phil Lynott' } }, - { 'title' => 'Emerald' } + "name" => "Louder And Even More Dangerous", + "songs" => [ + {"title" => "Southbound", "composer" => {"name" => "Lynott"}}, + {"title" => "Jailbreak", "composer" => {"name" => "Phil Lynott"}}, + {"title" => "Emerald"} ] } end @@ -137,18 +132,19 @@ class AlbumRepresenter < Representable::Decorator AlbumRepresenter.new(album).from_hash(album_hash) _(album.songs.size).must_equal 3 - _(album.name).must_equal 'Louder And Even More Dangerous' - _(album.songs[0].title).must_equal 'Southbound' - _(album.songs[0].composer.name).must_equal 'Lynott' - _(album.songs[1].title).must_equal 'Jailbreak' - _(album.songs[1].composer.name).must_equal 'Phil Lynott' - _(album.songs[2].title).must_equal 'Emerald' + _(album.name).must_equal "Louder And Even More Dangerous" + _(album.songs[0].title).must_equal "Southbound" + _(album.songs[0].composer.name).must_equal "Lynott" + _(album.songs[1].title).must_equal "Jailbreak" + _(album.songs[1].composer.name).must_equal "Phil Lynott" + _(album.songs[2].title).must_equal "Emerald" _(album.songs[2].composer).must_be_nil # TODO: test options. end - it 'xxx' do + it "xxx" do + skip("TruffleRuby profiler is not implemented yet") if RUBY_ENGINE == "truffleruby" representer = AlbumRepresenter.new(Model::Album.new) representer.from_hash(album_hash) @@ -159,9 +155,9 @@ class AlbumRepresenter < Representable::Decorator # MRI and JRuby has different output formats. See note above. _(data).must_match(/5\s*(?[#.]prepare/) # a total of 5 properties in the object graph. - _(data).wont_match 'Representable::Binding#initialize' + _(data).wont_match "Representable::Binding#initialize" - _(data).wont_match 'parse_functions' # no pipeline creation. + _(data).wont_match "parse_functions" # no pipeline creation. _(data).must_match(/10\s*Representable::Binding[#.]parse_pipeline/) # three mappers for Album, Song, composer # data.must_match "3 Representable::Mapper::Methods#initialize" diff --git a/test/class_test.rb b/test/class_test.rb index 1749aca5..2e27eaec 100644 --- a/test/class_test.rb +++ b/test/class_test.rb @@ -1,56 +1,56 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class ClassTest < BaseTest class RepresentingSong attr_reader :name def from_hash(doc, *) - @name = doc['__name__'] + @name = doc["__name__"] self # DISCUSS: do we wanna be able to return whatever we want here? this is a trick to replace the actual object end end - describe 'class: ClassName, only' do + describe "class: ClassName, only" do representer! do property :song, class: RepresentingSong # supposed this class exposes #from_hash itself. end it "creates fresh instance and doesn't extend" do - song = representer.prepare(OpenStruct.new).from_hash({ 'song' => { '__name__' => 'Captured' } }).song + song = representer.prepare(OpenStruct.new).from_hash({"song" => {"__name__" => "Captured"}}).song _(song).must_be_instance_of RepresentingSong - _(song.name).must_equal 'Captured' + _(song.name).must_equal "Captured" end end - describe 'class: lambda, only' do + describe "class: lambda, only" do representer! do property :song, class: ->(*) { RepresentingSong } end it "creates fresh instance and doesn't extend" do - song = representer.prepare(OpenStruct.new).from_hash({ 'song' => { '__name__' => 'Captured' } }).song + song = representer.prepare(OpenStruct.new).from_hash({"song" => {"__name__" => "Captured"}}).song _(song).must_be_instance_of RepresentingSong - _(song.name).must_equal 'Captured' + _(song.name).must_equal "Captured" end end # this throws a DeserializationError now. - describe 'lambda { nil }' do + describe "lambda { nil }" do representer! do property :title, class: nil end it do assert_raises Representable::DeserializeError do - OpenStruct.new.extend(representer).from_hash({ 'title' => {} }) + OpenStruct.new.extend(representer).from_hash({"title" => {}}) end end end - describe 'lambda receiving fragment and args' do + describe "lambda receiving fragment and args" do let(:klass) do Class.new do class << self @@ -65,7 +65,7 @@ def from_hash(*) representer!(inject: :klass) do _klass = klass - property :song, class: lambda { |options| + property :song, class: ->(options) { _klass.args = ([options[:fragment], options[:user_options]]) _klass } @@ -74,15 +74,15 @@ def from_hash(*) it { _( representer.prepare(OpenStruct.new).from_hash( - { 'song' => { 'name' => 'Captured' } }, - user_options: { volume: true } + {"song" => {"name" => "Captured"}}, + user_options: {volume: true} ).song.class.args ) - .must_equal([{ 'name' => 'Captured' }, { volume: true }]) + .must_equal([{"name" => "Captured"}, {volume: true}]) } end - describe 'collection: lambda receiving fragment and args' do + describe "collection: lambda receiving fragment and args" do let(:klass) do Class.new do class << self @@ -97,7 +97,7 @@ def from_hash(*) representer!(inject: :klass) do _klass = klass - collection :songs, class: lambda { |options| + collection :songs, class: ->(options) { _klass.args = ([options[:fragment], options[:index], options[:user_options]]) _klass } @@ -106,15 +106,15 @@ def from_hash(*) it { _( representer.prepare(OpenStruct.new).from_hash( - { 'songs' => [{ 'name' => 'Captured' }] }, - user_options: { volume: true } + {"songs" => [{"name" => "Captured"}]}, + user_options: {volume: true} ).songs.first.class.args ) - .must_equal([{ 'name' => 'Captured' }, 0, { volume: true }]) + .must_equal([{"name" => "Captured"}, 0, {volume: true}]) } end - describe 'class: implementing #from_hash' do + describe "class: implementing #from_hash" do let(:parser) do Class.new do def from_hash(*) @@ -127,8 +127,8 @@ def from_hash(*) property :song, class: parser # supposed this class exposes #from_hash itself. end - it 'allows returning arbitrary objects in #from_hash' do - _(representer.prepare(OpenStruct.new).from_hash({ 'song' => 1 }).song).must_equal [1, 2, 3, 4] + it "allows returning arbitrary objects in #from_hash" do + _(representer.prepare(OpenStruct.new).from_hash({"song" => 1}).song).must_equal [1, 2, 3, 4] end end end diff --git a/test/coercion_test.rb b/test/coercion_test.rb index d0dbf8d6..4b08dbfd 100644 --- a/test/coercion_test.rb +++ b/test/coercion_test.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'test_helper' -require 'representable/coercion' +require "test_helper" +require "representable/coercion" class CoercionTest < MiniTest::Spec representer! do @@ -21,8 +21,8 @@ class CoercionTest < MiniTest::Spec let(:album) do OpenStruct.new( - title: 'Dire Straits', length: 41.34, - band: OpenStruct.new(founded: '1977'), + title: "Dire Straits", length: 41.34, + band: OpenStruct.new(founded: "1977"), songs: [OpenStruct.new(ok: 1), OpenStruct.new(ok: 0)] ) end @@ -30,10 +30,10 @@ class CoercionTest < MiniTest::Spec it do _(album.extend(representer).to_hash).must_equal( { - 'title' => 'Dire Straits', - 'length' => 41.34, - 'band' => { 'founded' => 1977 }, - 'songs' => [{ 'ok' => true }, { 'ok' => false }] + "title" => "Dire Straits", + "length" => 41.34, + "band" => {"founded" => 1977}, + "songs" => [{"ok" => true}, {"ok" => false}] } ) end @@ -43,10 +43,10 @@ class CoercionTest < MiniTest::Spec album.extend(representer) album.from_hash( { - 'title' => 'Dire Straits', - 'length' => '41.34', - 'band' => { 'founded' => '1977' }, - 'songs' => [{ 'ok' => 1 }, { 'ok' => 0 }] + "title" => "Dire Straits", + "length" => "41.34", + "band" => {"founded" => "1977"}, + "songs" => [{"ok" => 1}, {"ok" => 0}] } ) @@ -56,7 +56,7 @@ class CoercionTest < MiniTest::Spec _(album.songs[0].ok).must_equal true } - describe 'with user :parse_filter and :render_filter' do + describe "with user :parse_filter and :render_filter" do representer! do include Representable::Coercion @@ -66,8 +66,8 @@ class CoercionTest < MiniTest::Spec end # user's :parse_filter(s) are run before coercion. - it { _(OpenStruct.new.extend(representer).from_hash('length' => '1').length).must_equal 1.1 } + it { _(OpenStruct.new.extend(representer).from_hash("length" => "1").length).must_equal 1.1 } # user's :render_filter(s) are run before coercion. - it { _(OpenStruct.new(length: 1).extend(representer).to_hash).must_equal({ 'length' => 1.1 }) } + it { _(OpenStruct.new(length: 1).extend(representer).to_hash).must_equal({"length" => 1.1}) } end end diff --git a/test/config/inherit_test.rb b/test/config/inherit_test.rb index 3e4c1760..3c69e9ae 100644 --- a/test/config/inherit_test.rb +++ b/test/config/inherit_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" # tests defining representers in modules, decorators and classes and the inheritance when combined. @@ -40,7 +40,8 @@ class InheritingDecorator < Decorator end it { _(InheritingDecorator.definitions.keys).must_equal %w[title artist location] } - it { assert_cloned(InheritingDecorator, Decorator, 'title') } + + it { assert_cloned(InheritingDecorator, Decorator, "title") } it do _(InheritingDecorator.representable_attrs.get(:artist).representer_module.object_id).wont_equal Decorator.representable_attrs.get(:artist).representer_module.object_id end @@ -53,6 +54,7 @@ class InheritingAndIncludingDecorator < Decorator end it { _(InheritingAndIncludingDecorator.definitions.keys).must_equal %w[title artist genre location] } + it { assert_cloned(InheritingAndIncludingDecorator, GenreModule, :genre) } # in module --------------------------------------------------- @@ -61,7 +63,7 @@ module Module property :title end - it { _(Module.definitions.keys).must_equal ['title'] } + it { _(Module.definitions.keys).must_equal ["title"] } # in module including module module SubModule @@ -72,6 +74,7 @@ module SubModule end it { _(SubModule.definitions.keys).must_equal %w[title location] } + it { assert_cloned(SubModule, Module, :title) } # including preserves order @@ -92,6 +95,7 @@ class Class end it { _(Class.definitions.keys).must_equal %w[genre title location] } + it { assert_cloned(Class, IncludingModule, :title) } it { assert_cloned(Class, IncludingModule, :location) } it { assert_cloned(Class, IncludingModule, :genre) } @@ -111,7 +115,7 @@ class RepresenterClass property :title end - it { _(RepresenterClass.definitions.keys).must_equal ['title'] } + it { _(RepresenterClass.definitions.keys).must_equal ["title"] } # in inheriting class class InheritingClass < RepresenterClass @@ -120,6 +124,7 @@ class InheritingClass < RepresenterClass end it { _(InheritingClass.definitions.keys).must_equal %w[title location] } + it { assert_cloned(InheritingClass, RepresenterClass, :title) } # in inheriting class and including diff --git a/test/config_test.rb b/test/config_test.rb index 43377cab..e160b661 100644 --- a/test/config_test.rb +++ b/test/config_test.rb @@ -1,15 +1,15 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class ConfigTest < MiniTest::Spec subject { Representable::Config.new(Representable::Definition) } PunkRock = Class.new Definition = Representable::Definition - describe 'wrapping' do - it 'returns false per default' do - assert_nil subject.wrap_for('Punk', nil) + describe "wrapping" do + it "returns false per default" do + assert_nil subject.wrap_for("Punk", nil) end # it "infers a printable class name if set to true" do @@ -23,7 +23,7 @@ class ConfigTest < MiniTest::Spec # end end - describe '#[]' do + describe "#[]" do # does return nil for non-existent it { _(subject[:hello]).must_be_nil } end @@ -40,35 +40,35 @@ class ConfigTest < MiniTest::Spec # []=(... inherit: true) # forwarded to Config#definitions # that goes to ConfigDefinitionsTest - describe '#add' do - describe 'returns' do + describe "#add" do + describe "returns" do it do # #add returns Definition.` - subject = Representable::Config.new(Representable::Definition).add(:title, { me: true }) + subject = Representable::Config.new(Representable::Definition).add(:title, {me: true}) _(subject).must_be_kind_of Representable::Definition _(subject[:me]).must_equal true end end - before { subject.add(:title, { me: true }) } + before { subject.add(:title, {me: true}) } # must be kind of Definition it { _(subject.size).must_equal 1 } - it { _(subject.get(:title).name).must_equal 'title' } + it { _(subject.get(:title).name).must_equal "title" } it { _(subject.get(:title)[:me]).must_equal true } # this is actually tested in context in inherit_test. - it 'overrides former definition' do - subject.add(:title, { peer: Module }) + it "overrides former definition" do + subject.add(:title, {peer: Module}) _(subject.get(:title)[:me]).must_be_nil _(subject.get(:title)[:peer]).must_equal Module end - describe 'inherit: true' do + describe "inherit: true" do before do - subject.add(:title, { me: true }) - subject.add(:title, { peer: Module, inherit: true }) + subject.add(:title, {me: true}) + subject.add(:title, {peer: Module, inherit: true}) end it { _(subject.get(:title)[:me]).must_equal true } @@ -76,11 +76,11 @@ class ConfigTest < MiniTest::Spec end end - describe '#remove' do + describe "#remove" do subject { Representable::Config.new(Representable::Definition) } it do - subject.add(:title, { me: true }) + subject.add(:title, {me: true}) subject.add(:genre, {}) _(subject.get(:genre)).must_be_kind_of Representable::Definition @@ -89,10 +89,10 @@ class ConfigTest < MiniTest::Spec end end - describe '#each' do - before { subject.add(:title, { me: true }) } + describe "#each" do + before { subject.add(:title, {me: true}) } - it 'what' do + it "what" do definitions = [] subject.each { |dfn| definitions << dfn } _(definitions.size).must_equal 1 @@ -100,7 +100,7 @@ class ConfigTest < MiniTest::Spec end end - describe '#options' do + describe "#options" do it { _(subject.options).must_equal({}) } it do subject.options[:namespacing] = true @@ -108,7 +108,7 @@ class ConfigTest < MiniTest::Spec end end - describe '#get' do + describe "#get" do subject { Representable::Config.new(Representable::Definition) } it do diff --git a/test/decorator_scope_test.rb b/test/decorator_scope_test.rb index 8977611e..7c66a08e 100644 --- a/test/decorator_scope_test.rb +++ b/test/decorator_scope_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" # TODO: remove in 2.0. class DecoratorScopeTest < MiniTest::Spec @@ -12,21 +12,21 @@ class DecoratorScopeTest < MiniTest::Spec Module.new do include Representable::Hash property :title, decorator_scope: true - def title = 'Crystal Planet' + def title; "Crystal Planet"; end end end - it 'executes lambdas in represented context' do + it "executes lambdas in represented context" do _( - Class.new do + Class.new { def title_from_representer - 'Sounds Of Silence' + "Sounds Of Silence" end - end.new.extend(representer).to_hash - ).must_equal({ 'title' => 'Sounds Of Silence' }) + }.new.extend(representer).to_hash + ).must_equal({"title" => "Sounds Of Silence"}) end - it 'executes method in represented context' do - _(Object.new.extend(representer_with_method).to_hash).must_equal({ 'title' => 'Crystal Planet' }) + it "executes method in represented context" do + _(Object.new.extend(representer_with_method).to_hash).must_equal({"title" => "Crystal Planet"}) end end diff --git a/test/decorator_test.rb b/test/decorator_test.rb index dc65c91f..913b1f80 100644 --- a/test/decorator_test.rb +++ b/test/decorator_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class DecoratorTest < MiniTest::Spec class SongRepresentation < Representable::Decorator @@ -24,18 +24,22 @@ class RatingRepresentation < Representable::Decorator let(:song) { Song.new("Mama, I'm Coming Home") } let(:album) { Album.new([song]) } - let(:rating) { OpenStruct.new(system: 'MPAA', value: 'R') } + let(:rating) { OpenStruct.new(system: "MPAA", value: "R") } - describe 'inheritance' do + describe "inheritance" do let(:inherited_decorator) do - Class.new(AlbumRepresentation) do + Class.new(AlbumRepresentation) { property :best_song - end.new(Album.new([song], 'Stand Up')) + }.new(Album.new([song], "Stand Up")) end it { - _(inherited_decorator.to_hash).must_equal({ 'songs' => [{ 'name' => "Mama, I'm Coming Home" }], - 'best_song' => 'Stand Up' }) + _(inherited_decorator.to_hash).must_equal( + { + "songs" => [{"name" => "Mama, I'm Coming Home"}], + "best_song" => "Stand Up" + } + ) } end @@ -43,45 +47,45 @@ class RatingRepresentation < Representable::Decorator let(:rating_decorator) { RatingRepresentation.new(rating) } - it 'renders' do - _(decorator.to_hash).must_equal({ 'songs' => [{ 'name' => "Mama, I'm Coming Home" }] }) + it "renders" do + _(decorator.to_hash).must_equal({"songs" => [{"name" => "Mama, I'm Coming Home"}]}) _(album).wont_respond_to :to_hash _(song).wont_respond_to :to_hash # DISCUSS: weak test, how to assert blank slate? # no @representable_attrs in decorated objects _(song).wont_be(:instance_variable_defined?, :@representable_attrs) - _(rating_decorator.to_hash).must_equal({ 'system' => 'MPAA', 'value' => 'R' }) + _(rating_decorator.to_hash).must_equal({"system" => "MPAA", "value" => "R"}) end - describe '#from_hash' do - it 'returns represented' do - _(decorator.from_hash({ 'songs' => [{ 'name' => "Mama, I'm Coming Home" }] })).must_equal album + describe "#from_hash" do + it "returns represented" do + _(decorator.from_hash({"songs" => [{"name" => "Mama, I'm Coming Home"}]})).must_equal album end - it 'parses' do - decorator.from_hash({ 'songs' => [{ 'name' => 'Atomic Garden' }] }) + it "parses" do + decorator.from_hash({"songs" => [{"name" => "Atomic Garden"}]}) _(album.songs.first).must_be_kind_of Song - _(album.songs).must_equal [Song.new('Atomic Garden')] + _(album.songs).must_equal [Song.new("Atomic Garden")] _(album).wont_respond_to :to_hash _(song).wont_respond_to :to_hash # DISCUSS: weak test, how to assert blank slate? end end - describe '#decorated' do - it 'is aliased to #represented' do + describe "#decorated" do + it "is aliased to #represented" do _(AlbumRepresentation.prepare(album).decorated).must_equal album end end - describe 'inline decorators' do + describe "inline decorators" do representer!(decorator: true) do collection :songs, class: Song do property :name end end - it 'does not pollute represented' do - representer.new(album).from_hash({ 'songs' => [{ 'name' => 'Atomic Garden' }] }) + it "does not pollute represented" do + representer.new(album).from_hash({"songs" => [{"name" => "Atomic Garden"}]}) # no @representable_attrs in decorated objects _(song).wont_be(:instance_variable_defined?, :@representable_attrs) @@ -90,7 +94,7 @@ class RatingRepresentation < Representable::Decorator end end -require 'uber/inheritable_attr' +require "uber/inheritable_attr" class InheritanceWithDecoratorTest < MiniTest::Spec class Twin extend Uber::InheritableAttr diff --git a/test/default_test.rb b/test/default_test.rb index dcc688b7..e3ca6d28 100644 --- a/test/default_test.rb +++ b/test/default_test.rb @@ -1,36 +1,36 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class DefaultTest < MiniTest::Spec Song = Struct.new(:id, :title) representer! do property :id - property :title, default: 'Huber Breeze' #->(options) { options[:default] } + property :title, default: "Huber Breeze" #->(options) { options[:default] } end - describe '#from_hash' do + describe "#from_hash" do let(:song) { Song.new.extend(representer) } - it { _(song.from_hash({})).must_equal Song.new(nil, 'Huber Breeze') } + it { _(song.from_hash({})).must_equal Song.new(nil, "Huber Breeze") } # default doesn't apply when empty string. - it { _(song.from_hash({ 'title' => '' })).must_equal Song.new(nil, '') } - it { _(song.from_hash({ 'title' => nil })).must_equal Song.new(nil, nil) } - it { _(song.from_hash({ 'title' => 'Blindfold' })).must_equal Song.new(nil, 'Blindfold') } + it { _(song.from_hash({"title" => ""})).must_equal Song.new(nil, "") } + it { _(song.from_hash({"title" => nil})).must_equal Song.new(nil, nil) } + it { _(song.from_hash({"title" => "Blindfold"})).must_equal Song.new(nil, "Blindfold") } end - describe '#to_json' do - it 'uses :default when not available from object' do - _(Song.new.extend(representer).to_hash).must_equal({ 'title' => 'Huber Breeze' }) + describe "#to_json" do + it "uses :default when not available from object" do + _(Song.new.extend(representer).to_hash).must_equal({"title" => "Huber Breeze"}) end - it 'uses value from represented object when present' do - _(Song.new(nil, 'After The War').extend(representer).to_hash).must_equal({ 'title' => 'After The War' }) + it "uses value from represented object when present" do + _(Song.new(nil, "After The War").extend(representer).to_hash).must_equal({"title" => "After The War"}) end - it 'uses value from represented object when emtpy string' do - _(Song.new(nil, '').extend(representer).to_hash).must_equal({ 'title' => '' }) + it "uses value from represented object when emtpy string" do + _(Song.new(nil, "").extend(representer).to_hash).must_equal({"title" => ""}) end end end diff --git a/test/defaults_options_test.rb b/test/defaults_options_test.rb index ea08444d..3298e3d2 100644 --- a/test/defaults_options_test.rb +++ b/test/defaults_options_test.rb @@ -1,16 +1,16 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class DefaultsOptionsTest < BaseTest let(:format) { :hash } - let(:song) { Struct.new(:title, :author_name, :song_volume, :description).new('Revolution', 'Some author', 20, nil) } + let(:song) { Struct.new(:title, :author_name, :song_volume, :description).new("Revolution", "Some author", 20, nil) } let(:prepared) { representer.prepare song } - describe 'hash options combined with dynamic options' do + describe "hash options combined with dynamic options" do representer! do defaults render_nil: true do |name| - { as: name.to_s.upcase } + {as: name.to_s.upcase} end property :title @@ -22,18 +22,18 @@ class DefaultsOptionsTest < BaseTest it { assert_equal_document( { - 'TITLE' => 'Revolution', 'AUTHOR_NAME' => 'Some author', 'DESCRIPTION' => nil, - 'SONG_VOLUME' => 20 + "TITLE" => "Revolution", "AUTHOR_NAME" => "Some author", "DESCRIPTION" => nil, + "SONG_VOLUME" => 20 }, render(prepared) ) } end - describe 'with only dynamic property options' do + describe "with only dynamic property options" do representer! do defaults do |name| - { as: name.to_s.upcase } + {as: name.to_s.upcase} end property :title @@ -44,13 +44,13 @@ class DefaultsOptionsTest < BaseTest it { assert_equal_document( - { 'TITLE' => 'Revolution', 'AUTHOR_NAME' => 'Some author', 'SONG_VOLUME' => 20 }, + {"TITLE" => "Revolution", "AUTHOR_NAME" => "Some author", "SONG_VOLUME" => 20}, render(prepared) ) } end - describe 'with only hashes' do + describe "with only hashes" do representer! do defaults render_nil: true @@ -63,15 +63,15 @@ class DefaultsOptionsTest < BaseTest it { assert_equal_document( { - 'title' => 'Revolution', 'author_name' => 'Some author', 'description' => nil, - 'song_volume' => 20 + "title" => "Revolution", "author_name" => "Some author", "description" => nil, + "song_volume" => 20 }, render(prepared) ) } end - describe 'direct defaults hash' do + describe "direct defaults hash" do representer! do defaults render_nil: true @@ -84,18 +84,18 @@ class DefaultsOptionsTest < BaseTest it { assert_equal_document( { - 'title' => 'Revolution', 'author_name' => 'Some author', 'description' => nil, - 'song_volume' => 20 + "title" => "Revolution", "author_name" => "Some author", "description" => nil, + "song_volume" => 20 }, render(prepared) ) } end - describe 'direct defaults hash with dynamic options' do + describe "direct defaults hash with dynamic options" do representer! do defaults render_nil: true do |name| - { as: name.to_s.upcase } + {as: name.to_s.upcase} end property :title @@ -107,18 +107,18 @@ class DefaultsOptionsTest < BaseTest it { assert_equal_document( { - 'TITLE' => 'Revolution', 'AUTHOR_NAME' => 'Some author', 'DESCRIPTION' => nil, - 'SONG_VOLUME' => 20 + "TITLE" => "Revolution", "AUTHOR_NAME" => "Some author", "DESCRIPTION" => nil, + "SONG_VOLUME" => 20 }, render(prepared) ) } end - describe 'prioritizes specific options' do + describe "prioritizes specific options" do representer! do defaults render_nil: true do |name| - { as: name.to_s.upcase } + {as: name.to_s.upcase} end property :title @@ -129,7 +129,7 @@ class DefaultsOptionsTest < BaseTest it { assert_equal_document( - { 'TITLE' => 'Revolution', 'AUTHOR_NAME' => 'Some author', 'volume' => 20 }, + {"TITLE" => "Revolution", "AUTHOR_NAME" => "Some author", "volume" => 20}, render(prepared) ) } diff --git a/test/definition_test.rb b/test/definition_test.rb index e9393100..8e30e3f2 100644 --- a/test/definition_test.rb +++ b/test/definition_test.rb @@ -1,12 +1,12 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class DefinitionTest < MiniTest::Spec Definition = Representable::Definition # TODO: test that we DON'T clone options, that must happen in - describe '#initialize' do + describe "#initialize" do it do # new yields the defaultized options HASH. definition = Definition.new(:song, extend: Module) do |options| @@ -17,7 +17,7 @@ class DefinitionTest < MiniTest::Spec _(options[:as]).must_be_nil _(options[:extend]).must_equal Module end - _(definition.name).must_equal 'song' + _(definition.name).must_equal "song" _(definition[:awesome]).must_equal true _(definition[:parse_filter]).must_equal Representable::Pipeline[1] @@ -25,26 +25,26 @@ class DefinitionTest < MiniTest::Spec end end - describe '#[]' do + describe "#[]" do let(:definition) { Definition.new(:song) } # default is nil. it { _(definition[:bla]).must_be_nil } end # merge! - describe '#merge!' do + describe "#merge!" do let(:definition) { Definition.new(:song, whatever: true) } # merges new options. it { _(definition.merge!(something: true)[:something]).must_equal true } # doesn't override original options. - it { _(definition.merge!({ something: true })[:whatever]).must_equal true } + it { _(definition.merge!({something: true})[:whatever]).must_equal true } # override original when passed in #merge!. - it { _(definition.merge!({ whatever: false })[:whatever]).must_equal false } + it { _(definition.merge!({whatever: false})[:whatever]).must_equal false } # with block it do - definition = Definition.new(:song, extend: Module).merge!({ something: true }) do |options| + definition = Definition.new(:song, extend: Module).merge!({something: true}) do |options| options[:awesome] = true options[:render_filter] << 1 @@ -59,7 +59,7 @@ class DefinitionTest < MiniTest::Spec _(definition[:parse_filter]).must_equal Representable::Pipeline[] end - describe 'with :parse_filter' do + describe "with :parse_filter" do let(:definition) { Definition.new(:title, parse_filter: 1) } # merges :parse_filter and :render_filter. @@ -76,84 +76,86 @@ class DefinitionTest < MiniTest::Spec # does not change arguments it do - Definition.new(:title).merge!(options = { whatever: 1 }) + Definition.new(:title).merge!(options = {whatever: 1}) _(options).must_equal(whatever: 1) end end # delete! - describe '#delete!' do - let(:definition) { Definition.new(:song, serialize: 'remove me!') } + describe "#delete!" do + let(:definition) { Definition.new(:song, serialize: "remove me!") } - before { _(definition[:serialize].call(nil)).must_equal 'remove me!' } + before { _(definition[:serialize].call(nil)).must_equal "remove me!" } it { _(definition.delete!(:serialize)[:serialize]).must_be_nil } end # #inspect - describe '#inspect' do + describe "#inspect" do it { _(Definition.new(:songs).inspect).must_equal '#songs @options={:name=>"songs", :parse_filter=>[], :render_filter=>[]}>' } end - describe 'generic API' do + describe "generic API" do before do @def = Representable::Definition.new(:songs) end - it 'responds to #representer_module' do + it "responds to #representer_module" do assert_nil Representable::Definition.new(:song).representer_module assert_equal Hash, Representable::Definition.new(:song, extend: Hash).representer_module end - describe '#typed?' do - it 'is false per default' do - refute @def.typed? + describe "#typed?" do + it "is false per default" do + refute_predicate @def, :typed? end - it 'is true when :class is present' do - assert Representable::Definition.new(:songs, class: Hash).typed? + it "is true when :class is present" do + assert_predicate Representable::Definition.new(:songs, class: Hash), :typed? end - it 'is true when :extend is present, only' do - assert Representable::Definition.new(:songs, extend: Hash).typed? + it "is true when :extend is present, only" do + assert_predicate Representable::Definition.new(:songs, extend: Hash), :typed? end - it 'is true when :instance is present, only' do - assert Representable::Definition.new(:songs, instance: Object.new).typed? + it "is true when :instance is present, only" do + assert_predicate Representable::Definition.new(:songs, instance: Object.new), :typed? end end - describe '#representable?' do - it { assert Definition.new(:song, representable: true).representable? } + describe "#representable?" do + it { assert_predicate Definition.new(:song, representable: true), :representable? } it { _(Definition.new(:song, representable: true, extend: Object).representable?).must_equal true } - it { refute Definition.new(:song, representable: false, extend: Object).representable? } - it { assert Definition.new(:song, extend: Object).representable? } - it { refute Definition.new(:song).representable? } + + it { refute_predicate Definition.new(:song, representable: false, extend: Object), :representable? } + it { assert_predicate Definition.new(:song, extend: Object), :representable? } + it { refute_predicate Definition.new(:song), :representable? } end - it 'responds to #getter and returns string' do - assert_equal 'songs', @def.getter + it "responds to #getter and returns string" do + assert_equal "songs", @def.getter end - it 'responds to #name' do - assert_equal 'songs', @def.name + it "responds to #name" do + assert_equal "songs", @def.name end - it 'responds to #setter' do + it "responds to #setter" do assert_equal :"songs=", @def.setter end - describe 'nested: FIXME' do + describe "nested: FIXME" do it do dfn = Representable::Definition.new(:songs, nested: Module) - assert dfn.typed? + + assert_predicate dfn, :typed? _(dfn[:extend].call(nil)).must_equal Module end end - describe '#clone' do + describe "#clone" do subject { Representable::Definition.new(:title, volume: 9, clonable: ::Representable::Option(1)) } it { _(subject.clone).must_be_kind_of Representable::Definition } @@ -165,36 +167,36 @@ class DefinitionTest < MiniTest::Spec cloned = @def.clone cloned.merge!(volume: 8) - assert_equal @def[:volume], 9 - assert_equal cloned[:volume], 8 + assert_equal(9, @def[:volume]) + assert_equal(8, cloned[:volume]) end end end - describe '#has_default?' do - it 'returns false if no :default set' do - refute Representable::Definition.new(:song).has_default? + describe "#has_default?" do + it "returns false if no :default set" do + refute_predicate Representable::Definition.new(:song), :has_default? end - it 'returns true if :default set' do - assert Representable::Definition.new(:song, default: nil).has_default? + it "returns true if :default set" do + assert_predicate Representable::Definition.new(:song, default: nil), :has_default? end end - describe '#binding' do - it 'returns true when :binding is set' do + describe "#binding" do + it "returns true when :binding is set" do assert Representable::Definition.new(:songs, binding: Object)[:binding] end - it 'returns false when :binding is not set' do + it "returns false when :binding is not set" do refute Representable::Definition.new(:songs)[:binding] end end - describe '#create_binding' do - it 'executes the block (without special context)' do + describe "#create_binding" do + it "executes the block (without special context)" do definition = Representable::Definition.new( - :title, binding: lambda { |*args| + :title, binding: ->(*args) { @binding = Representable::Binding.new(*args) } ) @@ -202,50 +204,52 @@ class DefinitionTest < MiniTest::Spec end end - describe ':collection => true' do + describe ":collection => true" do before do @def = Representable::Definition.new(:songs, collection: true, tag: :song) end - it 'responds to #array?' do - assert @def.array? + it "responds to #array?" do + assert_predicate @def, :array? end end - describe ':default => value' do - it 'responds to #default' do + describe ":default => value" do + it "responds to #default" do @def = Representable::Definition.new(:song) + assert_nil @def[:default] end - it 'accepts a default value' do - @def = Representable::Definition.new(:song, default: 'Atheist Peace') - assert_equal 'Atheist Peace', @def[:default] + it "accepts a default value" do + @def = Representable::Definition.new(:song, default: "Atheist Peace") + + assert_equal "Atheist Peace", @def[:default] end end - describe ':hash => true' do + describe ":hash => true" do before do @def = Representable::Definition.new(:songs, hash: true) end - it 'responds to #hash?' do - assert @def.hash? - refute Representable::Definition.new(:songs).hash? + it "responds to #hash?" do + assert_predicate @def, :hash? + refute_predicate Representable::Definition.new(:songs), :hash? end end - describe ':binding => Object' do + describe ":binding => Object" do subject do Representable::Definition.new(:songs, binding: Object) end - it 'responds to #binding' do + it "responds to #binding" do assert_equal subject[:binding], Object end end - describe '#[]=' do + describe "#[]=" do it "raises exception since it's deprecated" do assert_raises NoMethodError do Definition.new(:title)[:extend] = Module.new # use merge! after initialize. diff --git a/test/examples/example.rb b/test/examples/example.rb index 59074706..f44a3f10 100644 --- a/test/examples/example.rb +++ b/test/examples/example.rb @@ -1,10 +1,10 @@ # frozen_string_literal: true -require 'bundler' +require "bundler" Bundler.setup -require 'representable/yaml' -require 'ostruct' +require "representable/yaml" +require "ostruct" def reset_representer(*module_name) module_name.each do |mod| @@ -17,7 +17,7 @@ def reset_representer(*module_name) class Song < OpenStruct end -song = Song.new(title: 'Fallout', track: 1) +song = Song.new(title: "Fallout", track: 1) module SongRepresenter include Representable::JSON @@ -54,7 +54,7 @@ module SongRepresenter collection :composers end -song = Song.new(title: 'Fallout', composers: ['Stewart Copeland', 'Sting']) +song = Song.new(title: "Fallout", composers: ["Stewart Copeland", "Sting"]) puts song.extend(SongRepresenter).to_json ######### nesting types @@ -74,7 +74,7 @@ module AlbumRepresenter property :song, extend: SongRepresenter, class: Song end -album = Album.new(name: 'The Police', song: song) +album = Album.new(name: "The Police", song: song) puts album.extend(AlbumRepresenter).to_json reset_representer(AlbumRepresenter) @@ -86,7 +86,7 @@ module AlbumRepresenter collection :songs, extend: SongRepresenter, class: Song end -album = Album.new(name: 'The Police', songs: [song, Song.new(title: 'Synchronicity')]) +album = Album.new(name: "The Police", songs: [song, Song.new(title: "Synchronicity")]) puts album.extend(AlbumRepresenter).to_json album = Album.new.extend(AlbumRepresenter).from_json( @@ -106,7 +106,7 @@ def name end end -puts Album.new(name: 'The Police') +puts Album.new(name: "The Police") .extend(AlbumRepresenter).to_json reset_representer(SongRepresenter) @@ -126,11 +126,11 @@ module CoverSongRepresenter property :covered_by end -song = Song.new(title: 'Truth Hits Everybody', covered_by: 'No Use For A Name') +song = Song.new(title: "Truth Hits Everybody", covered_by: "No Use For A Name") puts song.extend(CoverSongRepresenter).to_json ### XML -require 'representable/xml' +require "representable/xml" module SongRepresenter include Representable::XML @@ -138,7 +138,7 @@ module SongRepresenter property :track collection :composers end -song = Song.new(title: 'Fallout', composers: ['Stewart Copeland', 'Sting']) +song = Song.new(title: "Fallout", composers: ["Stewart Copeland", "Sting"]) puts song.extend(SongRepresenter).to_xml reset_representer(SongRepresenter) @@ -192,7 +192,7 @@ module SongRepresenter property :track end song = Song.new.extend(SongRepresenter) -song.from_hash({ title: 'Fallout', track: 1 }) +song.from_hash({title: "Fallout", track: 1}) puts song ######### custom methods in representer (using helpers) @@ -203,9 +203,11 @@ module SongRepresenter class CoverSong < Song end -songs = [Song.new(title: 'Weirdo', track: 5), - CoverSong.new(title: 'Truth Hits Everybody', track: 6, copyright: 'The Police')] -album = Album.new(name: 'Incognito', songs: songs) +songs = [ + Song.new(title: "Weirdo", track: 5), + CoverSong.new(title: "Truth Hits Everybody", track: 6, copyright: "The Police") +] +album = Album.new(name: "Incognito", songs: songs) reset_representer(SongRepresenter, AlbumRepresenter) @@ -240,15 +242,15 @@ module AlbumRepresenter property :name collection :songs, extend: ->(song) { song.is_a?(CoverSong) ? CoverSongRepresenter : SongRepresenter }, - class: ->(hsh) { hsh.key?('copyright') ? CoverSong : Song } #=> {"title"=>"Weirdo", "track"=>5} + class: ->(hsh) { hsh.key?("copyright") ? CoverSong : Song } #=> {"title"=>"Weirdo", "track"=>5} end album = Album.new.extend(AlbumRepresenter).from_hash( { - 'name' => 'Incognito', - 'songs' => [ - { 'title' => 'Weirdo', 'track' => 5 }, - { 'title' => 'Truth Hits Everybody', 'track' => 6, 'copyright' => 'The Police' } + "name" => "Incognito", + "songs" => [ + {"title" => "Weirdo", "track" => 5}, + {"title" => "Truth Hits Everybody", "track" => 6, "copyright" => "The Police"} ] } ) @@ -262,15 +264,15 @@ module AlbumRepresenter property :name collection :songs, extend: ->(song) { song.is_a?(CoverSong) ? CoverSongRepresenter : SongRepresenter }, - instance: ->(hsh) { hsh.key?('copyright') ? CoverSong.new : Song.new(original: true) } + instance: ->(hsh) { hsh.key?("copyright") ? CoverSong.new : Song.new(original: true) } end album = Album.new.extend(AlbumRepresenter).from_hash( { - 'name' => 'Incognito', - 'songs' => [ - { 'title' => 'Weirdo', 'track' => 5 }, - { 'title' => 'Truth Hits Everybody', 'track' => 6, 'copyright' => 'The Police' } + "name" => "Incognito", + "songs" => [ + {"title" => "Weirdo", "track" => 5}, + {"title" => "Truth Hits Everybody", "track" => 6, "copyright" => "The Police"} ] } ) @@ -287,7 +289,7 @@ module SongRepresenter hash :ratings end -puts Song.new(title: 'Bliss', ratings: { 'Rolling Stone' => 4.9, 'FryZine' => 4.5 }).extend(SongRepresenter).to_json +puts Song.new(title: "Bliss", ratings: {"Rolling Stone" => 4.9, "FryZine" => 4.5}).extend(SongRepresenter).to_json ######### JSON::Hash @@ -295,22 +297,22 @@ module FavoriteSongsRepresenter include Representable::JSON::Hash end -puts({ 'Nick' => 'Hyper Music', 'El' => 'Blown In The Wind' }.extend(FavoriteSongsRepresenter).to_json) +puts({"Nick" => "Hyper Music", "El" => "Blown In The Wind"}.extend(FavoriteSongsRepresenter).to_json) -require 'representable/json/hash' +require "representable/json/hash" module FavoriteSongsRepresenter include Representable::JSON::Hash values extend: SongRepresenter, class: Song end -puts({ 'Nick' => Song.new(title: 'Hyper Music') }.extend(FavoriteSongsRepresenter).to_json) +puts({"Nick" => Song.new(title: "Hyper Music")}.extend(FavoriteSongsRepresenter).to_json) -require 'representable/json/collection' +require "representable/json/collection" module SongsRepresenter include Representable::JSON::Collection items extend: SongRepresenter, class: Song end -puts [Song.new(title: 'Hyper Music'), Song.new(title: 'Screenager')].extend(SongsRepresenter).to_json +puts [Song.new(title: "Hyper Music"), Song.new(title: "Screenager")].extend(SongsRepresenter).to_json diff --git a/test/examples/object.rb b/test/examples/object.rb index ea444179..4c2282fc 100644 --- a/test/examples/object.rb +++ b/test/examples/object.rb @@ -1,16 +1,16 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" -require 'ostruct' +require "ostruct" source = OpenStruct.new( - name: '30 Years Live', songs: [ - OpenStruct.new(id: 1, title: 'Dear Beloved'), OpenStruct.new(id: 2, title: 'Fuck Armageddon') + name: "30 Years Live", songs: [ + OpenStruct.new(id: 1, title: "Dear Beloved"), OpenStruct.new(id: 2, title: "Fuck Armageddon") ] ) -require 'representable/object' +require "representable/object" class AlbumRepresenter < Representable::Decorator include Representable::Object diff --git a/test/exec_context_test.rb b/test/exec_context_test.rb index 91688198..6272c629 100644 --- a/test/exec_context_test.rb +++ b/test/exec_context_test.rb @@ -1,67 +1,67 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class ExecContextTest < MiniTest::Spec for_formats( - hash: [Representable::Hash, { Song => 'Rebel Fate' }, { Song => 'Timing' }] + hash: [Representable::Hash, {Song => "Rebel Fate"}, {Song => "Timing"}] # :xml => [Representable::XML, "\n \n Alive\n \n", "You've Taken Everything/open_struct>"], # :yaml => [Representable::YAML, "---\nsong:\n name: Alive\n", "---\nsong:\n name: You've Taken Everything\n"], ) do |format, mod, input, output| - let(:song) { representer.prepare(Song.new('Timing')) } + let(:song) { representer.prepare(Song.new("Timing")) } let(:format) { format } - describe 'exec_context: nil' do + describe "exec_context: nil" do representer!(module: mod) do property :name, as: ->(*) { self.class } end it { assert_equal_document(render(song), output) } - it { _(parse(song, input).name).must_equal 'Rebel Fate' } + it { _(parse(song, input).name).must_equal "Rebel Fate" } end - describe 'exec_context: :decorator' do + describe "exec_context: :decorator" do representer!(module: mod) do property :name, as: ->(*) { self.class }, exec_context: :decorator end it { assert_equal_document(render(song), output) } - it { _(parse(song, input).name).must_equal 'Rebel Fate' } + it { _(parse(song, input).name).must_equal "Rebel Fate" } end - describe 'exec_context: :binding' do + describe "exec_context: :binding" do representer!(module: mod) do property :name, as: ->(*) { self.class }, # to actually test exec_context: :binding, - setter: lambda { |options| + setter: ->(options) { options[:represented].name = options[:fragment] # to make parsing work. } end it { - assert_equal_document(render(song), { Representable::Hash::Binding => 'name' }) + assert_equal_document(render(song), {Representable::Hash::Binding => "name"}) } - it { _(parse(song, { Representable::Hash::Binding => 'Rebel Fate' }).name).must_equal 'Rebel Fate' } + it { _(parse(song, {Representable::Hash::Binding => "Rebel Fate"}).name).must_equal "Rebel Fate" } end - describe 'Decorator' do + describe "Decorator" do # DISCUSS: do we need this test? - describe 'exec_context: nil' do + describe "exec_context: nil" do representer!(module: mod, decorator: true) do property :name, as: ->(*) { self.class } end it { assert_equal_document(render(song), output) } - it { _(parse(song, input).name).must_equal 'Rebel Fate' } + it { _(parse(song, input).name).must_equal "Rebel Fate" } end - describe 'exec_context: :decorator' do # this tests if lambdas are run in the right context, if methods are called in the right context and if we can access the represented object. + describe "exec_context: :decorator" do # this tests if lambdas are run in the right context, if methods are called in the right context and if we can access the represented object. representer!(module: mod, decorator: true) do property :name, as: ->(*) { self.class.superclass }, exec_context: :decorator define_method :name do # def in Decorator class. - 'Timebomb' + "Timebomb" end define_method :"name=" do |v| # def in Decorator class. @@ -69,23 +69,23 @@ class ExecContextTest < MiniTest::Spec end end - it { assert_equal_document(render(song), { Representable::Decorator => 'Timebomb' }) } - it { _(parse(song, { Representable::Decorator => 'Listless' }).name).must_equal 'Listless' } + it { assert_equal_document(render(song), {Representable::Decorator => "Timebomb"}) } + it { _(parse(song, {Representable::Decorator => "Listless"}).name).must_equal "Listless" } end # DISCUSS: do we need this test? - describe 'exec_context: :binding' do + describe "exec_context: :binding" do representer!(module: mod, decorator: true) do property :name, as: ->(*) { self.class }, # to actually test exec_context: :binding, - setter: lambda { |options| + setter: ->(options) { options[:represented].name = options[:fragment] # to make parsing work. } end - it { assert_equal_document(render(song), { Representable::Hash::Binding => 'name' }) } - it('xxx') { _(parse(song, { Representable::Hash::Binding => 'Rebel Fate' }).name).must_equal 'Rebel Fate' } + it { assert_equal_document(render(song), {Representable::Hash::Binding => "name"}) } + it("xxx") { _(parse(song, {Representable::Hash::Binding => "Rebel Fate"}).name).must_equal "Rebel Fate" } end end end diff --git a/test/features_test.rb b/test/features_test.rb index 370769f5..a8f61441 100644 --- a/test/features_test.rb +++ b/test/features_test.rb @@ -1,17 +1,17 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class FeaturesTest < MiniTest::Spec module Title - def title = 'Is It A Lie' + def title; "Is It A Lie"; end end module Length - def length = '2:31' + def length; "2:31"; end end - definition = lambda { + definition = -> { feature Title feature Length @@ -25,7 +25,7 @@ def length = '2:31' let(:song) { OpenStruct.new(details: Object.new) } - describe 'Module' do + describe "Module" do representer! do instance_exec(&definition) end @@ -33,14 +33,14 @@ def length = '2:31' it { _(song.extend(representer).to_hash).must_equal( { - 'title' => 'Is It A Lie', 'length' => '2:31', - 'details' => { 'title' => 'Is It A Lie' } + "title" => "Is It A Lie", "length" => "2:31", + "details" => {"title" => "Is It A Lie"} } ) } end - describe 'Decorator' do + describe "Decorator" do representer!(decorator: true) do instance_exec(&definition) end @@ -48,8 +48,8 @@ def length = '2:31' it { _(representer.new(song).to_hash).must_equal( { - 'title' => 'Is It A Lie', 'length' => '2:31', - 'details' => { 'title' => 'Is It A Lie' } + "title" => "Is It A Lie", "length" => "2:31", + "details" => {"title" => "Is It A Lie"} } ) } @@ -59,7 +59,7 @@ def length = '2:31' class FeatureInclusionOrderTest < MiniTest::Spec module Title def title - 'I was first!' + "I was first!" end end @@ -83,8 +83,8 @@ def title it do _(representer.new(OpenStruct.new(song: Object)).to_hash).must_equal( { - 'title' => 'I am number two, I was first!', - 'song' => { 'title' => 'I am number two, I was first!' } + "title" => "I am number two, I was first!", + "song" => {"title" => "I am number two, I was first!"} } ) end diff --git a/test/filter_test.rb b/test/filter_test.rb index 2cf9c7cb..863068a2 100644 --- a/test/filter_test.rb +++ b/test/filter_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class FilterPipelineTest < MiniTest::Spec let(:block1) { ->(input, _options) { "1: #{input}" } } @@ -8,7 +8,7 @@ class FilterPipelineTest < MiniTest::Spec subject { Representable::Pipeline[block1, block2] } - it { _(subject.call('Horowitz', {})).must_equal '2: 1: Horowitz' } + it { _(subject.call("Horowitz", {})).must_equal "2: 1: Horowitz" } end class FilterTest < MiniTest::Spec @@ -22,24 +22,24 @@ class FilterTest < MiniTest::Spec # gets doc and options. it { - song = OpenStruct.new.extend(representer).from_hash('title' => 'VULCAN EARS', 'track' => 'Nine') - _(song.title).must_equal 'VULCAN EARS' + song = OpenStruct.new.extend(representer).from_hash("title" => "VULCAN EARS", "track" => "Nine") + _(song.title).must_equal "VULCAN EARS" _(song.track).must_equal 'nine,{"title"=>"VULCAN EARS", "track"=>"Nine"}' } it { _( OpenStruct.new( - 'title' => 'vulcan ears', - 'track' => 'Nine' + "title" => "vulcan ears", + "track" => "Nine" ).extend(representer).to_hash ).must_equal({ - 'title' => 'vulcan ears', - 'track' => 'NINE,{"title"=>"vulcan ears"},{}' + "title" => "vulcan ears", + "track" => 'NINE,{"title"=>"vulcan ears"},{}' }) } - describe '#parse_filter' do + describe "#parse_filter" do representer! do property :track, parse_filter: [ @@ -53,8 +53,8 @@ class FilterTest < MiniTest::Spec end # order matters. - it { _(OpenStruct.new.extend(representer).from_hash('track' => 'Nine').track).must_equal 'Nine-1-2' } - it { _(OpenStruct.new('track' => 'Nine').extend(representer).to_hash).must_equal({ 'track' => 'Nine-1-2' }) } + it { _(OpenStruct.new.extend(representer).from_hash("track" => "Nine").track).must_equal "Nine-1-2" } + it { _(OpenStruct.new("track" => "Nine").extend(representer).to_hash).must_equal({"track" => "Nine-1-2"}) } end end diff --git a/test/for_collection_test.rb b/test/for_collection_test.rb index edc5d649..1f7a80d7 100644 --- a/test/for_collection_test.rb +++ b/test/for_collection_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class ForCollectionTest < MiniTest::Spec module SongRepresenter @@ -9,13 +9,13 @@ module SongRepresenter property :name end - let(:songs) { [Song.new('Days Go By'), Song.new("Can't Take Them All")] } + let(:songs) { [Song.new("Days Go By"), Song.new("Can't Take Them All")] } let(:json) { "[{\"name\":\"Days Go By\"},{\"name\":\"Can't Take Them All\"}]" } # Module.for_collection # Decorator.for_collection for_formats( - hash: [Representable::Hash, out = [{ 'name' => 'Days Go By' }, { 'name' => "Can't Take Them All" }], out], + hash: [Representable::Hash, out = [{"name" => "Days Go By"}, {"name" => "Can't Take Them All"}], out], json: [Representable::JSON, out = "[{\"name\":\"Days Go By\"},{\"name\":\"Can't Take Them All\"}]", out] # :xml => [Representable::XML, out="", out] ) do |format, mod, output, input| diff --git a/test/generic_test.rb b/test/generic_test.rb index b3cf6762..97ebd78c 100644 --- a/test/generic_test.rb +++ b/test/generic_test.rb @@ -1,12 +1,12 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" # TODO: rename/restructure to CollectionTest. class GenericTest < MiniTest::Spec let(:new_album) { OpenStruct.new.extend(representer) } - let(:album) { OpenStruct.new(songs: ['Fuck Armageddon']).extend(representer) } - let(:song) { OpenStruct.new(title: 'Resist Stance') } + let(:album) { OpenStruct.new(songs: ["Fuck Armageddon"]).extend(representer) } + let(:song) { OpenStruct.new(title: "Resist Stance") } let(:song_representer) do Module.new do include Representable::Hash @@ -14,7 +14,7 @@ class GenericTest < MiniTest::Spec end end - describe '::collection' do + describe "::collection" do representer! do collection :songs end @@ -24,19 +24,19 @@ class GenericTest < MiniTest::Spec _(new_album.songs).must_be_nil end - it 'leaves properties untouched' do + it "leaves properties untouched" do album.from_hash({}) # TODO: test property. - _(album.songs).must_equal ['Fuck Armageddon'] # when the collection is not present in the incoming hash, this propery stays untouched. + _(album.songs).must_equal ["Fuck Armageddon"] # when the collection is not present in the incoming hash, this propery stays untouched. end # when collection is nil, it doesn't get rendered: for_formats( hash: [Representable::Hash, {}], - xml: [Representable::XML, ''], + xml: [Representable::XML, ""], yaml: [Representable::YAML, "--- {}\n"] # FIXME: this doesn't look right. ) do |format, mod, output, _input| - describe 'nil collections' do + describe "nil collections" do let(:format) { format } representer!(module: mod) do @@ -54,11 +54,11 @@ class GenericTest < MiniTest::Spec # when collection is set but empty, render the empty collection. for_formats( - hash: [Representable::Hash, { 'songs' => [] }], + hash: [Representable::Hash, {"songs" => []}], # :xml => [Representable::XML, ""], yaml: [Representable::YAML, "---\nsongs: []\n"] ) do |format, mod, output, _input| - describe 'empty collections' do + describe "empty collections" do let(:format) { format } representer!(module: mod) do @@ -109,7 +109,7 @@ class GenericTest < MiniTest::Spec end it "doesn't change represented object" do - _(song.extend(representer).send("from_#{format}", input).title).must_equal 'Resist Stance' + _(song.extend(representer).send("from_#{format}", input).title).must_equal "Resist Stance" end end end diff --git a/test/getter_setter_test.rb b/test/getter_setter_test.rb index efe61528..f41697ec 100644 --- a/test/getter_setter_test.rb +++ b/test/getter_setter_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class GetterSetterTest < BaseTest representer! do @@ -9,25 +9,25 @@ class GetterSetterTest < BaseTest setter: ->(user_options:, input:, **) { self.song_name = "#{user_options[:welcome]} #{input}" } end - subject { Struct.new(:song_name).new('Mony Mony').extend(representer) } + subject { Struct.new(:song_name).new("Mony Mony").extend(representer) } - it 'uses :getter when rendering' do - subject.instance_eval { def name = raise } - _(subject.to_hash(user_options: { welcome: 'Hi' })).must_equal({ 'name' => 'Hi Mony Mony' }) + it "uses :getter when rendering" do + subject.instance_eval { def name; fail; end } + _(subject.to_hash(user_options: {welcome: "Hi"})).must_equal({"name" => "Hi Mony Mony"}) end - it 'uses :setter when parsing' do + it "uses :setter when parsing" do subject.instance_eval do def name=(*) - raise + fail end self end _( subject.from_hash( - { 'name' => 'Eyes Without A Face' }, - user_options: { welcome: 'Hello' } + {"name" => "Eyes Without A Face"}, + user_options: {welcome: "Hello"} ).song_name - ).must_equal 'Hello Eyes Without A Face' + ).must_equal "Hello Eyes Without A Face" end end diff --git a/test/hash_bindings_test.rb b/test/hash_bindings_test.rb index a64e56bf..990a01cf 100644 --- a/test/hash_bindings_test.rb +++ b/test/hash_bindings_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class HashBindingTest < MiniTest::Spec module SongRepresenter @@ -13,72 +13,78 @@ class SongWithRepresenter < ::Song include SongRepresenter end - describe 'PropertyBinding' do - describe '#read' do + describe "PropertyBinding" do + describe "#read" do before do @property = Representable::Hash::Binding.new(Representable::Definition.new(:song)) end - it 'returns fragment if present' do - assert_equal 'Stick The Flag Up Your Goddamn Ass, You Sonofabitch', - @property.read({ 'song' => 'Stick The Flag Up Your Goddamn Ass, You Sonofabitch' }, 'song') - assert_equal '', @property.read({ 'song' => '' }, 'song') - assert_nil @property.read({ 'song' => nil }, 'song') + it "returns fragment if present" do + assert_equal "Stick The Flag Up Your Goddamn Ass, You Sonofabitch", + @property.read({"song" => "Stick The Flag Up Your Goddamn Ass, You Sonofabitch"}, "song") + assert_equal "", @property.read({"song" => ""}, "song") + assert_nil @property.read({"song" => nil}, "song") end - it 'returns FRAGMENT_NOT_FOUND if not in document' do - assert_equal Representable::Binding::FragmentNotFound, @property.read({}, 'song') + it "returns FRAGMENT_NOT_FOUND if not in document" do + assert_equal Representable::Binding::FragmentNotFound, @property.read({}, "song") end - it 'will not fail if given an empty hash value and will return FRAGMENT_NOT_FOUND' do - assert_equal Representable::Binding::FragmentNotFound, @property.read(nil, 'song') + it "will not fail if given an empty hash value and will return FRAGMENT_NOT_FOUND" do + assert_equal Representable::Binding::FragmentNotFound, @property.read(nil, "song") end end end - describe 'CollectionBinding' do - describe 'with plain text items' do + describe "CollectionBinding" do + describe "with plain text items" do before do - @property = Representable::Hash::Binding::Collection.new(Representable::Definition.new(:songs, - collection: true)) + @property = Representable::Hash::Binding::Collection.new( + Representable::Definition.new( + :songs, + collection: true + ) + ) end - it 'extracts with #read' do - assert_equal ['The Gargoyle', 'Bronx'], @property.read({ 'songs' => ['The Gargoyle', 'Bronx'] }, 'songs') + it "extracts with #read" do + assert_equal ["The Gargoyle", "Bronx"], @property.read({"songs" => ["The Gargoyle", "Bronx"]}, "songs") end - it 'inserts with #write' do + it "inserts with #write" do doc = {} - assert_equal(['The Gargoyle', 'Bronx'], @property.write(doc, ['The Gargoyle', 'Bronx'], 'songs')) - assert_equal({ 'songs' => ['The Gargoyle', 'Bronx'] }, doc) + + assert_equal(["The Gargoyle", "Bronx"], @property.write(doc, ["The Gargoyle", "Bronx"], "songs")) + assert_equal({"songs" => ["The Gargoyle", "Bronx"]}, doc) end end end - describe 'HashBinding' do - describe 'with plain text items' do + describe "HashBinding" do + describe "with plain text items" do before do @property = Representable::Hash::Binding.new(Representable::Definition.new(:songs, hash: true)) end - it 'extracts with #read' do + it "extracts with #read" do assert_equal( - { 'first' => 'The Gargoyle', 'second' => 'Bronx' }, - @property.read({ 'songs' => { 'first' => 'The Gargoyle', 'second' => 'Bronx' } }, 'songs') + {"first" => "The Gargoyle", "second" => "Bronx"}, + @property.read({"songs" => {"first" => "The Gargoyle", "second" => "Bronx"}}, "songs") ) end - it 'inserts with #write' do + it "inserts with #write" do doc = {} + assert_equal( - { 'first' => 'The Gargoyle', 'second' => 'Bronx' }, - @property.write(doc, { 'first' => 'The Gargoyle', 'second' => 'Bronx' }, 'songs') + {"first" => "The Gargoyle", "second" => "Bronx"}, + @property.write(doc, {"first" => "The Gargoyle", "second" => "Bronx"}, "songs") ) - assert_equal({ 'songs' => { 'first' => 'The Gargoyle', 'second' => 'Bronx' } }, doc) + assert_equal({"songs" => {"first" => "The Gargoyle", "second" => "Bronx"}}, doc) end end - describe 'with objects' do + describe "with objects" do before do @property = Representable::Hash::Binding.new( Representable::Definition.new( @@ -89,10 +95,11 @@ class SongWithRepresenter < ::Song end it "doesn't change the represented hash in #write" do - song = Song.new('Better Than That') - hash = { 'first' => song } - @property.write({}, hash, 'song') - assert_equal({ 'first' => song }, hash) + song = Song.new("Better Than That") + hash = {"first" => song} + @property.write({}, hash, "song") + + assert_equal({"first" => song}, hash) end end end diff --git a/test/hash_test.rb b/test/hash_test.rb index 15a24d2a..061de13f 100644 --- a/test/hash_test.rb +++ b/test/hash_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class HashPublicMethodsTest < Minitest::Spec #--- @@ -11,14 +11,14 @@ class BandRepresenter < Representable::Decorator property :name end - let(:data) { { 'id' => 1, 'name' => 'Rancid' } } + let(:data) { {"id" => 1, "name" => "Rancid"} } - it { _(BandRepresenter.new(Band.new).from_hash(data)[:id, :name]).must_equal [1, 'Rancid'] } - it { _(BandRepresenter.new(Band.new).parse(data)[:id, :name]).must_equal [1, 'Rancid'] } + it { _(BandRepresenter.new(Band.new).from_hash(data)[:id, :name]).must_equal [1, "Rancid"] } + it { _(BandRepresenter.new(Band.new).parse(data)[:id, :name]).must_equal [1, "Rancid"] } #--- # to_hash - let(:band) { Band.new(1, 'Rancid') } + let(:band) { Band.new(1, "Rancid") } it { _(BandRepresenter.new(band).to_hash).must_equal data } it { _(BandRepresenter.new(band).render).must_equal data } @@ -31,24 +31,24 @@ class HashWithScalarPropertyTest < MiniTest::Spec property :title end - let(:album) { Album.new('Liar') } + let(:album) { Album.new("Liar") } - describe '#to_hash' do - it 'renders plain property' do - _(album.extend(representer).to_hash).must_equal('title' => 'Liar') + describe "#to_hash" do + it "renders plain property" do + _(album.extend(representer).to_hash).must_equal("title" => "Liar") end end - describe '#from_hash' do - it 'parses plain property' do - _(album.extend(representer).from_hash('title' => 'This Song Is Recycled').title).must_equal 'This Song Is Recycled' + describe "#from_hash" do + it "parses plain property" do + _(album.extend(representer).from_hash("title" => "This Song Is Recycled").title).must_equal "This Song Is Recycled" end # Fixes issue #115 - it 'allows nil value in the incoming document and corresponding nil value for the represented' do + it "allows nil value in the incoming document and corresponding nil value for the represented" do album = Album.new _(album.title).must_be_nil - album.extend(representer).from_hash('title' => nil) + album.extend(representer).from_hash("title" => nil) end end end @@ -62,38 +62,38 @@ class HashWithTypedPropertyTest < MiniTest::Spec end end - let(:album) { Album.new(Song.new('Liar')) } + let(:album) { Album.new(Song.new("Liar")) } - describe '#to_hash' do - it 'renders embedded typed property' do - _(album.extend(representer).to_hash).must_equal('best_song' => { 'name' => 'Liar' }) + describe "#to_hash" do + it "renders embedded typed property" do + _(album.extend(representer).to_hash).must_equal("best_song" => {"name" => "Liar"}) end end - describe '#from_hash' do - it 'parses embedded typed property' do - album.extend(representer).from_hash('best_song' => { 'name' => 'Go With Me' }) - _(album.best_song.name).must_equal 'Go With Me' + describe "#from_hash" do + it "parses embedded typed property" do + album.extend(representer).from_hash("best_song" => {"name" => "Go With Me"}) + _(album.best_song.name).must_equal "Go With Me" end # nested nil removes nested object. it do - album = Album.new(Song.new('Pre-medicated Murder')) - album.extend(representer).from_hash('best_song' => nil) + album = Album.new(Song.new("Pre-medicated Murder")) + album.extend(representer).from_hash("best_song" => nil) _(album.best_song).must_be_nil end # nested blank hash creates blank object when not populated. it do album = Album.new # (Song.new("Pre-medicated Murder")) - album.extend(representer).from_hash('best_song' => {}) + album.extend(representer).from_hash("best_song" => {}) _(album.best_song.name).must_be_nil end # Fixes issue #115 - it 'allows nil value in the incoming document and corresponding nil value for the represented' do + it "allows nil value in the incoming document and corresponding nil value for the represented" do album = Album.new - album.extend(representer).from_hash('best_song' => nil) + album.extend(representer).from_hash("best_song" => nil) _(album.best_song).must_be_nil end end @@ -107,11 +107,11 @@ class HashWithTypedPropertyAndAs < MiniTest::Spec end end - let(:album) { OpenStruct.new(song: Song.new('Liar')).extend(representer) } + let(:album) { OpenStruct.new(song: Song.new("Liar")).extend(representer) } - it { _(album.to_hash).must_equal('hit' => { 'name' => 'Liar' }) } + it { _(album.to_hash).must_equal("hit" => {"name" => "Liar"}) } it { - _(album.from_hash('hit' => { 'name' => 'Go With Me' })).must_equal OpenStruct.new(song: Song.new('Go With Me')) + _(album.from_hash("hit" => {"name" => "Go With Me"})).must_equal OpenStruct.new(song: Song.new("Go With Me")) } end # # describe "FIXME COMBINE WITH ABOVE with :extend and :as" do @@ -144,32 +144,32 @@ class HashWithTypedCollectionTest < MiniTest::Spec end end - let(:album) { Album.new([Song.new('Liar', 1), Song.new('What I Know', 2)]) } + let(:album) { Album.new([Song.new("Liar", 1), Song.new("What I Know", 2)]) } - describe '#to_hash' do - it 'renders collection of typed property' do + describe "#to_hash" do + it "renders collection of typed property" do _(album.extend(representer).to_hash).must_equal( - 'songs' => [ - { 'name' => 'Liar', 'track' => 1 }, - { 'name' => 'What I Know', 'track' => 2 } + "songs" => [ + {"name" => "Liar", "track" => 1}, + {"name" => "What I Know", "track" => 2} ] ) end end - describe '#from_hash' do - it 'parses collection of typed property' do + describe "#from_hash" do + it "parses collection of typed property" do _( album.extend(representer).from_hash( - 'songs' => [ - { 'name' => 'One Shot Deal', 'track' => 4 }, + "songs" => [ + {"name" => "One Shot Deal", "track" => 4}, { - 'name' => 'Three Way Dance', - 'track' => 5 + "name" => "Three Way Dance", + "track" => 5 } ] ) - ).must_equal Album.new([Song.new('One Shot Deal', 4), Song.new('Three Way Dance', 5)]) + ).must_equal Album.new([Song.new("One Shot Deal", 4), Song.new("Three Way Dance", 5)]) end end end @@ -178,24 +178,24 @@ class HashWithScalarCollectionTest < MiniTest::Spec Album = Struct.new(:songs) representer! { collection :songs } - let(:album) { Album.new(['Jackhammer', 'Terrible Man']) } + let(:album) { Album.new(["Jackhammer", "Terrible Man"]) } - describe '#to_hash' do - it 'renders a block style list per default' do - _(album.extend(representer).to_hash).must_equal('songs' => ['Jackhammer', 'Terrible Man']) + describe "#to_hash" do + it "renders a block style list per default" do + _(album.extend(representer).to_hash).must_equal("songs" => ["Jackhammer", "Terrible Man"]) end end - describe '#from_hash' do - it 'parses a block style list' do + describe "#from_hash" do + it "parses a block style list" do _( album.extend(representer).from_hash( - 'songs' => [ - 'Off Key Melody', - 'Sinking' + "songs" => [ + "Off Key Melody", + "Sinking" ] ) - ).must_equal Album.new(['Off Key Melody', 'Sinking']) + ).must_equal Album.new(["Off Key Melody", "Sinking"]) end end end diff --git a/test/heritage_test.rb b/test/heritage_test.rb index 69d1eaf9..7e99c75e 100644 --- a/test/heritage_test.rb +++ b/test/heritage_test.rb @@ -1,17 +1,17 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class HeritageTest < Minitest::Spec module Hello def hello - 'Hello!' + "Hello!" end end module Ciao def ciao - 'Ciao!' + "Ciao!" end end @@ -35,16 +35,16 @@ class C < A property :id do end # overwrite old :id. end - it 'B must inherit Hello! feature from A' do - _(B.representable_attrs.get(:id)[:extend].call(nil).new(nil).hello).must_equal 'Hello!' + it "B must inherit Hello! feature from A" do + _(B.representable_attrs.get(:id)[:extend].call(nil).new(nil).hello).must_equal "Hello!" end - it 'B must have Ciao from module (feauture) Ciao' do - _(B.representable_attrs.get(:id)[:extend].call(nil).new(nil).ciao).must_equal 'Ciao!' + it "B must have Ciao from module (feauture) Ciao" do + _(B.representable_attrs.get(:id)[:extend].call(nil).new(nil).ciao).must_equal "Ciao!" end - it 'C must inherit Hello! feature from A' do - _(C.representable_attrs.get(:id)[:extend].call(nil).new(nil).hello).must_equal 'Hello!' + it "C must inherit Hello! feature from A" do + _(C.representable_attrs.get(:id)[:extend].call(nil).new(nil).hello).must_equal "Hello!" end module M @@ -60,7 +60,7 @@ module N let(:obj_extending_N) { Object.new.extend(N) } - it 'obj should inherit from N, and N from M' do - _(obj_extending_N.hello).must_equal 'Hello!' + it "obj should inherit from N, and N from M" do + _(obj_extending_N.hello).must_equal "Hello!" end end diff --git a/test/if_test.rb b/test/if_test.rb index bd5375a9..228fd026 100644 --- a/test/if_test.rb +++ b/test/if_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class IfTest < MiniTest::Spec let(:band_class) do @@ -12,77 +12,81 @@ class IfTest < MiniTest::Spec end end - it 'respects property when condition true' do + it "respects property when condition true" do band_class.class_eval { property :fame, if: ->(*) { true } } band = band_class.new - band.from_hash({ 'fame' => 'oh yes' }) - assert_equal 'oh yes', band.fame + band.from_hash({"fame" => "oh yes"}) + + assert_equal "oh yes", band.fame end - it 'ignores property when condition false' do + it "ignores property when condition false" do band_class.class_eval { property :fame, if: ->(*) { false } } band = band_class.new - band.from_hash({ 'fame' => 'oh yes' }) + band.from_hash({"fame" => "oh yes"}) + assert_nil band.fame end it "ignores property when :exclude'ed even when condition is true" do band_class.class_eval { property :fame, if: ->(*) { true } } band = band_class.new - band.from_hash({ 'fame' => 'oh yes' }, { exclude: [:fame] }) + band.from_hash({"fame" => "oh yes"}, {exclude: [:fame]}) + assert_nil band.fame end - it 'executes block in instance context' do + it "executes block in instance context" do band_class.class_eval do property :fame, if: ->(*) { groupies } attr_accessor :groupies end band = band_class.new band.groupies = true - band.from_hash({ 'fame' => 'oh yes' }) - assert_equal 'oh yes', band.fame + band.from_hash({"fame" => "oh yes"}) + + assert_equal "oh yes", band.fame end - describe 'executing :if lambda in represented instance context' do + describe "executing :if lambda in represented instance context" do representer! do property :label, if: ->(*) { signed_contract } end - subject { OpenStruct.new(signed_contract: false, label: 'Fat') } + subject { OpenStruct.new(signed_contract: false, label: "Fat") } - it 'skips when false' do + it "skips when false" do _(subject.extend(representer).to_hash).must_equal({}) end - it 'represents when true' do + it "represents when true" do subject.signed_contract = true - _(subject.extend(representer).to_hash).must_equal({ 'label' => 'Fat' }) + _(subject.extend(representer).to_hash).must_equal({"label" => "Fat"}) end - it 'works with decorator' do + it "works with decorator" do rpr = representer _( - Class.new(Representable::Decorator) do + Class.new(Representable::Decorator) { include Representable::Hash include rpr - end.new(subject).to_hash + }.new(subject).to_hash ).must_equal({}) end end - describe 'propagating user options to the block' do + describe "propagating user options to the block" do representer! do property :name, if: ->(opts) { opts[:user_options][:include_name] } end - subject { OpenStruct.new(name: 'Outbound').extend(representer) } + subject { OpenStruct.new(name: "Outbound").extend(representer) } - it 'works without specifying options' do + it "works without specifying options" do _(subject.to_hash).must_equal({}) end - it 'passes user options to block' do - _(subject.to_hash(user_options: { include_name: true })).must_equal({ 'name' => 'Outbound' }) + it "passes user options to block" do + _(subject.to_hash(user_options: {include_name: true})).must_equal({"name" => "Outbound"}) end end end diff --git a/test/include_exclude_test.rb b/test/include_exclude_test.rb index 9d4bb331..de967e68 100644 --- a/test/include_exclude_test.rb +++ b/test/include_exclude_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class IncludeExcludeTest < Minitest::Spec Song = Struct.new(:title, :artist, :id) @@ -19,67 +19,67 @@ class IncludeExcludeTest < Minitest::Spec end end - let(:song) { Song.new('Listless', Artist.new('7yearsbadluck', 1)) } + let(:song) { Song.new("Listless", Artist.new("7yearsbadluck", 1)) } let(:decorator) { representer.new(song) } - describe '#from_hash' do - it 'accepts :exclude option' do - decorator.from_hash({ 'title' => "Don't Smile In Trouble", 'artist' => { 'id' => 2 } }, exclude: [:title]) + describe "#from_hash" do + it "accepts :exclude option" do + decorator.from_hash({"title" => "Don't Smile In Trouble", "artist" => {"id" => 2}}, exclude: [:title]) - _(song.title).must_equal 'Listless' + _(song.title).must_equal "Listless" _(song.artist).must_equal Artist.new(nil, 2) end - it 'accepts :include option' do - decorator.from_hash({ 'title' => "Don't Smile In Trouble", 'artist' => { 'id' => 2 } }, include: [:title]) + it "accepts :include option" do + decorator.from_hash({"title" => "Don't Smile In Trouble", "artist" => {"id" => 2}}, include: [:title]) _(song.title).must_equal "Don't Smile In Trouble" - _(song.artist).must_equal Artist.new('7yearsbadluck', 1) + _(song.artist).must_equal Artist.new("7yearsbadluck", 1) end - it 'accepts nested :exclude/:include option' do + it "accepts nested :exclude/:include option" do decorator.from_hash( { - 'title' => "Don't Smile In Trouble", - 'artist' => { 'name' => 'Foo', 'id' => 2, 'songs' => [{ 'id' => 1, 'title' => 'Listless' }] } + "title" => "Don't Smile In Trouble", + "artist" => {"name" => "Foo", "id" => 2, "songs" => [{"id" => 1, "title" => "Listless"}]} }, exclude: [:title], artist: { exclude: [:id], - songs: { include: [:title] } + songs: {include: [:title]} } ) - _(song.title).must_equal 'Listless' - _(song.artist).must_equal Artist.new('Foo', nil, [Song.new('Listless', nil, nil)]) + _(song.title).must_equal "Listless" + _(song.artist).must_equal Artist.new("Foo", nil, [Song.new("Listless", nil, nil)]) end end - describe '#to_hash' do - it 'accepts :exclude option' do - _(decorator.to_hash(exclude: [:title])).must_equal({ 'artist' => { 'name' => '7yearsbadluck', 'id' => 1 } }) + describe "#to_hash" do + it "accepts :exclude option" do + _(decorator.to_hash(exclude: [:title])).must_equal({"artist" => {"name" => "7yearsbadluck", "id" => 1}}) end - it 'accepts :include option' do - _(decorator.to_hash(include: [:title])).must_equal({ 'title' => 'Listless' }) + it "accepts :include option" do + _(decorator.to_hash(include: [:title])).must_equal({"title" => "Listless"}) end - it 'accepts nested :exclude/:include option' do - decorator = representer.new(Song.new('Listless', Artist.new('7yearsbadluck', 1, [Song.new('C.O.A.B.I.E.T.L.')]))) + it "accepts nested :exclude/:include option" do + decorator = representer.new(Song.new("Listless", Artist.new("7yearsbadluck", 1, [Song.new("C.O.A.B.I.E.T.L.")]))) _( decorator.to_hash( exclude: [:title], artist: { exclude: [:id], - songs: { include: [:title] } + songs: {include: [:title]} } ) - ).must_equal({ 'artist' => { 'name' => '7yearsbadluck', 'songs' => [{ 'title' => 'C.O.A.B.I.E.T.L.' }] } }) + ).must_equal({"artist" => {"name" => "7yearsbadluck", "songs" => [{"title" => "C.O.A.B.I.E.T.L."}]}}) end end - it 'xdoes not propagate private options to nested objects' do + it "xdoes not propagate private options to nested objects" do Cover = Struct.new(:title, :original) cover_rpr = Module.new do @@ -91,8 +91,8 @@ class IncludeExcludeTest < Minitest::Spec # FIXME: we should test all representable-options (:include, :exclude, ?) _( - Cover.new('Roxanne', Cover.new("Roxanne (Don't Put On The Red Light)")).extend(cover_rpr) + Cover.new("Roxanne", Cover.new("Roxanne (Don't Put On The Red Light)")).extend(cover_rpr) .to_hash(include: [:original]) - ).must_equal({ 'original' => { 'title' => "Roxanne (Don't Put On The Red Light)" } }) + ).must_equal({"original" => {"title" => "Roxanne (Don't Put On The Red Light)"}}) end end diff --git a/test/inherit_test.rb b/test/inherit_test.rb index eac8c57e..dc39ac29 100644 --- a/test/inherit_test.rb +++ b/test/inherit_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class InheritTest < MiniTest::Spec # it's important to have a global module so we can test if stuff gets overridden in the original module. @@ -13,22 +13,22 @@ module SongRepresenter property :track, as: :no end - let(:song) { Song.new(Struct.new(:string).new('Roxanne'), 1) } + let(:song) { Song.new(Struct.new(:string).new("Roxanne"), 1) } - describe ':inherit plain property' do + describe ":inherit plain property" do representer! do include SongRepresenter - property :track, inherit: true, getter: ->(*) { 'n/a' } + property :track, inherit: true, getter: ->(*) { "n/a" } end - it { _(SongRepresenter.prepare(song).to_hash).must_equal({ 'title' => { 'str' => 'Roxanne' }, 'no' => 1 }) } + it { _(SongRepresenter.prepare(song).to_hash).must_equal({"title" => {"str" => "Roxanne"}, "no" => 1}) } it { - _(representer.prepare(song).to_hash).must_equal({ 'title' => { 'str' => 'Roxanne' }, 'no' => 'n/a' }) + _(representer.prepare(song).to_hash).must_equal({"title" => {"str" => "Roxanne"}, "no" => "n/a"}) } # as: inherited. end - describe ':inherit with empty inline representer' do + describe ":inherit with empty inline representer" do representer! do include SongRepresenter @@ -41,26 +41,26 @@ module SongRepresenter _( SongRepresenter.prepare( Song.new( - Struct.new(:string).new('Believe It'), + Struct.new(:string).new("Believe It"), 1 ) ).to_hash - ).must_equal({ 'title' => { 'str' => 'Believe It' }, 'no' => 1 }) + ).must_equal({"title" => {"str" => "Believe It"}, "no" => 1}) } # the block doesn't override the inline representer. it { _( representer.prepare( Song.new( - Struct.new(:string).new('Believe It'), + Struct.new(:string).new("Believe It"), 1 ) ).to_hash - ).must_equal({ 'title' => { 'str' => 'Believe It' }, 'no' => 1 }) + ).must_equal({"title" => {"str" => "Believe It"}, "no" => 1}) } end - describe ':inherit with overriding inline representer' do + describe ":inherit with overriding inline representer" do representer! do include SongRepresenter @@ -75,15 +75,15 @@ module SongRepresenter _( representer.prepare( Song.new( - Struct.new(:string, :length).new('Believe It', 10), + Struct.new(:string, :length).new("Believe It", 10), 1 ) ).to_hash - ).must_equal({ 'title' => { 's' => 'Believe It', 'length' => 10 }, 'no' => 1 }) + ).must_equal({"title" => {"s" => "Believe It", "length" => 10}, "no" => 1}) } end - describe ':inherit with empty inline and options' do + describe ":inherit with empty inline and options" do representer! do include SongRepresenter @@ -96,25 +96,25 @@ module SongRepresenter _( SongRepresenter.prepare( Song.new( - Struct.new(:string).new('Believe It'), + Struct.new(:string).new("Believe It"), 1 ) ).to_hash - ).must_equal({ 'title' => { 'str' => 'Believe It' }, 'no' => 1 }) + ).must_equal({"title" => {"str" => "Believe It"}, "no" => 1}) } it { _( representer.prepare( Song.new( - Struct.new(:string).new('Believe It'), + Struct.new(:string).new("Believe It"), 1 ) ).to_hash - ).must_equal({ 'name' => { 'str' => 'Believe It' }, 'no' => 1 }) + ).must_equal({"name" => {"str" => "Believe It"}, "no" => 1}) } end - describe ':inherit with inline without block but options' do + describe ":inherit with inline without block but options" do representer! do include SongRepresenter @@ -125,50 +125,50 @@ module SongRepresenter _( SongRepresenter.prepare( Song.new( - Struct.new(:string).new('Believe It'), + Struct.new(:string).new("Believe It"), 1 ) ).to_hash - ).must_equal({ 'title' => { 'str' => 'Believe It' }, 'no' => 1 }) + ).must_equal({"title" => {"str" => "Believe It"}, "no" => 1}) } it { _( representer.prepare( Song.new( - Struct.new(:string).new('Believe It'), + Struct.new(:string).new("Believe It"), 1 ) ).to_hash - ).must_equal({ 'name' => { 'str' => 'Believe It' }, 'no' => 1 }) + ).must_equal({"name" => {"str" => "Believe It"}, "no" => 1}) } end # no :inherit - describe 'overwriting without :inherit' do + describe "overwriting without :inherit" do representer! do include SongRepresenter property :track, representable: true end - it 'replaces inherited property' do + it "replaces inherited property" do _(representer.representable_attrs.size).must_equal 2 definition = representer.representable_attrs.get(:track) # TODO: find a better way to assert Definition identity. # definition.keys.size.must_equal 2 _(definition[:representable]).must_equal true - _(definition.name).must_equal 'track' # was "no". + _(definition.name).must_equal "track" # was "no". end end # decorator - describe ':inherit with decorator' do + describe ":inherit with decorator" do representer!(decorator: true) do property :hit do property :title, exec_context: :decorator def title - 'Cheap Transistor Radio' + "Cheap Transistor Radio" end end end @@ -189,13 +189,13 @@ class InheritingDecorator < representer representer.new( OpenStruct.new( hit: OpenStruct.new( - title: 'I WILL BE OVERRIDDEN', - length: '2:59' + title: "I WILL BE OVERRIDDEN", + length: "2:59" ) ) ).to_hash ).must_equal( - { 'hit' => { 'title' => 'Cheap Transistor Radio' } } + {"hit" => {"title" => "Cheap Transistor Radio"}} ) } @@ -206,15 +206,15 @@ class InheritingDecorator < representer inheriting.new( OpenStruct.new( hit: OpenStruct.new( - title: 'Hole In Your Soul', - length: '2:59' + title: "Hole In Your Soul", + length: "2:59" ) ) ).to_hash ).must_equal( { - 'hit' => { - 'title' => 'Cheap Transistor Radio', 'length' => '2:59' + "hit" => { + "title" => "Cheap Transistor Radio", "length" => "2:59" } } ) @@ -222,12 +222,12 @@ class InheritingDecorator < representer end # :inherit when property doesn't exist, yet. - describe ':inherit without inheritable property' do + describe ":inherit without inheritable property" do representer! do property :name, inherit: true end - it { _(representer.prepare(Song.new('The Beginning')).to_hash).must_equal({ 'name' => 'The Beginning' }) } + it { _(representer.prepare(Song.new("The Beginning")).to_hash).must_equal({"name" => "The Beginning"}) } end end diff --git a/test/inline_test.rb b/test/inline_test.rb index 16c931fb..58bb8485 100644 --- a/test/inline_test.rb +++ b/test/inline_test.rb @@ -1,14 +1,18 @@ -require 'test_helper' +require "test_helper" class InlineTest < MiniTest::Spec - let(:song) { Song.new('Alive') } + let(:song) { Song.new("Alive") } let(:request) { representer.prepare(OpenStruct.new(song: song)) } { - hash: [Representable::Hash, { 'song' => { 'name' => 'Alive' } }, - { 'song' => { 'name' => "You've Taken Everything" } }], - json: [Representable::JSON, '{"song":{"name":"Alive"}}', - "{\"song\":{\"name\":\"You've Taken Everything\"}}"], + hash: [ + Representable::Hash, {"song" => {"name" => "Alive"}}, + {"song" => {"name" => "You've Taken Everything"}} + ], + json: [ + Representable::JSON, '{"song":{"name":"Alive"}}', + "{\"song\":{\"name\":\"You've Taken Everything\"}}" + ], xml: [ Representable::XML, "\n \n Alive\n \n", "You've Taken Everything/open_struct>" @@ -32,13 +36,17 @@ class InlineTest < MiniTest::Spec end { - hash: [Representable::Hash, { 'songs' => [{ 'name' => 'Alive' }] }, - { 'songs' => [{ 'name' => "You've Taken Everything" }] }], - json: [Representable::JSON, '{"songs":[{"name":"Alive"}]}', - "{\"songs\":[{\"name\":\"You've Taken Everything\"}]}"], + hash: [ + Representable::Hash, {"songs" => [{"name" => "Alive"}]}, + {"songs" => [{"name" => "You've Taken Everything"}]} + ], + json: [ + Representable::JSON, '{"songs":[{"name":"Alive"}]}', + "{\"songs\":[{\"name\":\"You've Taken Everything\"}]}" + ], xml: [ Representable::XML, "\n \n Alive\n \n", - "You've Taken Everything", { as: :song } + "You've Taken Everything", {as: :song} ], yaml: [Representable::YAML, "---\nsongs:\n- name: Alive\n", "---\nsongs:\n- name: You've Taken Everything\n"] }.each do |format, cfg| @@ -61,14 +69,14 @@ class InlineTest < MiniTest::Spec end end - describe 'without :class' do + describe "without :class" do representer! do property :song do property :name end end - it { _(request.to_hash).must_equal({ 'song' => { 'name' => 'Alive' } }) } + it { _(request.to_hash).must_equal({"song" => {"name" => "Alive"}}) } end for_formats( @@ -89,8 +97,8 @@ class InlineTest < MiniTest::Spec end end - describe 'inheriting from outer representer' do - let(:request) { Struct.new(:song, :requester).new(song, 'Josephine') } + describe "inheriting from outer representer" do + let(:request) { Struct.new(:song, :requester).new(song, "Josephine") } [false, true].each do |is_decorator| # test for module and decorator. representer!(decorator: is_decorator) do @@ -103,14 +111,14 @@ class InlineTest < MiniTest::Spec let(:decorator) { representer.prepare(request) } - it { _(decorator.to_hash).must_equal({ 'requester' => 'Josephine', 'song' => { 'name' => 'Alive' } }) } + it { _(decorator.to_hash).must_equal({"requester" => "Josephine", "song" => {"name" => "Alive"}}) } it { - _(decorator.from_hash({ 'song' => { 'name' => "You've Taken Everything" } }).song.name).must_equal "You've Taken Everything" + _(decorator.from_hash({"song" => {"name" => "You've Taken Everything"}}).song.name).must_equal "You've Taken Everything" } end end - describe 'object pollution' do + describe "object pollution" do representer!(decorator: true) do property :song do property :name @@ -155,7 +163,7 @@ class InlineTest < MiniTest::Spec for_formats( { - hash: [Representable::Hash, { 'album' => { 'artist' => { 'label' => 'Epitaph' } } }] + hash: [Representable::Hash, {"album" => {"artist" => {"label" => "Epitaph"}}}] # :xml => [Representable::XML, ""], # :yaml => [Representable::YAML, "---\nlabel:\n label: Epitaph\n owner: Brett Gurewitz\n"] } @@ -165,18 +173,18 @@ class ArtistDecorator < Representable::Decorator property :label end - describe ':getter with :decorator' do + describe ":getter with :decorator" do let(:format) { format } representer!(module: mod) do - self.representation_wrap = 'album' + self.representation_wrap = "album" property :artist, getter: ->(_args) { represented }, decorator: ArtistDecorator end - let(:album) { OpenStruct.new(label: 'Epitaph').extend(representer) } + let(:album) { OpenStruct.new(label: "Epitaph").extend(representer) } - it 'renders nested Album-properties in separate section' do + it "renders nested Album-properties in separate section" do assert_equal_document(render(album), output) end end @@ -185,7 +193,7 @@ class ArtistDecorator < Representable::Decorator # test helper methods within inline representer for_formats( { - hash: [Representable::Hash, { 'song' => { 'name' => 'ALIVE' } }], + hash: [Representable::Hash, {"song" => {"name" => "ALIVE"}}], xml: [Representable::XML, "\n \n ALIVE\n \n"], yaml: [Representable::YAML, "---\nsong:\n name: ALIVE\n"] } @@ -208,7 +216,7 @@ class ArtistDecorator < Representable::Decorator end end - let(:request) { representer.prepare(OpenStruct.new(song: Song.new('Alive'))) } + let(:request) { representer.prepare(OpenStruct.new(song: Song.new("Alive"))) } it do assert_equal_document(render(request), output) @@ -216,7 +224,7 @@ class ArtistDecorator < Representable::Decorator end end - describe 'include module in inline representers' do + describe "include module in inline representers" do representer! do extension = Module.new do include Representable::Hash @@ -233,60 +241,60 @@ class ArtistDecorator < Representable::Decorator _( OpenStruct.new( song: OpenStruct.new( - title: 'The Fever And The Sound', - artist: 'Strung Out' + title: "The Fever And The Sound", + artist: "Strung Out" ) ).extend(representer) .to_hash ) - .must_equal({ 'song' => { 'artist' => 'Strung Out', 'title' => 'The Fever And The Sound' } }) + .must_equal({"song" => {"artist" => "Strung Out", "title" => "The Fever And The Sound"}}) end end # define method in inline representer - describe 'define method in inline representer' do + describe "define method in inline representer" do Mod = Module.new do include Representable::Hash def song - 'Object.new' + "Object.new" end property :song do property :duration def duration - '6:53' + "6:53" end end end it { assert_equal( - { 'song' => { 'duration' => '6:53' } }, + {"song" => {"duration" => "6:53"}}, OpenStruct.new.extend(Mod).to_hash ) } end # define method inline with Decorator - describe 'define method inline with Decorator' do + describe "define method inline with Decorator" do dec = Class.new(Representable::Decorator) do include Representable::Hash def song - 'Object.new' + "Object.new" end property :song, exec_context: :decorator do property :duration, exec_context: :decorator def duration - '6:53' + "6:53" end end end - it { _(dec.new(Object.new).to_hash).must_equal('song' => { 'duration' => '6:53' }) } + it { _(dec.new(Object.new).to_hash).must_equal("song" => {"duration" => "6:53"}) } end end diff --git a/test/instance_test.rb b/test/instance_test.rb index 2c793331..8450307c 100644 --- a/test/instance_test.rb +++ b/test/instance_test.rb @@ -1,21 +1,21 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class InstanceTest < BaseTest Song = Struct.new(:id, :title) Song.class_eval do def self.find(id) - new(id, 'Invincible') + new(id, "Invincible") end end - describe 'lambda { fragment } (new way of class: lambda { nil })' do + describe "lambda { fragment } (new way of class: lambda { nil })" do representer! do property :title, instance: ->(options) { options[:fragment] } end - it 'skips creating new instance' do + it "skips creating new instance" do object = Object.new object.instance_eval do def from_hash(hash, *_args) @@ -23,42 +23,42 @@ def from_hash(hash, *_args) end end - song = OpenStruct.new.extend(representer).from_hash({ 'title' => object }) + song = OpenStruct.new.extend(representer).from_hash({"title" => object}) _(song.title).must_equal object end end # TODO: use *args in from_hash. # DISCUSS: do we need parse_strategy? - describe 'property with :instance' do + describe "property with :instance" do representer!(inject: :song_representer) do property :song, - instance: lambda { |options| - options[:fragment]['id'] == song.id ? song : Song.find(options[:fragment]['id']) + instance: ->(options) { + options[:fragment]["id"] == song.id ? song : Song.find(options[:fragment]["id"]) }, extend: song_representer end - it('xxx') { + it("xxx") { _( - OpenStruct.new(song: Song.new(1, 'The Answer Is Still No')).extend(representer) - .from_hash('song' => { 'id' => 1 }).song - ).must_equal Song.new(1, 'The Answer Is Still No') + OpenStruct.new(song: Song.new(1, "The Answer Is Still No")).extend(representer) + .from_hash("song" => {"id" => 1}).song + ).must_equal Song.new(1, "The Answer Is Still No") } it { _( - OpenStruct.new(song: Song.new(1, 'The Answer Is Still No')).extend(representer) - .from_hash('song' => { 'id' => 2 }).song - ).must_equal Song.new(2, 'Invincible') + OpenStruct.new(song: Song.new(1, "The Answer Is Still No")).extend(representer) + .from_hash("song" => {"id" => 2}).song + ).must_equal Song.new(2, "Invincible") } end - describe 'collection with :instance' do + describe "collection with :instance" do representer!(inject: :song_representer) do collection :songs, - instance: lambda { |options| - options[:fragment]['id'] == songs[options[:index]].id ? songs[options[:index]] : Song.find(options[:fragment]['id']) + instance: ->(options) { + options[:fragment]["id"] == songs[options[:index]].id ? songs[options[:index]] : Song.find(options[:fragment]["id"]) }, # let's not allow returning nil anymore. make sure we can still do everything as with nil. also, let's remove parse_strategy: sync. extend: song_representer @@ -67,33 +67,33 @@ def from_hash(hash, *_args) it { album = Struct.new(:songs).new( [ - Song.new(1, 'The Answer Is Still No'), - Song.new(2, '') + Song.new(1, "The Answer Is Still No"), + Song.new(2, "") ] ) _( album .extend(representer) - .from_hash('songs' => [{ 'id' => 2 }, { 'id' => 2, 'title' => 'The Answer Is Still No' }]).songs + .from_hash("songs" => [{"id" => 2}, {"id" => 2, "title" => "The Answer Is Still No"}]).songs ).must_equal [ - Song.new(2, 'Invincible'), Song.new(2, 'The Answer Is Still No') + Song.new(2, "Invincible"), Song.new(2, "The Answer Is Still No") ] } end - describe 'property with lambda receiving fragment and args' do + describe "property with lambda receiving fragment and args" do representer!(inject: :song_representer) do - property :song, instance: lambda { |options| + property :song, instance: ->(options) { Struct.new(:args, :id).new([options[:fragment], options[:user_options]]) }, extend: song_representer end it { _( - OpenStruct.new(song: Song.new(1, 'The Answer Is Still No')).extend(representer) - .from_hash({ 'song' => { 'id' => 1 } }, user_options: { volume: 1 }).song.args - ).must_equal([{ 'id' => 1 }, { volume: 1 }]) + OpenStruct.new(song: Song.new(1, "The Answer Is Still No")).extend(representer) + .from_hash({"song" => {"id" => 1}}, user_options: {volume: 1}).song.args + ).must_equal([{"id" => 1}, {volume: 1}]) } end @@ -119,10 +119,10 @@ def from_hash(hash, *_args) # lambda { |fragment, i, Context(binding: <..>, args: [..])| } - describe 'sync' do + describe "sync" do representer!(inject: :song_representer) do collection :songs, - instance: lambda { |options| + instance: ->(options) { songs[options[:index]] }, extend: song_representer, @@ -133,18 +133,18 @@ def from_hash(hash, *_args) it { album = Struct.new(:songs).new( songs = [ - Song.new(1, 'The Answer Is Still No'), - Song.new(2, 'Invncble') + Song.new(1, "The Answer Is Still No"), + Song.new(2, "Invncble") ] ) album .extend(representer) - .from_hash('songs' => [{ 'title' => 'The Answer Is Still No' }, { 'title' => 'Invincible' }]) + .from_hash("songs" => [{"title" => "The Answer Is Still No"}, {"title" => "Invincible"}]) _(album.songs).must_equal [ - Song.new(1, 'The Answer Is Still No'), - Song.new(2, 'Invincible') + Song.new(1, "The Answer Is Still No"), + Song.new(2, "Invincible") ] _(songs.object_id).must_equal album.songs.object_id @@ -153,12 +153,12 @@ def from_hash(hash, *_args) } end - describe 'update existing elements, only' do + describe "update existing elements, only" do representer!(inject: :song_representer) do collection :songs, - instance: lambda { |options| + instance: ->(options) { # fragment["id"] == songs[i].id ? songs[i] : Song.find(fragment["id"]) - songs.find { |s| s.id == options[:fragment]['id'] } + songs.find { |s| s.id == options[:fragment]["id"] } }, # let's not allow returning nil anymore. make sure we can still do everything as with nil. also, let's remove parse_strategy: sync. extend: song_representer, @@ -166,22 +166,22 @@ def from_hash(hash, *_args) setter: ->(*) {} end - it('hooray') { + it("hooray") { album = Struct.new(:songs).new( songs = [ - Song.new(1, 'The Answer Is Still No'), - Song.new(2, 'Invncble') + Song.new(1, "The Answer Is Still No"), + Song.new(2, "Invncble") ] ) _( album .extend(representer) - .from_hash('songs' => [{ 'id' => 2, 'title' => 'Invincible' }]) + .from_hash("songs" => [{"id" => 2, "title" => "Invincible"}]) .songs ).must_equal [ - Song.new(1, 'The Answer Is Still No'), - Song.new(2, 'Invincible') + Song.new(1, "The Answer Is Still No"), + Song.new(2, "Invincible") ] # TODO: check elements object_id! @@ -191,10 +191,10 @@ def from_hash(hash, *_args) } end - describe 'add incoming elements, only' do + describe "add incoming elements, only" do representer!(inject: :song_representer) do collection :songs, - instance: lambda { |_options| + instance: ->(_options) { songs << song = Song.new(2) song }, # let's not allow returning nil anymore. make sure we can still do everything as with nil. also, let's remove parse_strategy: sync. @@ -207,18 +207,18 @@ def from_hash(hash, *_args) it { album = Struct.new(:songs).new( songs = [ - Song.new(1, 'The Answer Is Still No') + Song.new(1, "The Answer Is Still No") ] ) _( album .extend(representer) - .from_hash('songs' => [{ 'title' => 'Invincible' }]) + .from_hash("songs" => [{"title" => "Invincible"}]) .songs ).must_equal [ - Song.new(1, 'The Answer Is Still No'), - Song.new(2, 'Invincible') + Song.new(1, "The Answer Is Still No"), + Song.new(2, "Invincible") ] _(songs.object_id).must_equal album.songs.object_id @@ -227,11 +227,11 @@ def from_hash(hash, *_args) end # not sure if this must be a library strategy - describe 'replace existing element' do + describe "replace existing element" do representer!(inject: :song_representer) do collection :songs, - instance: lambda { |options| - id = options[:fragment].delete('replace_id') + instance: ->(options) { + id = options[:fragment].delete("replace_id") replaced = songs.find { |s| s.id == id } songs[songs.index(replaced)] = song = Song.new(3) song @@ -245,19 +245,19 @@ def from_hash(hash, *_args) it { album = Struct.new(:songs).new( songs = [ - Song.new(1, 'The Answer Is Still No'), - Song.new(2, 'Invincible') + Song.new(1, "The Answer Is Still No"), + Song.new(2, "Invincible") ] ) _( album .extend(representer) - .from_hash('songs' => [{ 'replace_id' => 2, 'id' => 3, 'title' => 'Soulmate' }]) + .from_hash("songs" => [{"replace_id" => 2, "id" => 3, "title" => "Soulmate"}]) .songs ).must_equal [ - Song.new(1, 'The Answer Is Still No'), - Song.new(3, 'Soulmate') + Song.new(1, "The Answer Is Still No"), + Song.new(3, "Soulmate") ] _(songs.object_id).must_equal album.songs.object_id @@ -265,7 +265,7 @@ def from_hash(hash, *_args) } end - describe 'replace collection' do + describe "replace collection" do representer!(inject: :song_representer) do collection :songs, extend: song_representer, class: Song @@ -274,17 +274,17 @@ def from_hash(hash, *_args) it { album = Struct.new(:songs).new( songs = [ - Song.new(1, 'The Answer Is Still No') + Song.new(1, "The Answer Is Still No") ] ) _( album .extend(representer) - .from_hash('songs' => [{ 'title' => 'Invincible' }]) + .from_hash("songs" => [{"title" => "Invincible"}]) .songs ).must_equal [ - Song.new(nil, 'Invincible') + Song.new(nil, "Invincible") ] _(songs.object_id).wont_equal album.songs.object_id diff --git a/test/is_representable_test.rb b/test/is_representable_test.rb index 68f47977..275a2233 100644 --- a/test/is_representable_test.rb +++ b/test/is_representable_test.rb @@ -1,9 +1,9 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class IsRepresentableTest < BaseTest - describe 'representable: false, extend:' do + describe "representable: false, extend:" do representer!(inject: :song_representer) do property :song, representable: false, @@ -14,12 +14,12 @@ class IsRepresentableTest < BaseTest _( Struct.new(:song).new(song = Object.new).extend(representer) .to_hash - ).must_equal('song' => song) + ).must_equal("song" => song) _(song).must_be_kind_of Representable::Hash end end - describe 'representable: true, no extend:' do + describe "representable: true, no extend:" do representer!(inject: :song_representer) do property :song, representable: true @@ -36,14 +36,14 @@ def to_hash(*) _( Struct.new(:song).new(song).extend(representer) .to_hash - ).must_equal('song' => 1) + ).must_equal("song" => 1) _(song).wont_be_kind_of Representable::Hash end end # TODO: TEST implement for from_hash. - describe 'representable: false, with class:' do + describe "representable: false, with class:" do representer!(inject: :song_representer) do property :song, representable: false, class: OpenStruct, extend: song_representer @@ -51,17 +51,17 @@ def to_hash(*) it "does extend but doesn't call #from_hash" do hit = Struct.new(:song).new.extend(representer) - .from_hash('song' => 1) + .from_hash("song" => 1) _(hit.song).must_equal OpenStruct.new _(hit.song).must_be_kind_of Representable::Hash end end - describe 'representable: true, without extend: but class:' do + describe "representable: true, without extend: but class:" do SongReader = Class.new do def from_hash(*) - 'Piano?' + "Piano?" end end @@ -72,9 +72,9 @@ def from_hash(*) it "doesn't extend but calls #from_hash" do hit = Struct.new(:song).new.extend(representer) - .from_hash('song' => 'Sonata No.2') + .from_hash("song" => "Sonata No.2") - _(hit.song).must_equal 'Piano?' + _(hit.song).must_equal "Piano?" _(hit.song).wont_be_kind_of Representable::Hash end end diff --git a/test/json_test.rb b/test/json_test.rb index ae46db39..e643e4f1 100644 --- a/test/json_test.rb +++ b/test/json_test.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'test_helper' -require 'json' +require "test_helper" +require "json" module JsonTest class JSONPublicMethodsTest < Minitest::Spec @@ -15,12 +15,12 @@ class BandRepresenter < Representable::Decorator let(:json) { '{"id":1,"name":"Rancid"}' } - it { _(BandRepresenter.new(Band.new).from_json(json)[:id, :name]).must_equal [1, 'Rancid'] } - it { _(BandRepresenter.new(Band.new).parse(json)[:id, :name]).must_equal [1, 'Rancid'] } + it { _(BandRepresenter.new(Band.new).from_json(json)[:id, :name]).must_equal [1, "Rancid"] } + it { _(BandRepresenter.new(Band.new).parse(json)[:id, :name]).must_equal [1, "Rancid"] } #--- # to_json - let(:band) { Band.new(1, 'Rancid') } + let(:band) { Band.new(1, "Rancid") } it { _(BandRepresenter.new(band).to_json).must_equal json } it { _(BandRepresenter.new(band).render).must_equal json } @@ -30,7 +30,7 @@ class APITest < MiniTest::Spec Json = Representable::JSON Def = Representable::Definition - describe 'JSON module' do + describe "JSON module" do before do @Band = Class.new do include Representable::JSON @@ -46,80 +46,86 @@ def initialize(name = nil) @band = @Band.new end - describe '#from_json' do + describe "#from_json" do before do @band = @Band.new - @json = { name: 'Nofx', label: 'NOFX' }.to_json + @json = {name: "Nofx", label: "NOFX"}.to_json end - it 'parses JSON and assigns properties' do + it "parses JSON and assigns properties" do @band.from_json(@json) + assert_equal %w[Nofx NOFX], [@band.name, @band.label] end end - describe '#from_hash' do + describe "#from_hash" do before do @band = @Band.new - @hash = { 'name' => 'Nofx', 'label' => 'NOFX' } + @hash = {"name" => "Nofx", "label" => "NOFX"} end - it 'receives hash and assigns properties' do + it "receives hash and assigns properties" do @band.from_hash(@hash) + assert_equal %w[Nofx NOFX], [@band.name, @band.label] end - it 'respects :wrap option' do - @band.from_hash({ 'band' => { 'name' => 'This Is A Standoff' } }, wrap: :band) - assert_equal 'This Is A Standoff', @band.name + it "respects :wrap option" do + @band.from_hash({"band" => {"name" => "This Is A Standoff"}}, wrap: :band) + + assert_equal "This Is A Standoff", @band.name end - it 'respects :wrap option over representation_wrap' do + it "respects :wrap option over representation_wrap" do @Band.class_eval do self.representation_wrap = :group end - @band.from_hash({ 'band' => { 'name' => 'This Is A Standoff' } }, wrap: :band) - assert_equal 'This Is A Standoff', @band.name + @band.from_hash({"band" => {"name" => "This Is A Standoff"}}, wrap: :band) + + assert_equal "This Is A Standoff", @band.name end end - describe '#to_json' do - it 'delegates to #to_hash and returns string' do - assert_json '{"name":"Rise Against"}', @Band.new('Rise Against').to_json + describe "#to_json" do + it "delegates to #to_hash and returns string" do + assert_json '{"name":"Rise Against"}', @Band.new("Rise Against").to_json end end - describe '#to_hash' do - it 'returns unwrapped hash' do - hash = @Band.new('Rise Against').to_hash - assert_equal({ 'name' => 'Rise Against' }, hash) + describe "#to_hash" do + it "returns unwrapped hash" do + hash = @Band.new("Rise Against").to_hash + + assert_equal({"name" => "Rise Against"}, hash) end - it 'respects :wrap option' do - assert_equal({ band: { 'name' => 'NOFX' } }, @Band.new('NOFX').to_hash(wrap: :band)) + it "respects :wrap option" do + assert_equal({band: {"name" => "NOFX"}}, @Band.new("NOFX").to_hash(wrap: :band)) end - it 'respects :wrap option over representation_wrap' do + it "respects :wrap option over representation_wrap" do @Band.class_eval do self.representation_wrap = :group end - assert_equal({ band: { 'name' => 'Rise Against' } }, @Band.new('Rise Against').to_hash(wrap: :band)) + + assert_equal({band: {"name" => "Rise Against"}}, @Band.new("Rise Against").to_hash(wrap: :band)) end end - describe '#build_for' do - it 'returns TextBinding' do + describe "#build_for" do + it "returns TextBinding" do assert_kind_of Representable::Hash::Binding, Representable::Hash::Binding.build_for(Def.new(:band)) end - it 'returns CollectionBinding' do + it "returns CollectionBinding" do assert_kind_of Representable::Hash::Binding::Collection, Representable::Hash::Binding.build_for(Def.new(:band, collection: true)) end end end - describe 'DCI' do + describe "DCI" do module SongRepresenter include Representable::JSON property :name @@ -131,7 +137,7 @@ module AlbumRepresenter collection :songs, class: Song, extend: SongRepresenter end - it 'allows adding the representer by using #extend' do + it "allows adding the representer by using #extend" do module BandRepresenter include Representable::JSON property :name @@ -139,7 +145,7 @@ module BandRepresenter civ = Object.new civ.instance_eval do - def name = 'CIV' + def name; "CIV"; end def name=(v) @name = v @@ -147,50 +153,53 @@ def name=(v) end civ.extend(BandRepresenter) + assert_json '{"name":"CIV"}', civ.to_json end - it 'extends contained models when serializing' do - @album = Album.new([Song.new('I Hate My Brain'), mr = Song.new('Mr. Charisma')], mr) + it "extends contained models when serializing" do + @album = Album.new([Song.new("I Hate My Brain"), mr = Song.new("Mr. Charisma")], mr) @album.extend(AlbumRepresenter) assert_json '{"best_song":{"name":"Mr. Charisma"},"songs":[{"name":"I Hate My Brain"},{"name":"Mr. Charisma"}]}', @album.to_json end - it 'extends contained models when deserializing' do + it "extends contained models when deserializing" do # @album = Album.new(Song.new("I Hate My Brain"), Song.new("Mr. Charisma")) @album = Album.new @album.extend(AlbumRepresenter) @album.from_json('{"best_song":{"name":"Mr. Charisma"},"songs":[{"name":"I Hate My Brain"},{"name":"Mr. Charisma"}]}') - assert_equal 'Mr. Charisma', @album.best_song.name + + assert_equal "Mr. Charisma", @album.best_song.name end end end class PropertyTest < MiniTest::Spec - describe 'property :name' do + describe "property :name" do class Band include Representable::JSON property :name attr_accessor :name end - it '#from_json creates correct accessors' do - band = Band.new.from_json({ name: 'Bombshell Rocks' }.to_json) - assert_equal 'Bombshell Rocks', band.name + it "#from_json creates correct accessors" do + band = Band.new.from_json({name: "Bombshell Rocks"}.to_json) + + assert_equal "Bombshell Rocks", band.name end - it '#to_json serializes correctly' do + it "#to_json serializes correctly" do band = Band.new - band.name = 'Cigar' + band.name = "Cigar" assert_json '{"name":"Cigar"}', band.to_json end end - describe ':class => Item' do + describe ":class => Item" do class Label include Representable::JSON property :name @@ -203,21 +212,22 @@ class Album attr_accessor :label end - it '#from_json creates one Item instance' do + it "#from_json creates one Item instance" do album = Album.new.from_json('{"label":{"name":"Fat Wreck"}}') - assert_equal 'Fat Wreck', album.label.name + + assert_equal "Fat Wreck", album.label.name end - it '#to_json serializes' do + it "#to_json serializes" do label = Label.new - label.name = 'Fat Wreck' + label.name = "Fat Wreck" album = Album.new album.label = label assert_json '{"label":{"name":"Fat Wreck"}}', album.to_json end - describe ':different_name, :class => Label' do + describe ":different_name, :class => Label" do before do @Album = Class.new do include Representable::JSON @@ -226,9 +236,9 @@ class Album end end - it '#to_xml respects the different name' do + it "#to_xml respects the different name" do label = Label.new - label.name = 'Fat Wreck' + label.name = "Fat Wreck" album = @Album.new album.seller = label @@ -237,54 +247,57 @@ class Album end end - describe ':as => :songName' do + describe ":as => :songName" do class Song include Representable::JSON property :name, as: :songName attr_accessor :name end - it 'respects :as in #from_json' do - song = Song.new.from_json({ songName: 'Run To The Hills' }.to_json) - assert_equal 'Run To The Hills', song.name + it "respects :as in #from_json" do + song = Song.new.from_json({songName: "Run To The Hills"}.to_json) + + assert_equal "Run To The Hills", song.name end - it 'respects :as in #to_json' do + it "respects :as in #to_json" do song = Song.new - song.name = '22 Acacia Avenue' + song.name = "22 Acacia Avenue" + assert_json '{"songName":"22 Acacia Avenue"}', song.to_json end end end class CollectionTest < MiniTest::Spec - describe 'collection :name' do + describe "collection :name" do class CD include Representable::JSON collection :songs attr_accessor :songs end - it '#from_json creates correct accessors' do - cd = CD.new.from_json({ songs: ['Out in the cold', 'Microphone'] }.to_json) - assert_equal ['Out in the cold', 'Microphone'], cd.songs + it "#from_json creates correct accessors" do + cd = CD.new.from_json({songs: ["Out in the cold", "Microphone"]}.to_json) + + assert_equal ["Out in the cold", "Microphone"], cd.songs end - it 'zzz#to_json serializes correctly' do + it "zzz#to_json serializes correctly" do cd = CD.new - cd.songs = ['Out in the cold', 'Microphone'] + cd.songs = ["Out in the cold", "Microphone"] assert_json '{"songs":["Out in the cold","Microphone"]}', cd.to_json end end - describe 'collection :name, :class => Band' do + describe "collection :name, :class => Band" do class Band include Representable::JSON property :name attr_accessor :name - def initialize(name = '') + def initialize(name = "") self.name = name end end @@ -295,43 +308,45 @@ class Compilation attr_accessor :bands end - describe '#from_json' do - it 'pushes collection items to array' do + describe "#from_json" do + it "pushes collection items to array" do cd = Compilation.new.from_json( { bands: [ - { name: 'Cobra Skulls' }, - { name: 'Diesel Boy' } + {name: "Cobra Skulls"}, + {name: "Diesel Boy"} ] }.to_json ) - assert_equal ['Cobra Skulls', 'Diesel Boy'], cd.bands.map(&:name).sort + + assert_equal ["Cobra Skulls", "Diesel Boy"], cd.bands.map(&:name).sort end end - it 'responds to #to_json' do + it "responds to #to_json" do cd = Compilation.new - cd.bands = [Band.new('Diesel Boy'), Band.new('Bad Religion')] + cd.bands = [Band.new("Diesel Boy"), Band.new("Bad Religion")] assert_json '{"bands":[{"name":"Diesel Boy"},{"name":"Bad Religion"}]}', cd.to_json end end - describe ':as => :songList' do + describe ":as => :songList" do class Songs include Representable::JSON collection :tracks, as: :songList attr_accessor :tracks end - it 'respects :as in #from_json' do - songs = Songs.new.from_json({ songList: ['Out in the cold', 'Microphone'] }.to_json) - assert_equal ['Out in the cold', 'Microphone'], songs.tracks + it "respects :as in #from_json" do + songs = Songs.new.from_json({songList: ["Out in the cold", "Microphone"]}.to_json) + + assert_equal ["Out in the cold", "Microphone"], songs.tracks end - it 'respects option in #to_json' do + it "respects option in #to_json" do songs = Songs.new - songs.tracks = ['Out in the cold', 'Microphone'] + songs.tracks = ["Out in the cold", "Microphone"] assert_json '{"songList":["Out in the cold","Microphone"]}', songs.to_json end @@ -339,27 +354,28 @@ class Songs end class HashTest < MiniTest::Spec - describe 'hash :songs' do + describe "hash :songs" do representer!(module: Representable::JSON) do hash :songs end subject { OpenStruct.new.extend(representer) } - it 'renders with #to_json' do - subject.songs = { one: '65', two: 'Emo Boy' } + it "renders with #to_json" do + subject.songs = {one: "65", two: "Emo Boy"} + assert_json '{"songs":{"one":"65","two":"Emo Boy"}}', subject.to_json end - it 'parses with #from_json' do + it "parses with #from_json" do assert_equal( - { 'one' => '65', 'two' => ['Emo Boy'] }, + {"one" => "65", "two" => ["Emo Boy"]}, subject.from_json('{"songs":{"one":"65","two":["Emo Boy"]}}').songs ) end end - describe 'hash :songs, :class => Song' do + describe "hash :songs, :class => Song" do representer!(module: Representable::JSON) do hash :songs, extend: Module.new { include Representable::JSON @@ -367,20 +383,20 @@ class HashTest < MiniTest::Spec }, class: Song end - it 'renders' do - _(OpenStruct.new(songs: { '7' => Song.new('Contemplation') }).extend(representer).to_hash).must_equal('songs' => { '7' => { 'name' => 'Contemplation' } }) + it "renders" do + _(OpenStruct.new(songs: {"7" => Song.new("Contemplation")}).extend(representer).to_hash).must_equal("songs" => {"7" => {"name" => "Contemplation"}}) end - describe 'parsing' do + describe "parsing" do subject { OpenStruct.new.extend(representer) } - let(:hsh) { { '7' => { 'name' => 'Contemplation' } } } + let(:hsh) { {"7" => {"name" => "Contemplation"}} } - it 'parses incoming hash' do - _(subject.from_hash('songs' => hsh).songs).must_equal({ '7' => Song.new('Contemplation') }) + it "parses incoming hash" do + _(subject.from_hash("songs" => hsh).songs).must_equal({"7" => Song.new("Contemplation")}) end it "doesn't modify the incoming hash" do - subject.from_hash('songs' => incoming_hash = hsh.dup) + subject.from_hash("songs" => incoming_hash = hsh.dup) _(hsh).must_equal incoming_hash end end diff --git a/test/lonely_test.rb b/test/lonely_test.rb index 92aeb3ae..105806fb 100644 --- a/test/lonely_test.rb +++ b/test/lonely_test.rb @@ -1,17 +1,17 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" -require 'representable/json/hash' +require "representable/json/hash" class LonelyRepresenterTest < MiniTest::Spec # test ::items without arguments, render-only. for_formats( - hash: [Representable::Hash::Collection, [{ 'name' => 'Resist Stance' }, { 'name' => 'Suffer' }]], + hash: [Representable::Hash::Collection, [{"name" => "Resist Stance"}, {"name" => "Suffer"}]], json: [Representable::JSON::Collection, '[{"name":"Resist Stance"},{"name":"Suffer"}]'], xml: [ Representable::XML::Collection, - 'Resist StanceSuffer' + "Resist StanceSuffer" ] ) do |format, mod, output, _input| describe "[#{format}] lonely collection, render-only" do # TODO: introduce :representable option? @@ -23,9 +23,9 @@ class LonelyRepresenterTest < MiniTest::Spec end end - let(:album) { [Song.new('Resist Stance'), Song.new('Suffer')].extend(representer) } + let(:album) { [Song.new("Resist Stance"), Song.new("Suffer")].extend(representer) } - it 'calls #to_hash on song instances, nothing else' do + it "calls #to_hash on song instances, nothing else" do assert_equal_document(render(album), output) end end @@ -45,11 +45,11 @@ module SongRepresenter end end - describe 'JSON::Collection' do - let(:songs) { [Song.new('Days Go By'), Song.new("Can't Take Them All")] } + describe "JSON::Collection" do + let(:songs) { [Song.new("Days Go By"), Song.new("Can't Take Them All")] } let(:json) { "[{\"name\":\"Days Go By\"},{\"name\":\"Can't Take Them All\"}]" } - describe 'with contained objects' do + describe "with contained objects" do let(:representer) do Module.new do include Representable::JSON::Collection @@ -57,24 +57,24 @@ module SongRepresenter end end - it 'renders array' do + it "renders array" do assert_json json, songs.extend(representer).to_json end - it 'renders array with decorator' do + it "renders array with decorator" do assert_json json, decorator.new(songs).to_json end - it 'parses array' do + it "parses array" do _([].extend(representer).from_json(json)).must_equal songs end - it 'parses array with decorator' do + it "parses array with decorator" do _(decorator.new([]).from_json(json)).must_equal songs end end - describe 'with inline representer' do + describe "with inline representer" do representer!(module: Representable::JSON::Collection) do items class: Song do property :name @@ -85,43 +85,43 @@ module SongRepresenter it { _([].extend(representer).from_json(json)).must_equal songs } end - describe 'with contained text' do + describe "with contained text" do let(:representer) do Module.new do include Representable::JSON::Collection end end - let(:songs) { ['Days Go By', "Can't Take Them All"] } + let(:songs) { ["Days Go By", "Can't Take Them All"] } let(:json) { "[\"Days Go By\",\"Can't Take Them All\"]" } - it 'renders contained items #to_json' do + it "renders contained items #to_json" do assert_json json, songs.extend(representer).to_json end - it 'returns objects array from #from_json' do + it "returns objects array from #from_json" do _([].extend(representer).from_json(json)).must_equal songs end end end - describe 'Hash::Collection with dynamic options' do + describe "Hash::Collection with dynamic options" do class One < Representable::Decorator - def to_hash(*) = "One: #{represented}" + def to_hash(*); "One: #{represented}"; end end class Two < Representable::Decorator - def to_hash(*) = "Two: #{represented}" + def to_hash(*); "Two: #{represented}"; end end representer!(module: Representable::Hash::Collection) do items extend: ->(options) { options[:input] == 1 ? options[:user_options][:one] : options[:user_options][:two] } end - it { _([1, 2].extend(representer).to_hash(user_options: { one: One, two: Two })).must_equal(['One: 1', 'Two: 2']) } + it { _([1, 2].extend(representer).to_hash(user_options: {one: One, two: Two})).must_equal(["One: 1", "Two: 2"]) } end - describe 'JSON::Hash' do # TODO: move to HashTest. - describe 'with contained objects' do + describe "JSON::Hash" do # TODO: move to HashTest. + describe "with contained objects" do let(:representer) do Module.new do include Representable::JSON::Hash @@ -129,54 +129,56 @@ def to_hash(*) = "Two: #{represented}" end end let(:json) { "{\"one\":{\"name\":\"Days Go By\"},\"two\":{\"name\":\"Can't Take Them All\"}}" } - let(:songs) { { 'one' => Song.new('Days Go By'), 'two' => Song.new("Can't Take Them All") } } + let(:songs) { {"one" => Song.new("Days Go By"), "two" => Song.new("Can't Take Them All")} } - describe '#to_json' do - it 'renders hash' do + describe "#to_json" do + it "renders hash" do _(songs.extend(representer).to_json).must_equal json end - it 'renders hash with decorator' do + it "renders hash with decorator" do _(decorator.new(songs).to_json).must_equal json end - it 'respects :exclude' do + it "respects :exclude" do assert_json "{\"two\":{\"name\":\"Can't Take Them All\"}}", { - one: Song.new('Days Go By'), + one: Song.new("Days Go By"), two: Song.new("Can't Take Them All") }.extend(representer).to_json(exclude: [:one]) end - it 'respects :include' do + it "respects :include" do assert_json "{\"two\":{\"name\":\"Can't Take Them All\"}}", { - one: Song.new('Days Go By'), + one: Song.new("Days Go By"), two: Song.new("Can't Take Them All") }.extend(representer).to_json(include: [:two]) end end - describe '#from_json' do - it 'returns objects array' do + describe "#from_json" do + it "returns objects array" do _({}.extend(representer).from_json(json)).must_equal songs end - it 'parses hash with decorator' do + it "parses hash with decorator" do _(decorator.new({}).from_json(json)).must_equal songs end - it 'respects :exclude' do - assert_equal({ 'two' => Song.new("Can't Take Them All") }, - {}.extend(representer).from_json(json, exclude: [:one])) + it "respects :exclude" do + assert_equal( + {"two" => Song.new("Can't Take Them All")}, + {}.extend(representer).from_json(json, exclude: [:one]) + ) end - it 'respects :include' do - assert_equal({ 'one' => Song.new('Days Go By') }, {}.extend(representer).from_json(json, include: [:one])) + it "respects :include" do + assert_equal({"one" => Song.new("Days Go By")}, {}.extend(representer).from_json(json, include: [:one])) end end - describe 'with inline representer' do + describe "with inline representer" do representer!(module: Representable::JSON::Hash) do values class: Song do property :name @@ -188,16 +190,16 @@ def to_hash(*) = "Two: #{represented}" end end - describe 'with scalar' do + describe "with scalar" do let(:representer) do Module.new do include Representable::JSON::Hash end end let(:json) { %({"one":1,"two":2}) } - let(:data) { { one: 2, two: 3 } } + let(:data) { {one: 2, two: 3} } - describe '#to_json' do + describe "#to_json" do it { _(data.extend(representer).to_json).must_equal %({"one":2,"two":3}) } # it "respects :exclude" do @@ -209,25 +211,25 @@ def to_hash(*) = "Two: #{represented}" # end end - describe '#from_json' do # FIXME: what's the point of this? + describe "#from_json" do # FIXME: what's the point of this? it { _(data.extend(representer).from_hash(data)).must_equal data } end end - describe 'with contained text' do + describe "with contained text" do before do @songs_representer = Module.new do include Representable::JSON::Collection end end - it 'renders contained items #to_json' do + it "renders contained items #to_json" do assert_json "[\"Days Go By\",\"Can't Take Them All\"]", - ['Days Go By', "Can't Take Them All"].extend(@songs_representer).to_json + ["Days Go By", "Can't Take Them All"].extend(@songs_representer).to_json end - it 'returns objects array from #from_json' do - assert_equal ['Days Go By', "Can't Take Them All"], + it "returns objects array from #from_json" do + assert_equal ["Days Go By", "Can't Take Them All"], [].extend(@songs_representer).from_json("[\"Days Go By\",\"Can't Take Them All\"]") end end @@ -245,6 +247,6 @@ class CollectionWithIncludeTest < MiniTest::Spec end end - it { _(representer.new([Song.new(1, 'ACAB')]).to_hash).must_equal([{ 'id' => 1, 'title' => 'ACAB' }]) } - it { _(representer.new([Song.new(1, 'ACAB')]).to_hash(include: [:title])).must_equal([{ 'title' => 'ACAB' }]) } + it { _(representer.new([Song.new(1, "ACAB")]).to_hash).must_equal([{"id" => 1, "title" => "ACAB"}]) } + it { _(representer.new([Song.new(1, "ACAB")]).to_hash(include: [:title])).must_equal([{"title" => "ACAB"}]) } end diff --git a/test/nested_test.rb b/test/nested_test.rb index cc621045..a16ea81f 100644 --- a/test/nested_test.rb +++ b/test/nested_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class NestedTest < MiniTest::Spec Album = Struct.new(:label, :owner, :amount) @@ -8,11 +8,13 @@ class NestedTest < MiniTest::Spec for_formats( hash: [ Representable::Hash, - { 'label' => { 'label' => 'Epitaph', 'owner' => 'Brett Gurewitz', 'releases' => { 'amount' => 19 } } } + {"label" => {"label" => "Epitaph", "owner" => "Brett Gurewitz", "releases" => {"amount" => 19}}} ], # :xml => [Representable::XML, ""], - yaml: [Representable::YAML, - "---\nlabel:\n label: Epitaph\n owner: Brett Gurewitz\n releases:\n amount: 19\n"] + yaml: [ + Representable::YAML, + "---\nlabel:\n label: Epitaph\n owner: Brett Gurewitz\n releases:\n amount: 19\n" + ] ) do |format, mod, output, _input| [false, true].each do |is_decorator| describe "::nested with (inline representer|decorator): #{is_decorator}" do @@ -32,25 +34,25 @@ class NestedTest < MiniTest::Spec # self.representation_wrap = :album if format == :xml end - let(:album) { Album.new('Epitaph', 'Brett Gurewitz', 19) } + let(:album) { Album.new("Epitaph", "Brett Gurewitz", 19) } let(:decorator) { representer.prepare(album) } - it 'renders nested Album-properties in separate section' do + it "renders nested Album-properties in separate section" do assert_equal_document(render(decorator), output) # do not use extend on the nested object. # FIXME: make this a proper test with two describes instead of this pseudo-meta stuff. _(album).wont_be_kind_of(Representable::Hash) if is_decorator == true end - it 'parses nested properties to Album instance' do + it "parses nested properties to Album instance" do album = parse(representer.prepare(Album.new), output) - _(album.label).must_equal 'Epitaph' - _(album.owner).must_equal 'Brett Gurewitz' + _(album.label).must_equal "Epitaph" + _(album.owner).must_equal "Brett Gurewitz" end end end - describe 'Decorator ::nested with extend:' do + describe "Decorator ::nested with extend:" do let(:format) { format } representer!(name: :label_rpr) do @@ -69,23 +71,23 @@ class NestedTest < MiniTest::Spec self.representation_wrap = :album if format == :xml end - let(:album) { representer.prepare(Album.new('Epitaph', 'Brett Gurewitz', 19)) } + let(:album) { representer.prepare(Album.new("Epitaph", "Brett Gurewitz", 19)) } # TODO: shared example with above. - it 'renders nested Album-properties in separate section' do + it "renders nested Album-properties in separate section" do assert_equal_document(render(album), output) end - it 'parses nested properties to Album instance' do + it "parses nested properties to Album instance" do album = parse(representer.prepare(Album.new), output) - _(album.label).must_equal 'Epitaph' - _(album.owner).must_equal 'Brett Gurewitz' + _(album.label).must_equal "Epitaph" + _(album.owner).must_equal "Brett Gurewitz" _(album.amount).must_equal 19 end end end - describe '::nested without block but with inherit:' do + describe "::nested without block but with inherit:" do representer!(name: :parent) do include Representable::Hash @@ -96,13 +98,13 @@ class NestedTest < MiniTest::Spec representer!(module: Representable::Hash, inject: :parent) do include parent - nested :label, inherit: true, as: 'Label' + nested :label, inherit: true, as: "Label" end - let(:album) { representer.prepare(Album.new('Epitaph', 'Brett Gurewitz', 19)) } + let(:album) { representer.prepare(Album.new("Epitaph", "Brett Gurewitz", 19)) } - it 'renders nested Album-properties in separate section' do - _(representer.prepare(album).to_hash).must_equal({ 'Label' => { 'owner' => 'Brett Gurewitz' } }) + it "renders nested Album-properties in separate section" do + _(representer.prepare(album).to_hash).must_equal({"Label" => {"owner" => "Brett Gurewitz"}}) end # it "parses nested properties to Album instance" do diff --git a/test/object_test.rb b/test/object_test.rb index 3c995211..a2555b36 100644 --- a/test/object_test.rb +++ b/test/object_test.rb @@ -1,5 +1,5 @@ -require 'test_helper' -require 'representable/object' +require "test_helper" +require "representable/object" class ObjectTest < MiniTest::Spec Song = Struct.new(:title, :album) @@ -8,13 +8,13 @@ class ObjectTest < MiniTest::Spec representer!(module: Representable::Object) do property :title - property :album, instance: lambda { |options| + property :album, instance: ->(options) { options[:fragment].name.upcase! options[:fragment] } do property :name - collection :songs, instance: lambda { |options| + collection :songs, instance: ->(options) { options[:fragment].title.upcase! options[:fragment] } do @@ -24,37 +24,37 @@ class ObjectTest < MiniTest::Spec # TODO: collection end - let(:source) { Song.new('The King Is Dead', Album.new('Ruiner', [Song.new('In Vino Veritas II')])) } + let(:source) { Song.new("The King Is Dead", Album.new("Ruiner", [Song.new("In Vino Veritas II")])) } let(:target) { Song.new } it do representer.prepare(target).from_object(source) - _(target.title).must_equal 'The King Is Dead' - _(target.album.name).must_equal 'RUINER' - _(target.album.songs[0].title).must_equal 'IN VINO VERITAS II' + _(target.title).must_equal "The King Is Dead" + _(target.album.name).must_equal "RUINER" + _(target.album.songs[0].title).must_equal "IN VINO VERITAS II" end # ignore nested object when nil it do - representer.prepare(Song.new('The King Is Dead')).from_object(Song.new) + representer.prepare(Song.new("The King Is Dead")).from_object(Song.new) _(target.title).must_be_nil # scalar property gets overridden when nil. _(target.album).must_be_nil # nested property stays nil. end # to_object - describe '#to_object' do + describe "#to_object" do representer!(module: Representable::Object) do property :title - property :album, render_filter: lambda { |input, _options| - input.name = 'Live' + property :album, render_filter: ->(input, _options) { + input.name = "Live" input } do property :name - collection :songs, render_filter: lambda { |input, _options| + collection :songs, render_filter: ->(input, _options) { input[0].title = 1 input } do @@ -65,7 +65,7 @@ class ObjectTest < MiniTest::Spec it do representer.prepare(source).to_object - _(source.album.name).must_equal 'Live' + _(source.album.name).must_equal "Live" _(source.album.songs[0].title).must_equal 1 end end diff --git a/test/option_test.rb b/test/option_test.rb index 2ed9e4db..b34d55a9 100644 --- a/test/option_test.rb +++ b/test/option_test.rb @@ -1,36 +1,36 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class OptionTest < MiniTest::Spec class Callable include Uber::Callable - def call(*) = 'callable' + def call(*); "callable"; end end class MyRepresenter < Representable::Decorator include Representable::JSON - property :static, getter: 'static' + property :static, getter: "static" property :symbol, getter: :symbol - property :proc, getter: ->(*) { 'proc' } + property :proc, getter: ->(*) { "proc" } property :callable, getter: Callable.new end Album = Struct.new(:static) do - def symbol(*) = 'symbol' + def symbol(*); "symbol" end end let(:album_representer) { MyRepresenter.new(Album.new) } describe ::Representable::Option do - it 'supports all types of callables (method, proc, static etc)' do + it "supports all types of callables (method, proc, static etc)" do _(album_representer.to_hash).must_equal( { - 'static' => 'static', - 'symbol' => 'symbol', - 'proc' => 'proc', - 'callable' => 'callable' + "static" => "static", + "symbol" => "symbol", + "proc" => "proc", + "callable" => "callable" } ) end diff --git a/test/parse_pipeline_test.rb b/test/parse_pipeline_test.rb index 341cc544..02a0ce44 100644 --- a/test/parse_pipeline_test.rb +++ b/test/parse_pipeline_test.rb @@ -1,16 +1,16 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class ParsePipelineTest < MiniTest::Spec Album = Struct.new(:id, :artist, :songs) Artist = Struct.new(:email) Song = Struct.new(:title) - describe 'transforming nil to [] when parsing' do + describe "transforming nil to [] when parsing" do representer!(decorator: true) do collection :songs, - parse_pipeline: lambda { |*| + parse_pipeline: ->(*) { Representable::Pipeline.insert( parse_functions, # original function list from Binding#parse_functions. ->(input, _options) { input.nil? ? [] : input }, # your new function (can be any callable object).. @@ -23,13 +23,13 @@ class ParsePipelineTest < MiniTest::Spec end it do - representer.new(album = Album.new).from_hash('songs' => nil) + representer.new(album = Album.new).from_hash("songs" => nil) _(album.songs).must_equal [] end it do - representer.new(album = Album.new).from_hash('songs' => [{ 'title' => 'Business Conduct' }]) - _(album.songs).must_equal [Song.new('Business Conduct')] + representer.new(album = Album.new).from_hash("songs" => [{"title" => "Business Conduct"}]) + _(album.songs).must_equal [Song.new("Business Conduct")] end end @@ -41,7 +41,7 @@ class Representer < Representable::Decorator # property :email # end # DISCUSS: rename to populator_pipeline ? - collection :songs, parse_pipeline: lambda { |*| + collection :songs, parse_pipeline: ->(*) { [Collect[Instance, Prepare, Deserialize], Setter] }, instance: :instance!, exec_context: :decorator, pass_options: true do property :title @@ -57,14 +57,14 @@ def songs=(array) end it do - skip 'TODO: implement :parse_pipeline and :render_pipeline, and before/after/replace semantics' + skip "TODO: implement :parse_pipeline and :render_pipeline, and before/after/replace semantics" album = Album.new Representer.new(album).from_hash( { - 'artist' => { 'email' => 'yo' }, - 'songs' => [{ 'title' => 'Affliction' }, { 'title' => 'Dream Beater' }] + "artist" => {"email" => "yo"}, + "songs" => [{"title" => "Affliction"}, {"title" => "Dream Beater"}] } ) - _(album.songs).must_equal([Song.new('Affliction'), Song.new('Dream Beater')]) + _(album.songs).must_equal([Song.new("Affliction"), Song.new("Dream Beater")]) end end diff --git a/test/pipeline_test.rb b/test/pipeline_test.rb index 82128b12..59375919 100644 --- a/test/pipeline_test.rb +++ b/test/pipeline_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class PipelineTest < MiniTest::Spec Song = Struct.new(:title, :artist) @@ -10,9 +10,9 @@ class PipelineTest < MiniTest::Spec R = Representable P = R::Pipeline - Getter = ->(_input, _options) { 'Yo' } + Getter = ->(_input, _options) { "Yo" } StopOnNil = ->(input, _options) { input } - SkipRender = ->(input, *) { input == 'Yo' ? input : P::Stop } + SkipRender = ->(input, *) { input == "Yo" ? input : P::Stop } Prepare = ->(input, _options) { "Prepare(#{input})" } Deserialize = ->(input, options) { "Deserialize(#{input}, #{options[:fragment]})" } @@ -24,42 +24,42 @@ class PipelineTest < MiniTest::Spec AssignFragment = ->(input, options) { options[:fragment] = input } - it 'linear' do - _(P[SkipParse, Setter].call('doc', { fragment: 1 })).must_equal 'Setter(doc)' + it "linear" do + _(P[SkipParse, Setter].call("doc", {fragment: 1})).must_equal "Setter(doc)" # parse style. - _(P[AssignFragment, SkipParse, CreateObject, Prepare].call('Bla', {})).must_equal 'Prepare(#)' + _(P[AssignFragment, SkipParse, CreateObject, Prepare].call("Bla", {})).must_equal "Prepare(#)" # render style. _(P[Getter, StopOnNil, SkipRender, Prepare, Setter].call(nil, {})) - .must_equal 'Setter(Prepare(Yo))' + .must_equal "Setter(Prepare(Yo))" # pipeline = Representable::Pipeline[SkipParse , SetResult, ModifyResult] # pipeline.(fragment: "yo!").must_equal "modified object from yo!" end - Stopping = lambda { |input, options| - return P::Stop if options[:fragment] == 'stop!' + Stopping = ->(input, options) { + return P::Stop if options[:fragment] == "stop!" input } - it 'stopping' do + it "stopping" do pipeline = Representable::Pipeline[SkipParse, Stopping, Prepare] - _(pipeline.call(nil, fragment: 'oy!')).must_equal 'Prepare()' - _(pipeline.call(nil, fragment: 'stop!')).must_equal Representable::Pipeline::Stop + _(pipeline.call(nil, fragment: "oy!")).must_equal "Prepare()" + _(pipeline.call(nil, fragment: "stop!")).must_equal Representable::Pipeline::Stop end - describe 'Collect' do + describe "Collect" do Reverse = ->(input, _options) { input.reverse } Add = ->(input, _options) { "#{input}+" } let(:pipeline) { R::Collect[Reverse, Add] } - it { _(pipeline.call(['yo!', 'oy!'], {})).must_equal ['!oy+', '!yo+'] } + it { _(pipeline.call(["yo!", "oy!"], {})).must_equal ["!oy+", "!yo+"] } - describe 'Pipeline with Collect' do + describe "Pipeline with Collect" do let(:pipeline) { P[Reverse, R::Collect[Reverse, Add]] } - it { _(pipeline.call(['yo!', 'oy!'], {})).must_equal ['!yo+', '!oy+'] } + it { _(pipeline.call(["yo!", "oy!"], {})).must_equal ["!yo+", "!oy+"] } end end @@ -71,7 +71,7 @@ class PipelineTest < MiniTest::Spec R::Hash::Binding.new(dfn) end - it 'rendering scalar property' do + it "rendering scalar property" do doc = {} _( P[ @@ -79,13 +79,13 @@ class PipelineTest < MiniTest::Spec R::StopOnSkipable, R::AssignName, R::WriteFragment - ].call(nil, { represented: Song.new('Lime Green'), binding: title, doc: doc }) - ).must_equal 'Lime Green' + ].call(nil, {represented: Song.new("Lime Green"), binding: title, doc: doc}) + ).must_equal "Lime Green" - _(doc).must_equal({ 'title' => 'Lime Green' }) + _(doc).must_equal({"title" => "Lime Green"}) end - it 'parsing scalar property' do + it "parsing scalar property" do _( P[ R::AssignName, @@ -94,12 +94,12 @@ class PipelineTest < MiniTest::Spec R::OverwriteOnNil, # R::SkipParse, R::SetValue, - ].extend(P::Debug).call(doc = { 'title' => 'Eruption' }, { - represented: song = Song.new('Lime Green'), binding: title, + ].extend(P::Debug).call(doc = {"title" => "Eruption"}, { + represented: song = Song.new("Lime Green"), binding: title, doc: doc }) - ).must_equal 'Eruption' - _(song.title).must_equal 'Eruption' + ).must_equal "Eruption" + _(song.title).must_equal "Eruption" end module ArtistRepresenter @@ -113,9 +113,9 @@ module ArtistRepresenter R::Hash::Binding.new(dfn) end - let(:song_model) { Song.new('Lime Green', Artist.new('Diesel Boy')) } + let(:song_model) { Song.new("Lime Green", Artist.new("Diesel Boy")) } - it 'rendering typed property' do + it "rendering typed property" do doc = {} _( P[ @@ -130,12 +130,12 @@ module ArtistRepresenter represented: song_model, binding: artist, doc: doc, options: {} }) - ).must_equal({ 'name' => 'Diesel Boy' }) + ).must_equal({"name" => "Diesel Boy"}) - _(doc).must_equal({ 'artist' => { 'name' => 'Diesel Boy' } }) + _(doc).must_equal({"artist" => {"name" => "Diesel Boy"}}) end - it 'parsing typed property' do + it "parsing typed property" do _( P[ R::AssignName, @@ -147,11 +147,11 @@ module ArtistRepresenter R::Decorate, R::Deserialize, R::SetValue, - ].extend(P::Debug).call(doc = { 'artist' => { 'name' => 'Doobie Brothers' } }, { + ].extend(P::Debug).call(doc = {"artist" => {"name" => "Doobie Brothers"}}, { represented: song_model, binding: artist, doc: doc, options: {} }) - ).must_equal model = Artist.new('Doobie Brothers') + ).must_equal model = Artist.new("Doobie Brothers") _(song_model.artist).must_equal model end @@ -162,7 +162,7 @@ module ArtistRepresenter R::Hash::Binding::Collection.new(dfn) end - it 'render scalar collection' do + it "render scalar collection" do doc = {} _( P[ @@ -173,10 +173,10 @@ module ArtistRepresenter ], R::AssignName, R::WriteFragment - ].extend(P::Debug).call(nil, { represented: Album.new([1, 2, 3]), binding: ratings, doc: doc, options: {} }) + ].extend(P::Debug).call(nil, {represented: Album.new([1, 2, 3]), binding: ratings, doc: doc, options: {}}) ).must_equal([1, 2, 3]) - _(doc).must_equal({ 'ratings' => [1, 2, 3] }) + _(doc).must_equal({"ratings" => [1, 2, 3]}) end ######### collection :songs, extend: SongRepresenter @@ -185,7 +185,7 @@ module ArtistRepresenter R::Hash::Binding::Collection.new(dfn) end - it 'render typed collection' do + it "render typed collection" do doc = {} _( P[ @@ -198,18 +198,18 @@ module ArtistRepresenter R::AssignName, R::WriteFragment ].extend(P::Debug).call(nil, { - represented: Album.new(nil, [Artist.new('Diesel Boy'), Artist.new('Van Halen')]), binding: artists, + represented: Album.new(nil, [Artist.new("Diesel Boy"), Artist.new("Van Halen")]), binding: artists, doc: doc, options: {} }) - ).must_equal([{ 'name' => 'Diesel Boy' }, { 'name' => 'Van Halen' }]) + ).must_equal([{"name" => "Diesel Boy"}, {"name" => "Van Halen"}]) - _(doc).must_equal({ 'artists' => [{ 'name' => 'Diesel Boy' }, { 'name' => 'Van Halen' }] }) + _(doc).must_equal({"artists" => [{"name" => "Diesel Boy"}, {"name" => "Van Halen"}]}) end - let(:album_model) { Album.new(nil, [Artist.new('Diesel Boy'), Artist.new('Van Halen')]) } + let(:album_model) { Album.new(nil, [Artist.new("Diesel Boy"), Artist.new("Van Halen")]) } - it 'parse typed collection' do - doc = { 'artists' => [{ 'name' => 'Diesel Boy' }, { 'name' => 'Van Halen' }] } + it "parse typed collection" do + doc = {"artists" => [{"name" => "Diesel Boy"}, {"name" => "Van Halen"}]} _( P[ R::AssignName, @@ -228,78 +228,86 @@ module ArtistRepresenter represented: album_model, binding: artists, doc: doc, options: {} }) - ).must_equal([Artist.new('Diesel Boy'), Artist.new('Van Halen')]) + ).must_equal([Artist.new("Diesel Boy"), Artist.new("Van Halen")]) - _(album_model.artists).must_equal([Artist.new('Diesel Boy'), Artist.new('Van Halen')]) + _(album_model.artists).must_equal([Artist.new("Diesel Boy"), Artist.new("Van Halen")]) end # TODO: test with arrays, too, not "only" Pipeline instances. - describe '#Insert Pipeline[], Function, replace: OldFunction' do + describe "#Insert Pipeline[], Function, replace: OldFunction" do let(:pipeline) { P[R::GetValue, R::StopOnSkipable, R::StopOnNil] } - it 'returns Pipeline instance when passing in Pipeline instance' do + it "returns Pipeline instance when passing in Pipeline instance" do _(P::Insert.call(pipeline, R::Default, replace: R::StopOnSkipable)).must_be_instance_of(R::Pipeline) end - it 'replaces if exists' do + it "replaces if exists" do # pipeline.insert!(R::Default, replace: R::StopOnSkipable) - _(P::Insert.call(pipeline, R::Default, - replace: R::StopOnSkipable)).must_equal P[R::GetValue, R::Default, R::StopOnNil] + _( + P::Insert.call( + pipeline, R::Default, + replace: R::StopOnSkipable + ) + ).must_equal P[R::GetValue, R::Default, R::StopOnNil] _(pipeline).must_equal P[R::GetValue, R::StopOnSkipable, R::StopOnNil] end - it 'replaces Function instance' do + it "replaces Function instance" do pipeline = P[R::Prepare, R::StopOnSkipable, R::StopOnNil] - _(P::Insert.call(pipeline, R::Default, - replace: R::Prepare)).must_equal P[R::Default, R::StopOnSkipable, R::StopOnNil] + _( + P::Insert.call( + pipeline, R::Default, + replace: R::Prepare + ) + ).must_equal P[R::Default, R::StopOnSkipable, R::StopOnNil] _(pipeline).must_equal P[R::Prepare, R::StopOnSkipable, R::StopOnNil] end - it 'does not replace when not existing' do + it "does not replace when not existing" do P::Insert.call(pipeline, R::Default, replace: R::Prepare) _(pipeline).must_equal P[R::GetValue, R::StopOnSkipable, R::StopOnNil] end - it 'applies on nested Collect' do + it "applies on nested Collect" do pipeline = P[R::GetValue, R::Collect[R::GetValue, R::StopOnSkipable], R::StopOnNil] _( P::Insert.call(pipeline, R::Default, replace: R::StopOnSkipable).extend(P::Debug).inspect - ).must_equal 'Pipeline[GetValue, Collect[GetValue, Default], StopOnNil]' + ).must_equal "Pipeline[GetValue, Collect[GetValue, Default], StopOnNil]" _(pipeline).must_equal P[R::GetValue, R::Collect[R::GetValue, R::StopOnSkipable], R::StopOnNil] _( P::Insert.call(pipeline, R::Default, replace: R::StopOnNil).extend(P::Debug).inspect - ).must_equal 'Pipeline[GetValue, Collect[GetValue, StopOnSkipable], Default]' + ).must_equal "Pipeline[GetValue, Collect[GetValue, StopOnSkipable], Default]" end - it 'applies on nested Collect with Function::CreateObject' do + it "applies on nested Collect with Function::CreateObject" do pipeline = P[R::GetValue, R::Collect[R::GetValue, R::CreateObject], R::StopOnNil] _( P::Insert.call(pipeline, R::Default, replace: R::CreateObject).extend(P::Debug).inspect - ).must_equal 'Pipeline[GetValue, Collect[GetValue, Default], StopOnNil]' + ).must_equal "Pipeline[GetValue, Collect[GetValue, Default], StopOnNil]" _(pipeline).must_equal P[R::GetValue, R::Collect[R::GetValue, R::CreateObject], R::StopOnNil] end end - describe 'Insert.(delete: true)' do + describe "Insert.(delete: true)" do let(:pipeline) { P[R::GetValue, R::StopOnNil] } it do - _(P::Insert.call(pipeline, R::GetValue, delete: true).extend(P::Debug).inspect).must_equal 'Pipeline[StopOnNil]' - _(pipeline.extend(P::Debug).inspect).must_equal 'Pipeline[GetValue, StopOnNil]' + _(P::Insert.call(pipeline, R::GetValue, delete: true).extend(P::Debug).inspect).must_equal "Pipeline[StopOnNil]" + _(pipeline.extend(P::Debug).inspect).must_equal "Pipeline[GetValue, StopOnNil]" end end - describe 'Insert.(delete: true) with Collect' do + describe "Insert.(delete: true) with Collect" do let(:pipeline) { P[R::GetValue, R::Collect[R::GetValue, R::StopOnSkipable], R::StopOnNil] } it do _( P::Insert.call(pipeline, R::GetValue, delete: true).extend(P::Debug).inspect - ).must_equal 'Pipeline[Collect[StopOnSkipable], StopOnNil]' - _(pipeline.extend(P::Debug).inspect).must_equal 'Pipeline[GetValue, Collect[GetValue, StopOnSkipable], StopOnNil]' + ).must_equal "Pipeline[Collect[StopOnSkipable], StopOnNil]" + _(pipeline.extend(P::Debug).inspect).must_equal "Pipeline[GetValue, Collect[GetValue, StopOnSkipable], StopOnNil]" end end end diff --git a/test/populator_test.rb b/test/populator_test.rb index 3a67652c..eb58c2a6 100644 --- a/test/populator_test.rb +++ b/test/populator_test.rb @@ -1,15 +1,15 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class PopulatorTest < Minitest::Spec Song = Struct.new(:id) Artist = Struct.new(:name) Album = Struct.new(:songs, :artist) - describe 'populator: ->{}' do + describe "populator: ->{}" do representer! do - collection :songs, populator: lambda { |_input, options| + collection :songs, populator: ->(_input, options) { options[:represented].songs << song = Song.new song } do @@ -24,19 +24,19 @@ class PopulatorTest < Minitest::Spec let(:album) { Album.new([]) } it do - album.extend(representer).from_hash('songs' => [{ 'id' => 1 }, { 'id' => 2 }], 'artist' => { 'name' => 'Waste' }) + album.extend(representer).from_hash("songs" => [{"id" => 1}, {"id" => 2}], "artist" => {"name" => "Waste"}) _(album.inspect).must_equal '#, #], artist=#>' end end - describe 'populator: ->{}, ' do + describe "populator: ->{}, " do end end class PopulatorFindOrInstantiateTest < Minitest::Spec Song = Struct.new(:id, :title, :uid) do def self.find_by(attributes = {}) - return new(1, 'Resist Stan', 'abcd') if attributes[:id] == 1 # we should return the same object here + return new(1, "Resist Stan", "abcd") if attributes[:id] == 1 # we should return the same object here new end @@ -46,13 +46,13 @@ def self.find_by(attributes = {}) Composer.class_eval do def song=(v) @song = v - 'Absolute nonsense' # this tests that the populator always returns the correct object. + "Absolute nonsense" # this tests that the populator always returns the correct object. end attr_reader :song end - describe 'FindOrInstantiate with property' do + describe "FindOrInstantiate with property" do representer! do property :song, populator: Representable::FindOrInstantiate, class: Song do property :id @@ -62,24 +62,24 @@ def song=(v) let(:album) { Composer.new.extend(representer).extend(Representable::Debug) } - it 'finds by :id and creates new without :id' do - album.from_hash({ 'song' => { 'id' => 1, 'title' => 'Resist Stance' } }) + it "finds by :id and creates new without :id" do + album.from_hash({"song" => {"id" => 1, "title" => "Resist Stance"}}) - _(album.song.title).must_equal 'Resist Stance' # NOTE: how title is updated from "Resist Stan" + _(album.song.title).must_equal "Resist Stance" # NOTE: how title is updated from "Resist Stan" _(album.song.id).must_equal 1 - _(album.song.uid).must_equal 'abcd' # not changed via populator, indicating this is a formerly "persisted" object. + _(album.song.uid).must_equal "abcd" # not changed via populator, indicating this is a formerly "persisted" object. end - it 'creates new without :id' do - album.from_hash({ 'song' => { 'title' => 'Lower' } }) + it "creates new without :id" do + album.from_hash({"song" => {"title" => "Lower"}}) - _(album.song.title).must_equal 'Lower' + _(album.song.title).must_equal "Lower" _(album.song.id).must_be_nil _(album.song.uid).must_be_nil end end - describe 'FindOrInstantiate with collection' do + describe "FindOrInstantiate with collection" do representer! do collection :songs, populator: Representable::FindOrInstantiate, class: Song do property :id @@ -89,21 +89,21 @@ def song=(v) let(:album) { Struct.new(:songs).new([]).extend(representer) } - it 'finds by :id and creates new without :id' do + it "finds by :id and creates new without :id" do album.from_hash( { - 'songs' => [ - { 'id' => 1, 'title' => 'Resist Stance' }, - { 'title' => 'Suffer' } + "songs" => [ + {"id" => 1, "title" => "Resist Stance"}, + {"title" => "Suffer"} ] } ) - _(album.songs[0].title).must_equal 'Resist Stance' # NOTE: how title is updated from "Resist Stan" + _(album.songs[0].title).must_equal "Resist Stance" # NOTE: how title is updated from "Resist Stan" _(album.songs[0].id).must_equal 1 - _(album.songs[0].uid).must_equal 'abcd' # not changed via populator, indicating this is a formerly "persisted" object. + _(album.songs[0].uid).must_equal "abcd" # not changed via populator, indicating this is a formerly "persisted" object. - _(album.songs[1].title).must_equal 'Suffer' + _(album.songs[1].title).must_equal "Suffer" _(album.songs[1].id).must_be_nil _(album.songs[1].uid).must_be_nil end diff --git a/test/prepare_test.rb b/test/prepare_test.rb index c3bf08d8..e3acd9bb 100644 --- a/test/prepare_test.rb +++ b/test/prepare_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class PrepareTest < BaseTest class PreparerClass @@ -17,7 +17,7 @@ def ==(other) attr_reader :object end - describe '#to_hash' do # TODO: introduce :representable option? + describe "#to_hash" do # TODO: introduce :representable option? representer! do property :song, prepare: ->(options) { options[:binding][:arbitrary].new(options[:input]) }, @@ -28,9 +28,9 @@ def ==(other) let(:hit) { Struct.new(:song).new(song).extend(representer) } - it 'calls prepare:, nothing else' do + it "calls prepare:, nothing else" do # render(hit).must_equal_document(output) - _(hit.to_hash).must_equal({ 'song' => PreparerClass.new(song) }) + _(hit.to_hash).must_equal({"song" => PreparerClass.new(song)}) end # it "calls #from_hash on the existing song instance, nothing else" do @@ -43,24 +43,24 @@ def ==(other) # end end - describe '#from_hash' do + describe "#from_hash" do representer! do property :song, prepare: ->(options) { options[:binding][:arbitrary].new(options[:input]) }, arbitrary: PreparerClass, # :extend => true, # TODO: typed: true would be better. - instance: String.new, # pass_fragment + instance: +"", # pass_fragment pass_options: true, representable: false # don't call #to_hash. end let(:hit) { Struct.new(:song).new.extend(representer) } - it 'calls prepare:, nothing else' do + it "calls prepare:, nothing else" do # render(hit).must_equal_document(output) - hit.from_hash('song' => {}) + hit.from_hash("song" => {}) - _(hit.song).must_equal(PreparerClass.new(String.new)) + _(hit.song).must_equal(PreparerClass.new((+""))) end end end diff --git a/test/private_options_test.rb b/test/private_options_test.rb index c2b40b17..fd9d920d 100644 --- a/test/private_options_test.rb +++ b/test/private_options_test.rb @@ -1,21 +1,21 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" # TODO: move me to separate file. class PrivateOptionsTest < MiniTest::Spec representer!(decorator: true) do end - options = { exclude: 'name' } + options = {exclude: "name"} it "render: doesn't modify options" do representer.new(nil).to_hash(options) - _(options).must_equal({ exclude: 'name' }) + _(options).must_equal({exclude: "name"}) end it "parse: doesn't modify options" do representer.new(nil).from_hash(options) - _(options).must_equal({ exclude: 'name' }) + _(options).must_equal({exclude: "name"}) end end diff --git a/test/reader_writer_test.rb b/test/reader_writer_test.rb index 11b48b75..e9922087 100644 --- a/test/reader_writer_test.rb +++ b/test/reader_writer_test.rb @@ -1,21 +1,21 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class ReaderWriterTest < BaseTest representer! do property :name, - writer: ->(options) { options[:doc]['title'] = "#{options[:user_options][:nr]}) #{options[:input]}" }, - reader: ->(options) { self.name = options[:doc]['title'].split(') ').last } + writer: ->(options) { options[:doc]["title"] = "#{options[:user_options][:nr]}) #{options[:input]}" }, + reader: ->(options) { self.name = options[:doc]["title"].split(") ").last } end - subject { OpenStruct.new(name: 'Disorder And Disarray').extend(representer) } + subject { OpenStruct.new(name: "Disorder And Disarray").extend(representer) } - it 'uses :writer when rendering' do - _(subject.to_hash(user_options: { nr: 14 })).must_equal({ 'title' => '14) Disorder And Disarray' }) + it "uses :writer when rendering" do + _(subject.to_hash(user_options: {nr: 14})).must_equal({"title" => "14) Disorder And Disarray"}) end - it 'uses :reader when parsing' do - _(subject.from_hash({ 'title' => '15) The Wars End' }).name).must_equal 'The Wars End' + it "uses :reader when parsing" do + _(subject.from_hash({"title" => "15) The Wars End"}).name).must_equal "The Wars End" end end diff --git a/test/realistic_benchmark.rb b/test/realistic_benchmark.rb index 8094ec16..add9ce19 100644 --- a/test/realistic_benchmark.rb +++ b/test/realistic_benchmark.rb @@ -1,9 +1,9 @@ # frozen_string_literal: true -require 'test_helper' -require 'benchmark' +require "test_helper" +require "benchmark" -SONG_PROPERTIES = 50.times.collect do |i| +SONG_PROPERTIES = Array.new(50) do |i| "song_property_#{i}" end @@ -42,18 +42,18 @@ def random_song times = [] 3.times.each do - album = Album.new(100.times.collect { random_song }) + album = Album.new(Array.new(100) { random_song }) times << Benchmark.measure do - puts '================ next!' + puts "================ next!" AlbumRepresenter.new(album).to_json end end -puts times.join('') +puts times.join -album = Album.new(100.times.collect { random_song }) -require 'ruby-prof' +album = Album.new(Array.new(100) { random_song }) +require "ruby-prof" RubyProf.start AlbumRepresenter.new(album).to_hash res = RubyProf.stop diff --git a/test/render_nil_test.rb b/test/render_nil_test.rb index 2c9628b4..04a9695b 100644 --- a/test/render_nil_test.rb +++ b/test/render_nil_test.rb @@ -1,16 +1,16 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class RenderNilTest < MiniTest::Spec Song = Struct.new(:title) - describe 'render_nil: true' do + describe "render_nil: true" do representer! do property :title, render_nil: true end - it { _(Song.new.extend(representer).to_hash).must_equal({ 'title' => nil }) } + it { _(Song.new.extend(representer).to_hash).must_equal({"title" => nil}) } end describe "with :extend it shouldn't extend nil" do @@ -18,6 +18,6 @@ class RenderNilTest < MiniTest::Spec property :title, render_nil: true, extend: Class end - it { _(Song.new.extend(representer).to_hash).must_equal({ 'title' => nil }) } + it { _(Song.new.extend(representer).to_hash).must_equal({"title" => nil}) } end end diff --git a/test/represent_test.rb b/test/represent_test.rb index 55c0820e..4e489ac1 100644 --- a/test/represent_test.rb +++ b/test/represent_test.rb @@ -1,13 +1,13 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class RepresentTest < MiniTest::Spec let(:songs) { [song, Song.new("Can't Take Them All")] } - let(:song) { Song.new('Days Go By') } + let(:song) { Song.new("Days Go By") } for_formats( - hash: [Representable::Hash, out = [{ 'name' => 'Days Go By' }, { 'name' => "Can't Take Them All" }], out] + hash: [Representable::Hash, out = [{"name" => "Days Go By"}, {"name" => "Can't Take Them All"}], out] # :json => [Representable::JSON, out="[{\"name\":\"Days Go By\"},{\"name\":\"Can't Take Them All\"}]", out], # :xml => [Representable::XML, out="", out] ) do |format, mod, output, input| @@ -45,12 +45,12 @@ class RepresentTest < MiniTest::Spec it { assert_equal_document(render(representer.represent(songs)), output) } - it('ficken') { _(parse(representer.represent([]), input)).must_equal songs } + it("ficken") { _(parse(representer.represent([]), input)).must_equal songs } end end for_formats( - hash: [Representable::Hash, out = { 'name' => 'Days Go By' }, out], + hash: [Representable::Hash, out = {"name" => "Days Go By"}, out], json: [Representable::JSON, out = '{"name":"Days Go By"}', out] # :xml => [Representable::XML, out="", out] ) do |format, mod, output, input| diff --git a/test/representable_test.rb b/test/representable_test.rb index 0031797f..a1e2507b 100644 --- a/test/representable_test.rb +++ b/test/representable_test.rb @@ -1,4 +1,4 @@ -require 'test_helper' +require "test_helper" class RepresentableTest < MiniTest::Spec class Band @@ -25,17 +25,18 @@ module PunkBandRepresentation property :street_cred end - describe '#representable_attrs' do - describe 'in module' do - it 'allows including the concrete representer module later' do + describe "#representable_attrs" do + describe "in module" do + it "allows including the concrete representer module later" do vd = class VD attr_accessor :name, :street_cred include Representable::JSON include PunkBandRepresentation end.new - vd.name = 'Vention Dention' + vd.name = "Vention Dention" vd.street_cred = 1 + assert_json '{"name":"Vention Dention","street_cred":1}', vd.to_json end @@ -54,7 +55,7 @@ module PunkBandRepresentation end end - describe 'inheritance' do + describe "inheritance" do class CoverSong < OpenStruct end @@ -69,32 +70,33 @@ module CoverSongRepresenter property :by end - it 'merges properties from all ancestors' do - props = { 'name' => 'The Brews', 'by' => 'Nofx' } + it "merges properties from all ancestors" do + props = {"name" => "The Brews", "by" => "Nofx"} + assert_equal(props, CoverSong.new(props).extend(CoverSongRepresenter).to_hash) end - it 'allows mixing in multiple representers' do + it "allows mixing in multiple representers" do class Bodyjar include Representable::XML include Representable::JSON include PunkBandRepresentation - self.representation_wrap = 'band' + self.representation_wrap = "band" attr_accessor :name, :street_cred end band = Bodyjar.new - band.name = 'Bodyjar' + band.name = "Bodyjar" assert_json '{"band":{"name":"Bodyjar"}}', band.to_json - assert_xml_equal 'Bodyjar', band.to_xml + assert_xml_equal "Bodyjar", band.to_xml end - it 'allows extending with different representers subsequentially' do + it "allows extending with different representers subsequentially" do module SongXmlRepresenter include Representable::XML - property :name, as: 'name', attribute: true + property :name, as: "name", attribute: true end module SongJsonRepresenter @@ -102,7 +104,8 @@ module SongJsonRepresenter property :name end - @song = Song.new('Days Go By') + @song = Song.new("Days Go By") + assert_xml_equal '', @song.extend(SongXmlRepresenter).to_xml assert_json '{"name":"Days Go By"}', @song.extend(SongJsonRepresenter).to_json end @@ -119,7 +122,8 @@ class BaseClass def self.inherited(subclass) super subclass.instance_eval do - def other; end + def other + end end end @@ -140,7 +144,8 @@ class SubClass < BaseClass module DifferentIncluded def included(includer) includer.instance_eval do - def different; end + def different + end end end end @@ -162,7 +167,7 @@ class IncludingClass end end - describe '#property' do + describe "#property" do it "doesn't modify options hash" do options = {} representer.property(:title, options) @@ -171,24 +176,24 @@ class IncludingClass representer! {} - it 'returns the Definition instance' do + it "returns the Definition instance" do _(representer.property(:name)).must_be_kind_of Representable::Definition end end - describe '#collection' do + describe "#collection" do class RockBand < Band collection :albums end - it 'creates correct Definition' do - assert_equal 'albums', RockBand.representable_attrs.get(:albums).name - assert RockBand.representable_attrs.get(:albums).array? + it "creates correct Definition" do + assert_equal "albums", RockBand.representable_attrs.get(:albums).name + assert_predicate RockBand.representable_attrs.get(:albums), :array? end end - describe '#hash' do - it 'also responds to the original method' do + describe "#hash" do + it "also responds to the original method" do assert_kind_of Integer, BandRepresentation.hash end end @@ -211,51 +216,54 @@ class PopBand attr_accessor :name, :groupies, :hometown end - describe '#update_properties_from' do + describe "#update_properties_from" do before do @band = PopBand.new end - it 'copies values from document to object' do - @band.from_hash({ 'name' => "No One's Choice", 'groupies' => 2 }) + it "copies values from document to object" do + @band.from_hash({"name" => "No One's Choice", "groupies" => 2}) + assert_equal "No One's Choice", @band.name assert_equal 2, @band.groupies end - it 'ignores non-writeable properties' do - @band = Class.new(Band) do + it "ignores non-writeable properties" do + @band = Class.new(Band) { property :name collection :founders, writeable: false attr_accessor :founders - end.new - @band.from_hash('name' => 'Iron Maiden', 'groupies' => 2, 'founders' => ['Steve Harris']) - assert_equal 'Iron Maiden', @band.name + }.new + @band.from_hash("name" => "Iron Maiden", "groupies" => 2, "founders" => ["Steve Harris"]) + + assert_equal "Iron Maiden", @band.name assert_nil @band.founders end - it 'always returns the represented' do - assert_equal @band, @band.from_hash({ 'name' => 'Nofx' }) + it "always returns the represented" do + assert_equal @band, @band.from_hash({"name" => "Nofx"}) end - it 'includes false attributes' do - @band.from_hash({ 'groupies' => false }) + it "includes false attributes" do + @band.from_hash({"groupies" => false}) + refute @band.groupies end - it 'ignores properties not present in the incoming document' do + it "ignores properties not present in the incoming document" do @band.instance_eval do def name=(*) - raise 'I should never be called!' + fail "I should never be called!" end end @band.from_hash({}) end # FIXME: do we need this test with XML _and_ JSON? - it 'ignores (no-default) properties not present in the incoming document' do + it "ignores (no-default) properties not present in the incoming document" do { Representable::Hash => [:from_hash, {}], - Representable::XML => [:from_xml, xml(%()).to_s] + Representable::XML => [:from_xml, xml(%{}).to_s] }.each do |format, config| nested_repr = Module.new do # this module is never applied. # FIXME: can we make that a simpler test? include format @@ -269,11 +277,12 @@ def name=(*) @band = Band.new.extend(repr) @band.send(config.first, config.last) + assert_nil @band.name, "Failed in #{format}" end end - describe 'passing options' do + describe "passing options" do module TrackRepresenter include Representable::Hash end @@ -284,7 +293,7 @@ module TrackRepresenter property :length, class: OpenStruct do def to_hash(options) - { seconds: options[:user_options][:nr] } + {seconds: options[:user_options][:nr]} end def from_hash(hash, options) @@ -295,7 +304,7 @@ def from_hash(hash, options) end def to_hash(options) - super.merge({ 'nr' => options[:user_options][:nr] }) + super.merge({"nr" => options[:user_options][:nr]}) end def from_hash(data, options) @@ -306,7 +315,7 @@ def from_hash(data, options) end end - it '#to_hash propagates to nested objects' do + it "#to_hash propagates to nested objects" do _( OpenStruct.new( track: OpenStruct.new( @@ -314,13 +323,13 @@ def from_hash(data, options) length: OpenStruct.new(seconds: nil) ) ).extend(representer).extend(Representable::Debug) - .to_hash(user_options: { nr: 9 }) - ).must_equal({ 'track' => { 'nr' => 9, 'length' => { seconds: 9 } } }) + .to_hash(user_options: {nr: 9}) + ).must_equal({"track" => {"nr" => 9, "length" => {seconds: 9}}}) end - it '#from_hash propagates to nested objects' do + it "#from_hash propagates to nested objects" do song = OpenStruct.new.extend(representer).from_hash( - { 'track' => { 'nr' => 'replace me', 'length' => { 'seconds' => 'replacing' } } }, user_options: { nr: 9 } + {"track" => {"nr" => "replace me", "length" => {"seconds" => "replacing"}}}, user_options: {nr: 9} ) _(song.track.nr).must_equal 9 _(song.track.length.seconds).must_equal 9 @@ -328,42 +337,45 @@ def from_hash(data, options) end end - describe '#create_representation_with' do + describe "#create_representation_with" do before do @band = PopBand.new @band.name = "No One's Choice" @band.groupies = 2 end - it 'compiles document from properties in object' do - assert_equal({ 'name' => "No One's Choice", 'groupies' => 2 }, @band.to_hash) + it "compiles document from properties in object" do + assert_equal({"name" => "No One's Choice", "groupies" => 2}, @band.to_hash) end - it 'ignores non-readable properties' do - @band = Class.new(Band) do + it "ignores non-readable properties" do + @band = Class.new(Band) { property :name collection :founder_ids, readable: false attr_accessor :founder_ids - end.new - @band.name = 'Iron Maiden' + }.new + @band.name = "Iron Maiden" @band.founder_ids = [1, 2, 3] hash = @band.to_hash - assert_equal({ 'name' => 'Iron Maiden' }, hash) + + assert_equal({"name" => "Iron Maiden"}, hash) end - it 'does not write nil attributes' do + it "does not write nil attributes" do @band.groupies = nil - assert_equal({ 'name' => "No One's Choice" }, @band.to_hash) + + assert_equal({"name" => "No One's Choice"}, @band.to_hash) end - it 'writes false attributes' do + it "writes false attributes" do @band.groupies = false - assert_equal({ 'name' => "No One's Choice", 'groupies' => false }, @band.to_hash) + + assert_equal({"name" => "No One's Choice", "groupies" => false}, @band.to_hash) end end - describe ':extend and :class' do + describe ":extend and :class" do module UpcaseRepresenter include Representable def to_hash(*); upcase; end @@ -379,25 +391,26 @@ def from_hash(hsh, *_args); replace hsh.downcase; end class UpcaseString < String; end - describe 'lambda blocks' do + describe "lambda blocks" do representer! do property :name, extend: ->(name, *) { compute_representer(name) } end - it 'executes lambda in represented instance context' do - assert_equal({ 'name' => 'CARNAGE' }, - Song.new('Carnage').instance_eval do + it "executes lambda in represented instance context" do + assert_equal( + {"name" => "CARNAGE"}, + Song.new("Carnage").instance_eval { def compute_representer(_name) UpcaseRepresenter end self - end.extend(representer).to_hash + }.extend(representer).to_hash ) end end - describe ':instance' do - obj = String.new('Fate') + describe ":instance" do + obj = +"Fate" mod = Module.new do include Representable def from_hash(*) @@ -408,93 +421,95 @@ def from_hash(*) property :name, extend: mod, instance: ->(*) { obj } end - it 'uses object from :instance but still extends it' do - song = Song.new.extend(representer).from_hash('name' => "Eric's Had A Bad Day") + it "uses object from :instance but still extends it" do + song = Song.new.extend(representer).from_hash("name" => "Eric's Had A Bad Day") _(song.name).must_equal obj _(song.name).must_be_kind_of mod end end - describe 'property with :extend' do + describe "property with :extend" do representer! do - property :name, extend: lambda { |options| + property :name, extend: ->(options) { options[:input].is_a?(UpcaseString) ? UpcaseRepresenter : DowncaseRepresenter }, class: String end - it 'uses lambda when rendering' do - assert_equal({ 'name' => 'you make me thick' }, Song.new('You Make Me Thick').extend(representer).to_hash) - assert_equal({ 'name' => 'STEPSTRANGER' }, - Song.new(UpcaseString.new('Stepstranger')).extend(representer).to_hash) + it "uses lambda when rendering" do + assert_equal({"name" => "you make me thick"}, Song.new("You Make Me Thick").extend(representer).to_hash) + assert_equal( + {"name" => "STEPSTRANGER"}, + Song.new(UpcaseString.new("Stepstranger")).extend(representer).to_hash + ) end - it 'uses lambda when parsing' do - _(Song.new.extend(representer).from_hash({ 'name' => 'You Make Me Thick' }).name).must_equal 'you make me thick' - _(Song.new.extend(representer).from_hash({ 'name' => 'Stepstranger' }).name).must_equal 'stepstranger' # DISCUSS: we compare "".is_a?(UpcaseString) + it "uses lambda when parsing" do + _(Song.new.extend(representer).from_hash({"name" => "You Make Me Thick"}).name).must_equal "you make me thick" + _(Song.new.extend(representer).from_hash({"name" => "Stepstranger"}).name).must_equal "stepstranger" # DISCUSS: we compare "".is_a?(UpcaseString) end - describe 'with :class lambda' do + describe "with :class lambda" do representer! do - property :name, extend: lambda { |options| + property :name, extend: ->(options) { options[:input].is_a?(UpcaseString) ? UpcaseRepresenter : DowncaseRepresenter }, - class: ->(options) { options[:fragment] == 'Still Failing?' ? String : UpcaseString } + class: ->(options) { options[:fragment] == "Still Failing?" ? String : UpcaseString } end - it 'creates instance from :class lambda when parsing' do - song = OpenStruct.new.extend(representer).from_hash({ 'name' => 'Quitters Never Win' }) + it "creates instance from :class lambda when parsing" do + song = OpenStruct.new.extend(representer).from_hash({"name" => "Quitters Never Win"}) _(song.name).must_be_kind_of UpcaseString - _(song.name).must_equal 'QUITTERS NEVER WIN' + _(song.name).must_equal "QUITTERS NEVER WIN" - song = OpenStruct.new.extend(representer).from_hash({ 'name' => 'Still Failing?' }) + song = OpenStruct.new.extend(representer).from_hash({"name" => "Still Failing?"}) _(song.name).must_be_kind_of String - _(song.name).must_equal 'still failing?' + _(song.name).must_equal "still failing?" end end end - describe 'collection with :extend' do + describe "collection with :extend" do representer! do - collection :songs, extend: lambda { |options| + collection :songs, extend: ->(options) { options[:input].is_a?(UpcaseString) ? UpcaseRepresenter : DowncaseRepresenter }, class: String end - it 'uses lambda for each item when rendering' do + it "uses lambda for each item when rendering" do _( Album.new( [ - UpcaseString.new('Dean Martin'), - 'Charlie Still Smirks' + UpcaseString.new("Dean Martin"), + "Charlie Still Smirks" ] ).extend(representer).to_hash - ).must_equal('songs' => [ - 'DEAN MARTIN', - 'charlie still smirks' + ).must_equal("songs" => [ + "DEAN MARTIN", + "charlie still smirks" ]) end - it 'uses lambda for each item when parsing' do - album = Album.new.extend(representer).from_hash('songs' => ['DEAN MARTIN', 'charlie still smirks']) - _(album.songs).must_equal ['dean martin', 'charlie still smirks'] # DISCUSS: we compare "".is_a?(UpcaseString) + it "uses lambda for each item when parsing" do + album = Album.new.extend(representer).from_hash("songs" => ["DEAN MARTIN", "charlie still smirks"]) + _(album.songs).must_equal ["dean martin", "charlie still smirks"] # DISCUSS: we compare "".is_a?(UpcaseString) end - describe 'with :class lambda' do + describe "with :class lambda" do representer! do - collection :songs, extend: lambda { |options| + collection :songs, extend: ->(options) { options[:input].is_a?(UpcaseString) ? UpcaseRepresenter : DowncaseRepresenter }, - class: ->(options) { options[:input] == 'Still Failing?' ? String : UpcaseString } + class: ->(options) { options[:input] == "Still Failing?" ? String : UpcaseString } end - it 'creates instance from :class lambda for each item when parsing' do - album = Album.new.extend(representer).from_hash('songs' => ['Still Failing?', 'charlie still smirks']) - _(album.songs).must_equal ['still failing?', 'CHARLIE STILL SMIRKS'] + it "creates instance from :class lambda for each item when parsing" do + album = Album.new.extend(representer).from_hash("songs" => ["Still Failing?", "charlie still smirks"]) + _(album.songs).must_equal ["still failing?", "CHARLIE STILL SMIRKS"] end end end - describe ':decorator' do + describe ":decorator" do let(:extend_rpr) do Module.new do include Representable::Hash @@ -507,9 +522,9 @@ def from_hash(*) collection :songs, decorator: SongRepresenter end end - let(:songs) { [Song.new('Bloody Mary')] } + let(:songs) { [Song.new("Bloody Mary")] } - it 'is aliased to :extend' do + it "is aliased to :extend" do _(Album.new(songs).extend(extend_rpr).to_hash).must_equal Album.new(songs).extend(decorator_rpr).to_hash end end @@ -526,25 +541,25 @@ class AlbumRepresentation < Representable::Decorator collection :songs, class: Song, extend: SongRepresentation end - describe '::prepare' do - let(:song) { Song.new('Still Friends In The End') } + describe "::prepare" do + let(:song) { Song.new("Still Friends In The End") } let(:album) { Album.new([song]) } - describe 'module including Representable' do - it 'uses :extend strategy' do + describe "module including Representable" do + it "uses :extend strategy" do album_rpr = Module.new do include Representable::Hash collection :songs, class: Song, extend: SongRepresenter end - _(album_rpr.prepare(album).to_hash).must_equal({ 'songs' => [{ 'name' => 'Still Friends In The End' }] }) + _(album_rpr.prepare(album).to_hash).must_equal({"songs" => [{"name" => "Still Friends In The End"}]}) _(album).must_respond_to :to_hash end end - describe 'Decorator subclass' do - it 'uses :decorate strategy' do - _(AlbumRepresentation.prepare(album).to_hash).must_equal({ 'songs' => [{ 'name' => 'Still Friends In The End' }] }) + describe "Decorator subclass" do + it "uses :decorate strategy" do + _(AlbumRepresentation.prepare(album).to_hash).must_equal({"songs" => [{"name" => "Still Friends In The End"}]}) _(album).wont_respond_to :to_hash end end diff --git a/test/schema_test.rb b/test/schema_test.rb index 269065ba..78d8088e 100644 --- a/test/schema_test.rb +++ b/test/schema_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" # Include Inherit Module And Decorator Test class SchemaTest < MiniTest::Spec @@ -15,7 +15,8 @@ def self.included(base) end module Link - def link; end + def link + end end end @@ -34,7 +35,7 @@ module Module end end - property :album, extend: -> { raise "don't manifest me!" } # this is not an inline decorator, don't manifest it. + property :album, extend: -> { fail "don't manifest me!" } # this is not an inline decorator, don't manifest it. include Genre # Schema::Included::included is called! end @@ -55,17 +56,17 @@ class WithLocationStreetRepresenter < Representable::Decorator end end - describe '3-level deep with features' do + describe "3-level deep with features" do let(:label) do - OpenStruct.new(name: 'Epitaph', location: OpenStruct.new(city: 'Sanfran', name: "DON'T SHOW ME!")) + OpenStruct.new(name: "Epitaph", location: OpenStruct.new(city: "Sanfran", name: "DON'T SHOW ME!")) end # Module does correctly include features in inlines. it { _(band.extend(Module).to_hash).must_equal( { - 'label' => { 'name' => 'Epitaph', 'location' => { 'city' => 'Sanfran' } }, - 'genre' => 'Punkrock' + "label" => {"name" => "Epitaph", "location" => {"city" => "Sanfran"}}, + "genre" => "Punkrock" } ) } @@ -74,8 +75,8 @@ class WithLocationStreetRepresenter < Representable::Decorator it { _(Decorator.new(band).to_hash).must_equal( { - 'label' => { 'name' => 'Epitaph', 'location' => { 'city' => 'Sanfran' } }, - 'genre' => 'Punkrock' + "label" => {"name" => "Epitaph", "location" => {"city" => "Sanfran"}}, + "genre" => "Punkrock" } ) } @@ -91,19 +92,19 @@ class Decorator < Representable::Decorator let(:label) do OpenStruct.new( - name: 'Fat Wreck', city: 'San Francisco', employees: [OpenStruct.new(name: 'Mike')], - location: OpenStruct.new(city: 'Sanfran') + name: "Fat Wreck", city: "San Francisco", employees: [OpenStruct.new(name: "Mike")], + location: OpenStruct.new(city: "Sanfran") ) end - let(:band) { OpenStruct.new(genre: 'Punkrock', label: label) } + let(:band) { OpenStruct.new(genre: "Punkrock", label: label) } # it { FlatlinersDecorator.new( OpenStruct.new(label: OpenStruct.new) ). # to_hash.must_equal({}) } it do _(Decorator.new(band).to_hash).must_equal( { - 'genre' => 'Punkrock', - 'label' => { 'name' => 'Fat Wreck', 'location' => { 'city' => 'Sanfran' } } + "genre" => "Punkrock", + "label" => {"name" => "Fat Wreck", "location" => {"city" => "Sanfran"}} } ) end @@ -125,10 +126,10 @@ class InheritDecorator < Representable::Decorator it do _(InheritDecorator.new(band).to_hash).must_equal( { - 'genre' => 'Punkrock', - 'label' => { - 'name' => 'Fat Wreck', 'city' => 'San Francisco', - 'location' => { 'city' => 'Sanfran' } + "genre" => "Punkrock", + "label" => { + "name" => "Fat Wreck", "city" => "San Francisco", + "location" => {"city" => "Sanfran"} } } ) @@ -145,10 +146,10 @@ class InheritFromDecorator < InheritDecorator it do _(InheritFromDecorator.new(band).to_hash).must_equal( { - 'genre' => 'Punkrock', - 'label' => { - 'name' => 'Fat Wreck', 'city' => 'San Francisco', 'employees' => [{ 'name' => 'Mike' }], - 'location' => { 'city' => 'Sanfran' } + "genre" => "Punkrock", + "label" => { + "name" => "Fat Wreck", "city" => "San Francisco", "employees" => [{"name" => "Mike"}], + "location" => {"city" => "Sanfran"} } } ) diff --git a/test/serialize_deserialize_test.rb b/test/serialize_deserialize_test.rb index 0d0d99e8..ddef3075 100644 --- a/test/serialize_deserialize_test.rb +++ b/test/serialize_deserialize_test.rb @@ -1,38 +1,42 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class SerializeDeserializeTest < BaseTest subject { Struct.new(:song).new.extend(representer) } - describe 'deserialize' do + describe "deserialize" do representer! do property :song, instance: ->(options) { options[:input].to_s.upcase }, prepare: ->(options) { options[:input] }, - deserialize: lambda { |options| + deserialize: ->(options) { "#{options[:input]} #{options[:fragment]} #{options[:user_options].inspect}" } end it { - _(subject.from_hash({ 'song' => Object }, - user_options: { volume: 9 }).song).must_equal 'OBJECT Object {:volume=>9}' + _( + subject.from_hash( + {"song" => Object}, + user_options: {volume: 9} + ).song + ).must_equal "OBJECT Object {:volume=>9}" } end - describe 'serialize' do + describe "serialize" do representer! do property :song, representable: true, prepare: ->(options) { options[:fragment] }, - serialize: lambda { |options| + serialize: ->(options) { "#{options[:input]} #{options[:user_options].inspect}" } end - before { subject.song = 'Arrested In Shanghai' } + before { subject.song = "Arrested In Shanghai" } - it { _(subject.to_hash(user_options: { volume: 9 })).must_equal({ 'song' => 'Arrested In Shanghai {:volume=>9}' }) } + it { _(subject.to_hash(user_options: {volume: 9})).must_equal({"song" => "Arrested In Shanghai {:volume=>9}"}) } end end diff --git a/test/skip_test.rb b/test/skip_test.rb index 3a5e3c9d..8d249ea4 100644 --- a/test/skip_test.rb +++ b/test/skip_test.rb @@ -1,20 +1,20 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class SkipParseTest < MiniTest::Spec representer! do - property :title, skip_parse: ->(options) { options[:user_options][:skip?] and options[:fragment] == 'skip me' } + property :title, skip_parse: ->(options) { options[:user_options][:skip?] and options[:fragment] == "skip me" } property :band, - skip_parse: lambda { |options| - options[:user_options][:skip?] and options[:fragment]['name'].nil? + skip_parse: ->(options) { + options[:user_options][:skip?] and options[:fragment]["name"].nil? }, class: OpenStruct do property :name end collection :airplays, - skip_parse: lambda { |options| - options[:user_options][:skip?] and options[:fragment]['station'].nil? + skip_parse: ->(options) { + options[:user_options][:skip?] and options[:fragment]["station"].nil? }, class: OpenStruct do property :station end @@ -26,27 +26,27 @@ class SkipParseTest < MiniTest::Spec it do song.from_hash( { - 'title' => 'Victim Of Fate', - 'band' => { 'name' => 'Mute 98' }, - 'airplays' => [{ 'station' => 'JJJ' }] - }, user_options: { skip?: true } + "title" => "Victim Of Fate", + "band" => {"name" => "Mute 98"}, + "airplays" => [{"station" => "JJJ"}] + }, user_options: {skip?: true} ) - _(song.title).must_equal 'Victim Of Fate' - _(song.band.name).must_equal 'Mute 98' - _(song.airplays[0].station).must_equal 'JJJ' + _(song.title).must_equal "Victim Of Fate" + _(song.band.name).must_equal "Mute 98" + _(song.airplays[0].station).must_equal "JJJ" end # skip parsing. - let(:airplay) { OpenStruct.new(station: 'JJJ') } + let(:airplay) { OpenStruct.new(station: "JJJ") } it do song.from_hash( { - 'title' => 'skip me', - 'band' => {}, - 'airplays' => [{}, { 'station' => 'JJJ' }, {}] - }, user_options: { skip?: true } + "title" => "skip me", + "band" => {}, + "airplays" => [{}, {"station" => "JJJ"}, {}] + }, user_options: {skip?: true} ) _(song.title).must_be_nil @@ -59,46 +59,66 @@ class SkipRenderTest < MiniTest::Spec representer! do property :title property :band, - skip_render: ->(options) { options[:user_options][:skip?] and options[:input].name == 'Rancid' } do + skip_render: ->(options) { options[:user_options][:skip?] and options[:input].name == "Rancid" } do property :name end collection :airplays, - skip_render: lambda { |options| - options[:user_options][:skip?] and options[:input].station == 'Radio Dreyeckland' + skip_render: ->(options) { + options[:user_options][:skip?] and options[:input].station == "Radio Dreyeckland" } do property :station end end - let(:song) { OpenStruct.new(title: 'Black Night', band: OpenStruct.new(name: 'Time Again')).extend(representer) } - let(:skip_song) { OpenStruct.new(title: 'Time Bomb', band: OpenStruct.new(name: 'Rancid')).extend(representer) } + let(:song) { OpenStruct.new(title: "Black Night", band: OpenStruct.new(name: "Time Again")).extend(representer) } + let(:skip_song) { OpenStruct.new(title: "Time Bomb", band: OpenStruct.new(name: "Rancid")).extend(representer) } # do render. it { - _(song.to_hash(user_options: { skip?: true })).must_equal({ 'title' => 'Black Night', - 'band' => { 'name' => 'Time Again' } }) + _(song.to_hash(user_options: {skip?: true})).must_equal( + { + "title" => "Black Night", + "band" => {"name" => "Time Again"} + } + ) } # skip. - it { _(skip_song.to_hash(user_options: { skip?: true })).must_equal({ 'title' => 'Time Bomb' }) } + it { _(skip_song.to_hash(user_options: {skip?: true})).must_equal({"title" => "Time Bomb"}) } # do render all collection items. it do - song = OpenStruct.new(airplays: [OpenStruct.new(station: 'JJJ'), - OpenStruct.new(station: 'ABC')]).extend(representer) - _(song.to_hash(user_options: { skip?: true })).must_equal({ 'airplays' => [{ 'station' => 'JJJ' }, - { 'station' => 'ABC' }] }) + song = OpenStruct.new( + airplays: [ + OpenStruct.new(station: "JJJ"), + OpenStruct.new(station: "ABC") + ] + ).extend(representer) + _(song.to_hash(user_options: {skip?: true})).must_equal( + { + "airplays" => [ + {"station" => "JJJ"}, + {"station" => "ABC"} + ] + } + ) end # skip middle item. it do song = OpenStruct.new( airplays: [ - OpenStruct.new(station: 'JJJ'), OpenStruct.new(station: 'Radio Dreyeckland'), - OpenStruct.new(station: 'ABC') + OpenStruct.new(station: "JJJ"), OpenStruct.new(station: "Radio Dreyeckland"), + OpenStruct.new(station: "ABC") ] ).extend(representer) - _(song.to_hash(user_options: { skip?: true })).must_equal({ 'airplays' => [{ 'station' => 'JJJ' }, - { 'station' => 'ABC' }] }) + _(song.to_hash(user_options: {skip?: true})).must_equal( + { + "airplays" => [ + {"station" => "JJJ"}, + {"station" => "ABC"} + ] + } + ) end end diff --git a/test/stringify_hash_test.rb b/test/stringify_hash_test.rb index 09fbe52b..92ddc08c 100644 --- a/test/stringify_hash_test.rb +++ b/test/stringify_hash_test.rb @@ -1,9 +1,9 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class StringifyHashTest < MiniTest::Spec - describe '#from_hash' do + describe "#from_hash" do representer!(name: :song_representer) do include Representable::Hash include Representable::Hash::AllowSymbols @@ -17,15 +17,15 @@ class StringifyHashTest < MiniTest::Spec property :song, extend: song_representer, class: OpenStruct end - it 'parses symbols, too' do - _(OpenStruct.new.extend(representer).from_hash({ song: { title: 'Der Optimist' } }).song.title).must_equal 'Der Optimist' + it "parses symbols, too" do + _(OpenStruct.new.extend(representer).from_hash({song: {title: "Der Optimist"}}).song.title).must_equal "Der Optimist" end - it 'still parses strings' do - _(OpenStruct.new.extend(representer).from_hash({ 'song' => { 'title' => 'Der Optimist' } }).song.title).must_equal 'Der Optimist' + it "still parses strings" do + _(OpenStruct.new.extend(representer).from_hash({"song" => {"title" => "Der Optimist"}}).song.title).must_equal "Der Optimist" end - describe 'with :wrap' do + describe "with :wrap" do representer!(inject: :song_representer) do include Representable::Hash::AllowSymbols @@ -33,8 +33,8 @@ class StringifyHashTest < MiniTest::Spec property :song, extend: song_representer, class: OpenStruct end - it 'parses symbols, too' do - _(OpenStruct.new.extend(representer).from_hash({ album: { song: { title: 'Der Optimist' } } }).song.title).must_equal 'Der Optimist' + it "parses symbols, too" do + _(OpenStruct.new.extend(representer).from_hash({album: {song: {title: "Der Optimist"}}}).song.title).must_equal "Der Optimist" end end end diff --git a/test/test_helper.rb b/test/test_helper.rb index e127c541..5ce9b78a 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,30 +1,30 @@ # frozen_string_literal: true begin - require 'pry-byebug' + require "pry-byebug" rescue LoadError end -require 'representable' +require "representable" -require 'minitest/autorun' -require 'test_xml/mini_test' +require "minitest/autorun" +require "test_xml/mini_test" -require 'representable/debug' -require 'minitest/assertions' +require "representable/debug" +require "minitest/assertions" module MiniTest module Assertions def assert_equal_xml(text, subject) - assert_equal text.delete("\n").gsub(/(\s\s+)/, ''), subject.delete("\n").gsub(/(\s\s+)/, '') + assert_equal text.delete("\n").gsub(/(\s\s+)/, ""), subject.delete("\n").gsub(/(\s\s+)/, "") end end end String.infect_an_assertion :assert_equal_xml, :must_xml # TODO: delete all that in 4.0 -require_relative 'models/album' -require_relative 'models/band' -require_relative 'models/song' +require_relative "models/album" +require_relative "models/band" +require_relative "models/song" module XmlHelper def xml(document) @@ -35,7 +35,7 @@ def xml(document) module AssertJson module Assertions def assert_json(expected, actual, msg = nil) - msg = message(msg, '') { diff expected, actual } + msg = message(msg, "") { diff expected, actual } assert_equal(expected.chars.sort, actual.chars.sort, msg) end @@ -121,8 +121,8 @@ def representer_for(modules = [Representable::Hash], &block) class BaseTest < MiniTest::Spec let(:new_album) { OpenStruct.new.extend(representer) } - let(:album) { OpenStruct.new(songs: ['Fuck Armageddon']).extend(representer) } - let(:song) { OpenStruct.new(title: 'Resist Stance') } + let(:album) { OpenStruct.new(songs: ["Fuck Armageddon"]).extend(representer) } + let(:song) { OpenStruct.new(title: "Resist Stance") } let(:song_representer) do Module.new do include Representable::Hash diff --git a/test/test_helper_test.rb b/test/test_helper_test.rb index 4f57a6f3..b8c22eb4 100644 --- a/test/test_helper_test.rb +++ b/test/test_helper_test.rb @@ -1,24 +1,24 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class TestHelperTest < MiniTest::Spec - describe '#assert_json' do - it 'tests for equality' do + describe "#assert_json" do + it "tests for equality" do assert_json '{"songs":{"one":"65","two":"Emo Boy"}}', '{"songs":{"one":"65","two":"Emo Boy"}}' end - it 'allows different key orders' do + it "allows different key orders" do assert_json '{"songs":{"one":"65","two":"Emo Boy"}}', '{"songs":{"two":"Emo Boy","one":"65"}}' end - it 'complains when expected hash is subset' do + it "complains when expected hash is subset" do assert_raises MiniTest::Assertion do assert_json '{"songs":{"one":"65"}}', '{"songs":{"two":"Emo Boy","one":"65"}}' end end - it 'complains when source hash is subset' do + it "complains when source hash is subset" do assert_raises MiniTest::Assertion do assert_json '{"songs":{"two":"Emo Boy","one":"65"}}', '{"songs":{"one":"65"}}' end diff --git a/test/uncategorized_test.rb b/test/uncategorized_test.rb index 115103ab..f029aaca 100644 --- a/test/uncategorized_test.rb +++ b/test/uncategorized_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class StopWhenIncomingObjectFragmentIsNilTest < MiniTest::Spec Album = Struct.new(:id, :songs) @@ -8,7 +8,7 @@ class StopWhenIncomingObjectFragmentIsNilTest < MiniTest::Spec representer!(decorator: true) do property :id - collection :songs, class: Song, parse_pipeline: lambda { |_input, _options| # TODO: test if :doc is set for parsing. test if options are ok and contain :user_options! + collection :songs, class: Song, parse_pipeline: ->(_input, _options) { # TODO: test if :doc is set for parsing. test if options are ok and contain :user_options! Representable::Pipeline[*parse_functions.insert(3, Representable::StopOnNil)] } do property :title @@ -20,57 +20,57 @@ class StopWhenIncomingObjectFragmentIsNilTest < MiniTest::Spec _( representer.new(album).from_hash( { - 'id' => 1, - 'songs' => [{ 'title' => 'Walkie Talkie' }] + "id" => 1, + "songs" => [{"title" => "Walkie Talkie"}] } ).songs - ).must_equal [Song.new('Walkie Talkie')] + ).must_equal [Song.new("Walkie Talkie")] end it do - album = Album.new(2, ['original']) - _(representer.new(album).from_hash({ 'id' => 1, 'songs' => nil }).songs).must_equal ['original'] + album = Album.new(2, ["original"]) + _(representer.new(album).from_hash({"id" => 1, "songs" => nil}).songs).must_equal ["original"] end end class RenderPipelineOptionTest < MiniTest::Spec Album = Struct.new(:id, :songs) - NilToNA = ->(input, _options) { input.nil? ? 'n/a' : input } + NilToNA = ->(input, _options) { input.nil? ? "n/a" : input } representer!(decorator: true) do - property :id, render_pipeline: lambda { |_input, options| + property :id, render_pipeline: ->(_input, options) { Representable::Pipeline[*render_functions.insert(2, options[:options][:user_options][:function])] } end - it { _(representer.new(Album.new).to_hash(user_options: { function: NilToNA })).must_equal({ 'id' => 'n/a' }) } - it { _(representer.new(Album.new(1)).to_hash(user_options: { function: NilToNA })).must_equal({ 'id' => 1 }) } + it { _(representer.new(Album.new).to_hash(user_options: {function: NilToNA})).must_equal({"id" => "n/a"}) } + it { _(representer.new(Album.new(1)).to_hash(user_options: {function: NilToNA})).must_equal({"id" => 1}) } - it 'is cached' do + it "is cached" do decorator = representer.new(Album.new) - _(decorator.to_hash(user_options: { function: NilToNA })).must_equal({ 'id' => 'n/a' }) - _(decorator.to_hash(user_options: { function: nil })).must_equal({ 'id' => 'n/a' }) # non-sense function is not applied. + _(decorator.to_hash(user_options: {function: NilToNA})).must_equal({"id" => "n/a"}) + _(decorator.to_hash(user_options: {function: nil})).must_equal({"id" => "n/a"}) # non-sense function is not applied. end end class ParsePipelineOptionTest < MiniTest::Spec Album = Struct.new(:id, :songs) - NilToNA = ->(input, _options) { input.nil? ? 'n/a' : input } + NilToNA = ->(input, _options) { input.nil? ? "n/a" : input } representer!(decorator: true) do - property :id, parse_pipeline: lambda { |_input, options| + property :id, parse_pipeline: ->(_input, options) { Representable::Pipeline[*parse_functions.insert(3, options[:options][:user_options][:function])].extend(Representable::Pipeline::Debug) } end it { - _(representer.new(Album.new).from_hash({ 'id' => nil }, user_options: { function: NilToNA }).id).must_equal 'n/a' + _(representer.new(Album.new).from_hash({"id" => nil}, user_options: {function: NilToNA}).id).must_equal "n/a" } - it { _(representer.new(Album.new(1)).to_hash(user_options: { function: NilToNA })).must_equal({ 'id' => 1 }) } + it { _(representer.new(Album.new(1)).to_hash(user_options: {function: NilToNA})).must_equal({"id" => 1}) } - it 'is cached' do + it "is cached" do decorator = representer.new(Album.new) - _(decorator.from_hash({ 'id' => nil }, user_options: { function: NilToNA }).id).must_equal 'n/a' - _(decorator.from_hash({ 'id' => nil }, user_options: { function: 'nonsense' }).id).must_equal 'n/a' # non-sense function is not applied. + _(decorator.from_hash({"id" => nil}, user_options: {function: NilToNA}).id).must_equal "n/a" + _(decorator.from_hash({"id" => nil}, user_options: {function: "nonsense"}).id).must_equal "n/a" # non-sense function is not applied. end end diff --git a/test/user_options_test.rb b/test/user_options_test.rb index f9ee5e9f..b90cae03 100644 --- a/test/user_options_test.rb +++ b/test/user_options_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class UserOptionsTest < Minitest::Spec Song = Struct.new(:title) @@ -9,20 +9,20 @@ class UserOptionsTest < Minitest::Spec property :title, if: ->(options) { options[:user_options][:visible] } end - it { _(Song.new('Run With It').extend(representer).to_hash).must_equal({}) } + it { _(Song.new("Run With It").extend(representer).to_hash).must_equal({}) } it { - _(Song.new('Run With It').extend(representer).to_hash(user_options: { visible: true })).must_equal({ 'title' => 'Run With It' }) + _(Song.new("Run With It").extend(representer).to_hash(user_options: {visible: true})).must_equal({"title" => "Run With It"}) } it { - _(Song.new('Run With It').extend(representer).from_hash('title' => 'Business Conduct').title).must_equal 'Run With It' + _(Song.new("Run With It").extend(representer).from_hash("title" => "Business Conduct").title).must_equal "Run With It" } it { _( - Song.new('Run With It').extend(representer).from_hash( - { 'title' => 'Business Conduct' }, - user_options: { visible: true } + Song.new("Run With It").extend(representer).from_hash( + {"title" => "Business Conduct"}, + user_options: {visible: true} ).title - ).must_equal 'Business Conduct' + ).must_equal "Business Conduct" } end # Representable.deprecations=false diff --git a/test/wrap_test.rb b/test/wrap_test.rb index ef98ea81..fcff2b6b 100644 --- a/test/wrap_test.rb +++ b/test/wrap_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class WrapTest < MiniTest::Spec class HardcoreBand @@ -12,29 +12,33 @@ class SoftcoreBand < HardcoreBand let(:band) { HardcoreBand.new } - it 'returns false per default' do + it "returns false per default" do assert_nil SoftcoreBand.new.send(:representation_wrap) end - it 'infers a printable class name if set to true' do + it "infers a printable class name if set to true" do HardcoreBand.representation_wrap = true - assert_equal 'hardcore_band', band.send(:representation_wrap) + + assert_equal "hardcore_band", band.send(:representation_wrap) end - it 'can be set explicitely' do - HardcoreBand.representation_wrap = 'breach' - assert_equal 'breach', band.send(:representation_wrap) + it "can be set explicitely" do + HardcoreBand.representation_wrap = "breach" + + assert_equal "breach", band.send(:representation_wrap) end for_formats( - hash: [Representable::Hash, { 'Blink182' => { 'genre' => 'Pop' } }, { 'Blink182' => { 'genre' => 'Poppunk' } }], + hash: [Representable::Hash, {"Blink182" => {"genre" => "Pop"}}, {"Blink182" => {"genre" => "Poppunk"}}], json: [Representable::JSON, '{"Blink182":{"genre":"Pop"}}', '{"Blink182":{"genre":"Poppunk"}}'], - xml: [Representable::XML, 'Pop', - 'Poppunk'] + xml: [ + Representable::XML, "Pop", + "Poppunk" + ] # :yaml => [Representable::YAML, "---\nBlink182:\n"], # TODO: fix YAML. ) do |format, mod, output, input| describe "[#{format}] dynamic wrap" do - let(:band) { representer.prepare(Struct.new(:name, :genre).new('Blink', 'Pop')) } + let(:band) { representer.prepare(Struct.new(:name, :genre).new("Blink", "Pop")) } let(:format) { format } representer!(module: mod) do @@ -42,10 +46,10 @@ class SoftcoreBand < HardcoreBand property :genre end - it { assert_equal_document(render(band, { number: 182 }), output) } + it { assert_equal_document(render(band, {number: 182}), output) } it { - _(parse(band, input, { number: 182 }).genre).must_equal 'Poppunk' + _(parse(band, input, {number: 182}).genre).must_equal "Poppunk" } # TODO: better test. also, xml parses _any_ wrap. end end @@ -69,19 +73,19 @@ class BandDecorator < Representable::Decorator end end - let(:band) { BandDecorator.prepare(Band.new('Social Distortion')) } + let(:band) { BandDecorator.prepare(Band.new("Social Distortion")) } # direct, local api. it do - _(band.to_hash).must_equal({ 'bands' => { 'name' => 'Social Distortion' } }) - _(band.to_hash(wrap: false)).must_equal({ 'name' => 'Social Distortion' }) - _(band.to_hash(wrap: :band)).must_equal(band: { 'name' => 'Social Distortion' }) + _(band.to_hash).must_equal({"bands" => {"name" => "Social Distortion"}}) + _(band.to_hash(wrap: false)).must_equal({"name" => "Social Distortion"}) + _(band.to_hash(wrap: :band)).must_equal(band: {"name" => "Social Distortion"}) end it do - _(band.from_hash({ 'bands' => { 'name' => 'Social Distortion' } }).name).must_equal 'Social Distortion' - _(band.from_hash({ 'name' => 'Social Distortion' }, wrap: false).name).must_equal 'Social Distortion' - _(band.from_hash({ band: { 'name' => 'Social Distortion' } }, wrap: :band).name).must_equal 'Social Distortion' + _(band.from_hash({"bands" => {"name" => "Social Distortion"}}).name).must_equal "Social Distortion" + _(band.from_hash({"name" => "Social Distortion"}, wrap: false).name).must_equal "Social Distortion" + _(band.from_hash({band: {"name" => "Social Distortion"}}, wrap: :band).name).must_equal "Social Distortion" end class AlbumDecorator < Representable::Decorator @@ -92,24 +96,24 @@ class AlbumDecorator < Representable::Decorator property :band, decorator: BandDecorator, wrap: false, class: Band end - let(:album) { AlbumDecorator.prepare(Album.new(Band.new('Social Distortion', Label.new('Epitaph')))) } + let(:album) { AlbumDecorator.prepare(Album.new(Band.new("Social Distortion", Label.new("Epitaph")))) } # band has wrap turned off per property definition, however, label still has wrap. - it 'renders' do + it "renders" do _(album.to_hash).must_equal( { - 'albums' => { - 'band' => { - 'name' => 'Social Distortion', - 'label' => { 'important' => { 'name' => 'Epitaph' } } + "albums" => { + "band" => { + "name" => "Social Distortion", + "label" => {"important" => {"name" => "Epitaph"}} } } } ) end - it 'parses' do - _(album.from_hash({ 'albums' => { 'band' => { 'name' => 'Rvivr' } } }).band.name).must_equal 'Rvivr' + it "parses" do + _(album.from_hash({"albums" => {"band" => {"name" => "Rvivr"}}}).band.name).must_equal "Rvivr" end end @@ -130,11 +134,11 @@ class BandDecorator < Representable::Decorator # end end - let(:band) { BandDecorator.prepare(Band.new('Social Distortion')) } + let(:band) { BandDecorator.prepare(Band.new("Social Distortion")) } it do - assert_xml_equal band.to_xml, 'Social Distortion' - assert_xml_equal band.to_xml(wrap: 'combo'), 'Social Distortion' + assert_xml_equal band.to_xml, "Social Distortion" + assert_xml_equal band.to_xml(wrap: "combo"), "Social Distortion" end class AlbumDecorator < Representable::Decorator @@ -142,20 +146,22 @@ class AlbumDecorator < Representable::Decorator self.representation_wrap = :albums - property :band, decorator: BandDecorator, wrap: 'po', class: Band + property :band, decorator: BandDecorator, wrap: "po", class: Band end - let(:album) { AlbumDecorator.prepare(Album.new(Band.new('Social Distortion', Label.new('Epitaph')))) } + let(:album) { AlbumDecorator.prepare(Album.new(Band.new("Social Distortion", Label.new("Epitaph")))) } # band has wrap turned of per property definition, however, label still has wrap. - it 'rendersxx' do - assert_xml_equal(" + it "rendersxx" do + assert_xml_equal( + " Social Distortion -", album.to_xml) +", album.to_xml + ) end # it "parses" do diff --git a/test/xml_bindings_test.rb b/test/xml_bindings_test.rb index 55fdf7dd..9b2c53b1 100644 --- a/test/xml_bindings_test.rb +++ b/test/xml_bindings_test.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'test_helper' -require 'representable/xml/hash' +require "test_helper" +require "representable/xml/hash" class XMLBindingTest < MiniTest::Spec module SongRepresenter @@ -18,40 +18,42 @@ class SongWithRepresenter < ::Song before do @doc = Nokogiri::XML::Document.new - @song = SongWithRepresenter.new('Thinning the Herd') + @song = SongWithRepresenter.new("Thinning the Herd") end - describe 'AttributeBinding' do - describe 'with plain text items' do + describe "AttributeBinding" do + describe "with plain text items" do before do @property = Representable::XML::Binding::Attribute.new(Representable::Definition.new(:name, attribute: true)) end - it 'extracts with #read' do - assert_equal 'The Gargoyle', @property.read(Nokogiri::XML('').root, 'name') + it "extracts with #read" do + assert_equal "The Gargoyle", @property.read(Nokogiri::XML('').root, "name") end - it 'inserts with #write' do - parent = Nokogiri::XML::Node.new('song', @doc) - @property.write(parent, 'The Gargoyle', 'name') + it "inserts with #write" do + parent = Nokogiri::XML::Node.new("song", @doc) + @property.write(parent, "The Gargoyle", "name") + assert_xml_equal('', parent.to_s) end end end - describe 'ContentBinding' do + describe "ContentBinding" do before do @property = Representable::XML::Binding::Content.new(Representable::Definition.new(:name, content: true)) end - it 'extracts with #read' do - assert_equal 'The Gargoyle', @property.read(Nokogiri::XML('The Gargoyle').root, 'song') + it "extracts with #read" do + assert_equal "The Gargoyle", @property.read(Nokogiri::XML("The Gargoyle").root, "song") end - it 'inserts with #write' do - parent = Nokogiri::XML::Node.new('song', @doc) - @property.write(parent, 'The Gargoyle', 'song') - assert_xml_equal('The Gargoyle', parent.to_s) + it "inserts with #write" do + parent = Nokogiri::XML::Node.new("song", @doc) + @property.write(parent, "The Gargoyle", "song") + + assert_xml_equal("The Gargoyle", parent.to_s) end end end diff --git a/test/xml_namespace_test.rb b/test/xml_namespace_test.rb index 5326d832..b44e741b 100644 --- a/test/xml_namespace_test.rb +++ b/test/xml_namespace_test.rb @@ -1,4 +1,4 @@ -require 'test_helper' +require "test_helper" # + %{ 666 - ), + }, # :simple-xml end Library.new(Model::Library.new(book)).to_xml ) @@ -98,7 +98,7 @@ module Model end let(:book) do - Model::Book.new(1, 666, Model::Character.new('Fowler'), [Model::Character.new('Frau Java', 1991, 'typed')]) + Model::Book.new(1, 666, Model::Character.new("Fowler"), [Model::Character.new("Frau Java", 1991, "typed")]) end # :map-class @@ -106,37 +106,36 @@ class Library < Representable::Decorator feature Representable::XML feature Representable::XML::Namespace - namespace 'http://eric.van-der-vlist.com/ns/library' - namespace_def lib: 'http://eric.van-der-vlist.com/ns/library' - namespace_def hr: 'http://eric.van-der-vlist.com/ns/person' + namespace "http://eric.van-der-vlist.com/ns/library" + namespace_def lib: "http://eric.van-der-vlist.com/ns/library" + namespace_def hr: "http://eric.van-der-vlist.com/ns/person" property :book, class: Model::Book do - namespace 'http://eric.van-der-vlist.com/ns/library' + namespace "http://eric.van-der-vlist.com/ns/library" property :id, attribute: true property :isbn property :author, class: Model::Character do - namespace 'http://eric.van-der-vlist.com/ns/person' + namespace "http://eric.van-der-vlist.com/ns/person" property :name property :born end collection :character, class: Model::Character do - namespace 'http://eric.van-der-vlist.com/ns/library' + namespace "http://eric.van-der-vlist.com/ns/library" property :qualification - property :name, namespace: 'http://eric.van-der-vlist.com/ns/person' - property :born, namespace: 'http://eric.van-der-vlist.com/ns/person' + property :name, namespace: "http://eric.van-der-vlist.com/ns/person" + property :born, namespace: "http://eric.van-der-vlist.com/ns/person" end end end # :map-class end - it 'renders' do - + it "renders" do assert_equal( # :map-xml "\n \n 666\n \n Fowler\n \n \n typed\n Frau Java\n 1991\n \n \n", @@ -145,11 +144,11 @@ class Library < Representable::Decorator ) end - it 'parses' do + it "parses" do lib = Model::Library.new # :parse-call Library.new(lib).from_xml( - %( @@ -165,11 +164,11 @@ class Library < Representable::Decorator 1991 -) +} # :parse-call end ) - #take last line only + # take last line only xml = lib.book.inspect expected = "#, character=[#]>" diff --git a/test/xml_test.rb b/test/xml_test.rb index 7af993a9..11612036 100644 --- a/test/xml_test.rb +++ b/test/xml_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class XmlPublicMethodsTest < Minitest::Spec #--- @@ -11,14 +11,14 @@ class BandRepresenter < Representable::Decorator property :name end - let(:data) { %(1Rancid) } + let(:data) { %{1Rancid} } it { _(BandRepresenter.new(Band.new).from_xml(data)[:id, :name]).must_equal %w[1 Rancid] } it { _(BandRepresenter.new(Band.new).parse(data)[:id, :name]).must_equal %w[1 Rancid] } #--- # to_hash - let(:band) { Band.new('1', 'Rancid') } + let(:band) { Band.new("1", "Rancid") } it { assert_xml_equal(BandRepresenter.new(band).to_xml, data) } it { assert_xml_equal(BandRepresenter.new(band).render, data) } @@ -38,7 +38,7 @@ def initialize(name = nil) XML = Representable::XML Def = Representable::Definition - describe 'Xml module' do + describe "Xml module" do before do @Band = Class.new do include Representable::XML @@ -51,92 +51,98 @@ def initialize(name = nil) @band = @Band.new end - describe '#from_xml' do + describe "#from_xml" do before do @band = @Band.new - @xml = %(Nofx) + @xml = %{Nofx} end - it 'parses XML and assigns properties' do + it "parses XML and assigns properties" do @band.from_xml(@xml) + assert_equal %w[Nofx NOFX], [@band.name, @band.label] end end - describe '#from_xml with remove_namespaces! and xmlns present' do + describe "#from_xml with remove_namespaces! and xmlns present" do before do @Band.remove_namespaces! @band = @Band.new - @xml = %(Nofx) + @xml = %{Nofx} end - it 'parses with xmlns present' do + it "parses with xmlns present" do @band.from_xml(@xml) + assert_equal %w[Nofx NOFX], [@band.name, @band.label] end end - describe '#from_node' do + describe "#from_node" do before do @band = @Band.new - @xml = Nokogiri::XML(%(Nofx)).root + @xml = Nokogiri::XML(%{Nofx}).root end - it 'receives Nokogiri node and assigns properties' do + it "receives Nokogiri node and assigns properties" do @band.from_node(@xml) + assert_equal %w[Nofx NOFX], [@band.name, @band.label] end end - describe '#to_xml' do - it 'delegates to #to_node and returns string' do - assert_xml_equal 'Rise Against', Band.new('Rise Against').to_xml + describe "#to_xml" do + it "delegates to #to_node and returns string" do + assert_xml_equal "Rise Against", Band.new("Rise Against").to_xml end end - describe '#to_node' do - it 'returns Nokogiri node' do - node = Band.new('Rise Against').to_node + describe "#to_node" do + it "returns Nokogiri node" do + node = Band.new("Rise Against").to_node + assert_kind_of Nokogiri::XML::Element, node end - it 'wraps with infered class name per default' do - node = Band.new('Rise Against').to_node - assert_xml_equal 'Rise Against', node.to_s + it "wraps with infered class name per default" do + node = Band.new("Rise Against").to_node + + assert_xml_equal "Rise Against", node.to_s end - it 'respects #representation_wrap=' do + it "respects #representation_wrap=" do klass = Class.new(Band) do include Representable property :name end klass.representation_wrap = :group - assert_xml_equal 'Rise Against', klass.new('Rise Against').to_node.to_s + + assert_xml_equal "Rise Against", klass.new("Rise Against").to_node.to_s end end - describe 'XML::Binding#build_for' do - it 'returns AttributeBinding' do + describe "XML::Binding#build_for" do + it "returns AttributeBinding" do assert_kind_of XML::Binding::Attribute, - XML::Binding.build_for(Def.new(:band, as: 'band', attribute: true)) + XML::Binding.build_for(Def.new(:band, as: "band", attribute: true)) end - it 'returns Binding' do + it "returns Binding" do assert_kind_of XML::Binding, XML::Binding.build_for(Def.new(:band, class: Hash)) assert_kind_of XML::Binding, XML::Binding.build_for(Def.new(:band, as: :content)) end - it 'returns CollectionBinding' do + it "returns CollectionBinding" do assert_kind_of XML::Binding::Collection, XML::Binding.build_for(Def.new(:band, collection: true)) end - it 'returns HashBinding' do + it "returns HashBinding" do assert_kind_of XML::Binding::Hash, XML::Binding.build_for(Def.new(:band, hash: true)) end end - describe 'DCI' do + describe "DCI" do module SongRepresenter include Representable::XML property :name @@ -148,7 +154,7 @@ module AlbumRepresenter collection :songs, class: Song, as: :song, extend: SongRepresenter end - it 'allows adding the representer by using #extend' do + it "allows adding the representer by using #extend" do module BandRepresenter include Representable::XML property :name @@ -156,7 +162,7 @@ module BandRepresenter civ = Object.new civ.instance_eval do - def name = 'CIV' + def name; "CIV"; end def name=(v) @name = v @@ -164,12 +170,13 @@ def name=(v) end civ.extend(BandRepresenter) - assert_xml_equal 'CIV', civ.to_xml + + assert_xml_equal "CIV", civ.to_xml end - it 'extends contained models when serializing' do + it "extends contained models when serializing" do @album = Album.new( - [Song.new('I Hate My Brain'), mr = Song.new('Mr. Charisma')], mr + [Song.new("I Hate My Brain"), mr = Song.new("Mr. Charisma")], mr ) @album.extend(AlbumRepresenter) @@ -180,41 +187,43 @@ def name=(v) ", @album.to_xml end - it 'extends contained models when deserializing' do + it "extends contained models when deserializing" do @album = Album.new @album.extend(AlbumRepresenter) - @album.from_xml('Mr. CharismaI Hate My BrainMr. Charisma') - assert_equal 'Mr. Charisma', @album.best_song.name + @album.from_xml("Mr. CharismaI Hate My BrainMr. Charisma") + + assert_equal "Mr. Charisma", @album.best_song.name end end end end class AttributesTest < MiniTest::Spec - describe ':as => rel, :attribute => true' do + describe ":as => rel, :attribute => true" do class Link include Representable::XML - property :href, as: 'href', attribute: true - property :title, as: 'title', attribute: true + property :href, as: "href", attribute: true + property :title, as: "title", attribute: true attr_accessor :href, :title end - it '#from_xml creates correct accessors' do + it "#from_xml creates correct accessors" do link = Link.new.from_xml( - %( + %{ + } ) - ) - assert_equal 'http://apotomo.de', link.href - assert_equal 'Home, sweet home', link.title + + assert_equal "http://apotomo.de", link.href + assert_equal "Home, sweet home", link.title end - it '#to_xml serializes correctly' do + it "#to_xml serializes correctly" do link = Link.new - link.href = 'http://apotomo.de/' + link.href = "http://apotomo.de/" - assert_xml_equal %(), link.to_xml + assert_xml_equal %{}, link.to_xml end end end @@ -227,7 +236,7 @@ def serialize_node(parent, _value) end include Representable::XML - property :name, binding: lambda { |*args| + property :name, binding: ->(*args) { CData.new(*args) } # getter: lambda { |opt| Nokogiri::XML::CDATA.new(opt[:doc], name) } attr_accessor :name @@ -264,52 +273,53 @@ def initialize(band = nil) # TODO: property :group, :class => Band # :class # where to mixin DCI? - describe ':class => Item' do - it '#from_xml creates one Item instance' do + describe ":class => Item" do + it "#from_xml creates one Item instance" do album = Album.new.extend(AlbumRepresenter).from_xml( - %( + %{ Bad Religion + } ) - ) - assert_equal 'Bad Religion', album.band.name + + assert_equal "Bad Religion", album.band.name end - describe '#to_xml' do + describe "#to_xml" do it "doesn't escape xml from Band#to_xml" do - band = Band.new('Bad Religion') + band = Band.new("Bad Religion") album = Album.new(band).extend(AlbumRepresenter) - assert_xml_equal %( + assert_xml_equal %{ Bad Religion - ), album.to_xml + }, album.to_xml end it "doesn't escape and wrap string from Band#to_node" do - band = Band.new('Bad Religion') + band = Band.new("Bad Religion") band.instance_eval do def to_node(*) - 'Baaaad Religion' + "Baaaad Religion" end end - assert_xml_equal %(Baaaad Religion), Album.new(band).extend(AlbumRepresenter).to_xml + assert_xml_equal %{Baaaad Religion}, Album.new(band).extend(AlbumRepresenter).to_xml end end - describe '#to_xml with CDATA' do - it 'wraps Band name in CDATA#to_xml' do - band = CDataBand.new('Bad Religion') + describe "#to_xml with CDATA" do + it "wraps Band name in CDATA#to_xml" do + band = CDataBand.new("Bad Religion") album = Album.new(band).extend(AlbumRepresenter) - assert_xml_equal %( + assert_xml_equal %{ - ), album.to_xml + }, album.to_xml end end end @@ -328,7 +338,7 @@ class BandRepresenter < Representable::Decorator property :genre, attribute: true end - it { assert_xml_equal(BandRepresenter.new(Band.new('Mute')).to_xml, %(Mute)) } + it { assert_xml_equal(BandRepresenter.new(Band.new("Mute")).to_xml, %{Mute}) } class ManagerRepresenter < Representable::Decorator include Representable::XML @@ -337,15 +347,17 @@ class ManagerRepresenter < Representable::Decorator #- :as with nested property it { - assert_xml_equal(%(Mute), - ManagerRepresenter.new( - Manager.new( - Band.new( - 'Mute', - 'Punkrock' + assert_xml_equal( + %{Mute}, + ManagerRepresenter.new( + Manager.new( + Band.new( + "Mute", + "Punkrock" + ) ) - ) - ).to_xml) + ).to_xml + ) } end @@ -360,37 +372,40 @@ class BandRepresenter < Representable::Decorator #--- #- :as, :decorator, :class - describe ':class => Band, :as => :band, :collection => true' do + describe ":class => Band, :as => :band, :collection => true" do class CompilationRepresenter < Representable::Decorator include Representable::XML collection :bands, class: Band, as: :group, decorator: BandRepresenter end - describe '#from_xml' do - it 'pushes collection items to array' do + describe "#from_xml" do + it "pushes collection items to array" do cd = CompilationRepresenter.new(Compilation.new).from_xml( - %( + %{ Diesel Boy Cobra Skulls + } ) - ) - assert_equal ['Cobra Skulls', 'Diesel Boy'], cd.bands.map(&:name).sort + + assert_equal ["Cobra Skulls", "Diesel Boy"], cd.bands.map(&:name).sort end end - it 'responds to #to_xml' do - cd = Compilation.new([Band.new('Diesel Boy'), Band.new('Bad Religion')]) + it "responds to #to_xml" do + cd = Compilation.new([Band.new("Diesel Boy"), Band.new("Bad Religion")]) - assert_xml_equal(CompilationRepresenter.new(cd).to_xml, %( + assert_xml_equal( + CompilationRepresenter.new(cd).to_xml, %{ Diesel Boy Bad Religion - )) + } + ) end end - describe ':as' do + describe ":as" do let(:xml_doc) do Module.new do include Representable::XML @@ -398,21 +413,22 @@ class CompilationRepresenter < Representable::Decorator end end - it 'collects untyped items' do + it "collects untyped items" do album = Album.new.extend(xml_doc).from_xml( - %( + %{ Two Kevins Wright and Rong Laundry Basket + } ) - ) - assert_equal ['Laundry Basket', 'Two Kevins', 'Wright and Rong'].sort, album.songs.sort + + assert_equal ["Laundry Basket", "Two Kevins", "Wright and Rong"].sort, album.songs.sort end end - describe ':wrap' do + describe ":wrap" do let(:album) { Album.new.extend(xml_doc) } let(:xml_doc) do Module.new do @@ -421,10 +437,10 @@ class CompilationRepresenter < Representable::Decorator end end - describe '#from_xml' do - it 'finds items in wrapped collection' do + describe "#from_xml" do + it "finds items in wrapped collection" do album.from_xml( - %( + %{ Two Kevins @@ -432,16 +448,18 @@ class CompilationRepresenter < Representable::Decorator Laundry Basket + } ) - ) - assert_equal ['Laundry Basket', 'Two Kevins', 'Wright and Rong'].sort, album.songs.sort + + assert_equal ["Laundry Basket", "Two Kevins", "Wright and Rong"].sort, album.songs.sort end end - describe '#to_xml' do - it 'wraps items' do - album.songs = ['Laundry Basket', 'Two Kevins', 'Wright and Rong'] - assert_xml_equal %( + describe "#to_xml" do + it "wraps items" do + album.songs = ["Laundry Basket", "Two Kevins", "Wright and Rong"] + + assert_xml_equal %{ Laundry Basket @@ -449,12 +467,12 @@ class CompilationRepresenter < Representable::Decorator Wright and Rong - ), album.to_xml + }, album.to_xml end end end - require 'representable/xml/hash' + require "representable/xml/hash" class LonelyRepresenterTest < MiniTest::Spec # TODO: where is the XML::Hash test? module SongRepresenter @@ -471,76 +489,76 @@ module SongRepresenter end end - describe 'XML::Collection' do - describe 'with contained objects' do + describe "XML::Collection" do + describe "with contained objects" do representer!(module: Representable::XML::Collection) do items class: Song, extend: SongRepresenter self.representation_wrap = :songs end - let(:songs) { [Song.new('Days Go By'), Song.new("Can't Take Them All")] } + let(:songs) { [Song.new("Days Go By"), Song.new("Can't Take Them All")] } let(:xml_doc) do "Days Go ByCan't Take Them All" end - it 'renders array' do + it "renders array" do assert_xml_equal(songs.extend(representer).to_xml, xml_doc) end - it 'renders array with decorator' do + it "renders array with decorator" do assert_xml_equal(decorator.new(songs).to_xml, xml_doc) end - it 'parses array' do + it "parses array" do _([].extend(representer).from_xml(xml_doc)).must_equal songs end - it 'parses array with decorator' do + it "parses array with decorator" do _(decorator.new([]).from_xml(xml_doc)).must_equal songs end end end - describe 'XML::AttributeHash' do # TODO: move to HashTest. + describe "XML::AttributeHash" do # TODO: move to HashTest. representer!(module: Representable::XML::AttributeHash) do self.representation_wrap = :songs end - let(:songs) { { 'one' => 'Graveyards', 'two' => "Can't Take Them All" } } + let(:songs) { {"one" => "Graveyards", "two" => "Can't Take Them All"} } let(:xml_doc) { "" } - describe '#to_xml' do - it 'renders hash' do + describe "#to_xml" do + it "renders hash" do assert_xml_equal(songs.extend(representer).to_xml, xml_doc) end - it 'respects :exclude' do + it "respects :exclude" do assert_xml_equal "", songs.extend(representer).to_xml(exclude: [:one]) end - it 'respects :include' do + it "respects :include" do assert_xml_equal "", songs.extend(representer).to_xml(include: [:two]) end - it 'renders hash with decorator' do + it "renders hash with decorator" do assert_xml_equal(decorator.new(songs).to_xml, xml_doc) end end - describe '#from_json' do - it 'returns hash' do + describe "#from_json" do + it "returns hash" do _({}.extend(representer).from_xml(xml_doc)).must_equal songs end - it 'respects :exclude' do - assert_equal({ 'two' => "Can't Take Them All" }, {}.extend(representer).from_xml(xml_doc, exclude: [:one])) + it "respects :exclude" do + assert_equal({"two" => "Can't Take Them All"}, {}.extend(representer).from_xml(xml_doc, exclude: [:one])) end - it 'respects :include' do - assert_equal({ 'one' => 'Graveyards' }, {}.extend(representer).from_xml(xml_doc, include: [:one])) + it "respects :include" do + assert_equal({"one" => "Graveyards"}, {}.extend(representer).from_xml(xml_doc, include: [:one])) end - it 'parses hash with decorator' do + it "parses hash with decorator" do _(decorator.new({}).from_xml(xml_doc)).must_equal songs end end @@ -550,23 +568,29 @@ module SongRepresenter class XmlHashTest < MiniTest::Spec # scalar, no object - describe 'plain text' do + describe "plain text" do representer!(module: Representable::XML) do hash :songs end - let(:doc) { 'The GargoyleBronx' } + let(:doc) { "The GargoyleBronx" } # to_xml it { - assert_xml_equal(OpenStruct.new(songs: { 'first' => 'The Gargoyle', - 'second' => 'Bronx' }).extend(representer).to_xml, doc) + assert_xml_equal( + OpenStruct.new( + songs: { + "first" => "The Gargoyle", + "second" => "Bronx" + } + ).extend(representer).to_xml, doc + ) } # FIXME: this NEVER worked! # it { OpenStruct.new.extend(representer).from_xml(doc).songs.must_equal({"first" => "The Gargoyle", "second" => "Bronx"}) } end - describe 'with objects' do + describe "with objects" do representer!(module: Representable::XML) do hash :songs, class: OpenStruct do property :title @@ -586,12 +610,14 @@ class XmlHashTest < MiniTest::Spec # to_xml it { - assert_xml_equal(OpenStruct.new( - songs: { - 'first' => OpenStruct.new(title: 'The Gargoyle'), - 'second' => OpenStruct.new(title: 'Bronx') - } - ).extend(representer).to_xml, doc) + assert_xml_equal( + OpenStruct.new( + songs: { + "first" => OpenStruct.new(title: "The Gargoyle"), + "second" => OpenStruct.new(title: "Bronx") + } + ).extend(representer).to_xml, doc + ) } # FIXME: this NEVER worked! # it { OpenStruct.new.extend(representer).from_xml(doc).songs.must_equal({"first" => "The Gargoyle", "second" => "Bronx"}) } diff --git a/test/yaml_test.rb b/test/yaml_test.rb index a1d88277..0500265e 100644 --- a/test/yaml_test.rb +++ b/test/yaml_test.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'test_helper' +require "test_helper" class YamlPublicMethodsTest < Minitest::Spec #--- @@ -12,18 +12,18 @@ class BandRepresenter < Representable::Decorator end let(:data) do - %(--- + %{--- id: 1 name: Rancid -) +} end - it { _(BandRepresenter.new(Band.new).from_yaml(data)[:id, :name]).must_equal [1, 'Rancid'] } - it { _(BandRepresenter.new(Band.new).parse(data)[:id, :name]).must_equal [1, 'Rancid'] } + it { _(BandRepresenter.new(Band.new).from_yaml(data)[:id, :name]).must_equal [1, "Rancid"] } + it { _(BandRepresenter.new(Band.new).parse(data)[:id, :name]).must_equal [1, "Rancid"] } #--- # to_yaml - let(:band) { Band.new('1', 'Rancid') } + let(:band) { Band.new("1", "Rancid") } it { _(BandRepresenter.new(band).to_yaml).must_equal data } it { _(BandRepresenter.new(band).render).must_equal data } @@ -41,17 +41,17 @@ def yaml_representer(&block) self.class.yaml_representer(&block) end - describe 'property' do + describe "property" do let(:yaml) { yaml_representer { property :best_song } } let(:album) do Album.new.tap do |album| - album.best_song = 'Liar' + album.best_song = "Liar" end end - describe '#to_yaml' do - it 'renders plain property' do + describe "#to_yaml" do + it "renders plain property" do _(album.extend(yaml).to_yaml).must_equal( "--- best_song: Liar @@ -59,7 +59,7 @@ def yaml_representer(&block) ) end - it 'always renders values into strings' do + it "always renders values into strings" do _(Album.new.tap { |a| a.best_song = 8_675_309 }.extend(yaml).to_yaml).must_equal( "--- best_song: 8675309 @@ -68,19 +68,19 @@ def yaml_representer(&block) end end - describe '#from_yaml' do - it 'parses plain property' do + describe "#from_yaml" do + it "parses plain property" do _( album.extend(yaml).from_yaml( "--- best_song: This Song Is Recycled " ).best_song - ).must_equal 'This Song Is Recycled' + ).must_equal "This Song Is Recycled" end end - describe 'with :class and :extend' do + describe "with :class and :extend" do yaml_song = yaml_representer { property :name } let(:yaml_album) do Module.new do @@ -91,12 +91,12 @@ def yaml_representer(&block) let(:album) do Album.new.tap do |album| - album.best_song = Song.new('Liar') + album.best_song = Song.new("Liar") end end - describe '#to_yaml' do - it 'renders embedded typed property' do + describe "#to_yaml" do + it "renders embedded typed property" do _(album.extend(yaml_album).to_yaml).must_equal "--- best_song: name: Liar @@ -104,8 +104,8 @@ def yaml_representer(&block) end end - describe '#from_yaml' do - it 'parses embedded typed property' do + describe "#from_yaml" do + it "parses embedded typed property" do _( album.extend(yaml_album).from_yaml( "--- @@ -113,23 +113,23 @@ def yaml_representer(&block) name: Go With Me " ) - ).must_equal Album.new(nil, Song.new('Go With Me')) + ).must_equal Album.new(nil, Song.new("Go With Me")) end end end end - describe 'collection' do + describe "collection" do let(:yaml) { yaml_representer { collection :songs } } let(:album) do Album.new.tap do |album| - album.songs = ['Jackhammer', 'Terrible Man'] + album.songs = ["Jackhammer", "Terrible Man"] end end - describe '#to_yaml' do - it 'renders a block style list per default' do + describe "#to_yaml" do + it "renders a block style list per default" do _(album.extend(yaml).to_yaml).must_equal "--- songs: - Jackhammer @@ -137,7 +137,7 @@ def yaml_representer(&block) " end - it 'renders a flow style list when :style => :flow set' do + it "renders a flow style list when :style => :flow set" do yaml = yaml_representer { collection :songs, style: :flow } _(album.extend(yaml).to_yaml).must_equal "--- songs: [Jackhammer, Terrible Man] @@ -145,8 +145,8 @@ def yaml_representer(&block) end end - describe '#from_yaml' do - it 'parses a block style list' do + describe "#from_yaml" do + it "parses a block style list" do _( album.extend(yaml).from_yaml( "--- @@ -154,20 +154,20 @@ def yaml_representer(&block) - Off Key Melody - Sinking" ) - ).must_equal Album.new(['Off Key Melody', 'Sinking']) + ).must_equal Album.new(["Off Key Melody", "Sinking"]) end - it 'parses a flow style list' do + it "parses a flow style list" do _( album.extend(yaml).from_yaml( "--- songs: [Off Key Melody, Sinking]" ) - ).must_equal Album.new(['Off Key Melody', 'Sinking']) + ).must_equal Album.new(["Off Key Melody", "Sinking"]) end end - describe 'with :class and :extend' do + describe "with :class and :extend" do let(:yaml_album) do Module.new do include Representable::YAML @@ -178,10 +178,10 @@ def yaml_representer(&block) end end - let(:album) { Album.new([Song.new('Liar', 1), Song.new('What I Know', 2)]) } + let(:album) { Album.new([Song.new("Liar", 1), Song.new("What I Know", 2)]) } - describe '#to_yaml' do - it 'renders collection of typed property' do + describe "#to_yaml" do + it "renders collection of typed property" do _(album.extend(yaml_album).to_yaml).must_equal "--- songs: - name: Liar @@ -192,8 +192,8 @@ def yaml_representer(&block) end end - describe '#from_yaml' do - it 'parses collection of typed property' do + describe "#from_yaml" do + it "parses collection of typed property" do _( album.extend(yaml_album).from_yaml( "--- @@ -203,7 +203,7 @@ def yaml_representer(&block) - name: Three Way Dance track: 5" ) - ).must_equal Album.new([Song.new('One Shot Deal', 4), Song.new('Three Way Dance', 5)]) + ).must_equal Album.new([Song.new("One Shot Deal", 4), Song.new("Three Way Dance", 5)]) end end end