File: coercion_test.rb

package info (click to toggle)
ruby-representable 3.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 952 kB
  • sloc: ruby: 6,495; makefile: 4
file content (63 lines) | stat: -rw-r--r-- 2,237 bytes parent folder | download
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
# frozen_string_literal: true

require 'test_helper'
require 'representable/coercion'

class CoercionTest < Minitest::Spec
  representer! do
    include Representable::Coercion

    property :title # no coercion.
    property :length, type: Representable::Coercion::Types::Params::Float

    property :band, class: OpenStruct do
      property :founded, type: Representable::Coercion::Types::Params::Integer
    end

    collection :songs, class: OpenStruct do
      property :ok, type: Representable::Coercion::Types::Params::Bool
    end
  end

  let(:album) do
    OpenStruct.new(title: 'Dire Straits', length: 41.34,
                   band: OpenStruct.new(founded: '1977'),
                   songs: [OpenStruct.new(ok: 1), OpenStruct.new(ok: 0)])
  end

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

  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: Representable::Coercion::Types::Params::Float,
                        parse_filter: ->(input, _options) { "#{input}.1" }, # happens BEFORE coercer.
                        render_filter: ->(fragment, *) { "#{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