Sha256: e3498b01d5da717cb4572ddc0dc8ab8d3ab2c100863fc315a4ade6a99152f88c

Contents?: true

Size: 1.73 KB

Versions: 20

Compression:

Stored size: 1.73 KB

Contents

require 'test_helper'
require 'representable/coercion'

class VirtusCoercionTest < MiniTest::Spec
  representer! do
    include Representable::Coercion

    property :title # no coercion.
    property :length, :type => Float

    property :band, :class => OpenStruct do
      property :founded, :type => Integer
    end

    collection :songs, :class => OpenStruct do
      property :ok, :type => Virtus::Attribute::Boolean
    end
  end

  let (:album) { OpenStruct.new(:title => "Dire Straits", :length => 41.34,
    :band  => OpenStruct.new(:founded => "1977"),
    :songs => [OpenStruct.new(:ok => 1), OpenStruct.new(:ok => 0)]) }

  it { album.extend(representer).to_hash.must_equal({"title"=>"Dire Straits", "length"=>41.34, "band"=>{"founded"=>1977}, "songs"=>[{"ok"=>true}, {"ok"=>false}]}) }

  it {
    album = OpenStruct.new
    album.extend(representer)
    album.from_hash({"title"=>"Dire Straits", "length"=>"41.34", "band"=>{"founded"=>"1977"}, "songs"=>[{"ok"=>1}, {"ok"=>0}]})

    # it
    album.length.must_equal 41.34
    album.band.founded.must_equal 1977
    album.songs[0].ok.must_equal true
  }


  describe "with user :parse_filter and :render_filter" do
    representer! do
      include Representable::Coercion

      property :length, :type => Float,
      :parse_filter  => lambda { |fragment, doc, options| "#{fragment}.1" }, # happens BEFORE coercer.
      :render_filter => lambda { |fragment, doc, options| "#{fragment}.1" }
    end

    # user's :parse_filter(s) are run before coercion.
    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}) }
  end
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
representable-2.3.0 test/coercion_test.rb
representable-2.2.3 test/coercion_test.rb
representable-2.2.2 test/coercion_test.rb
representable-2.2.1 test/coercion_test.rb
representable-2.2.0 test/coercion_test.rb
representable-2.1.8 test/coercion_test.rb
representable-2.1.7 test/coercion_test.rb
representable-2.1.6 test/coercion_test.rb
representable-2.1.5 test/coercion_test.rb
representable-2.1.4 test/coercion_test.rb
representable-2.1.3 test/coercion_test.rb
representable-2.1.1 test/coercion_test.rb
representable-2.1.0 test/coercion_test.rb
representable-2.0.4 test/coercion_test.rb
representable-2.0.3 test/coercion_test.rb
representable-2.0.2 test/coercion_test.rb
representable-2.0.1 test/coercion_test.rb
representable-2.0.0 test/coercion_test.rb
representable-2.0.0.rc2 test/coercion_test.rb
representable-2.0.0.rc1 test/coercion_test.rb