1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
require "test_helper"
class StopWhenIncomingObjectFragmentIsNilTest < Minitest::Spec
Album = Struct.new(:id, :songs)
Song = Struct.new(:title)
representer!(decorator: true) do
property :id
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
end
end
it do
album = Album.new
representer.new(album).from_hash({"id"=>1, "songs"=>[{"title"=>"Walkie Talkie"}]}).songs.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"]
end
end
class RenderPipelineOptionTest < Minitest::Spec
Album = Struct.new(:id, :songs)
NilToNA = ->(input, options) { input.nil? ? "n/a" : input }
representer!(decorator: true) do
property :id, render_pipeline: ->(input, options) do
Representable::Pipeline[*render_functions.insert(2, options[:options][:user_options][:function])]
end
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 "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.
end
end
class ParsePipelineOptionTest < Minitest::Spec
Album = Struct.new(:id, :songs)
NilToNA = ->(input, options) { input.nil? ? "n/a" : input }
representer!(decorator: true) do
property :id, parse_pipeline: ->(input, options) do
Representable::Pipeline[*parse_functions.insert(3, options[:options][:user_options][:function])].extend(Representable::Pipeline::Debug)
end
end
it { 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 "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.
end
end
|