summaryrefslogtreecommitdiff
path: root/spec/hashie/extensions/ignore_undeclared_spec.rb
blob: 6f2d818f16a86caac468b7456b93c535eea1c4b4 (plain)
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
require 'spec_helper'

describe Hashie::Extensions::IgnoreUndeclared do
  context 'included in Trash' do
    class ForgivingTrash < Hashie::Trash
      include Hashie::Extensions::IgnoreUndeclared
      property :city
      property :state, from: :provence
      property :str_state, from: 'str_provence'
    end

    subject { ForgivingTrash }

    it 'silently ignores undeclared properties on initialization' do
      expect { subject.new(city: 'Toronto', provence: 'ON', country: 'Canada') }.to_not raise_error
    end

    it 'works with translated properties (with symbol keys)' do
      expect(subject.new(provence: 'Ontario').state).to eq('Ontario')
    end

    it 'works with translated properties (with string keys)' do
      expect(subject.new('str_provence' => 'Ontario').str_state).to eq('Ontario')
    end

    it 'requires properties to be declared on assignment' do
      hash = subject.new(city: 'Toronto')
      expect { hash.country = 'Canada' }.to raise_error(NoMethodError)
    end

    context 'with a default value' do
      let(:test) do
        Class.new(Hashie::Trash) do
          include Hashie::Extensions::IgnoreUndeclared

          property :description, from: :desc, default: ''
        end
      end

      include_examples 'Dash default handling', :description, :desc
    end
  end

  context 'combined with DeepMerge' do
    class ForgivingTrashWithMerge < Hashie::Trash
      include Hashie::Extensions::DeepMerge
      include Hashie::Extensions::IgnoreUndeclared
      property :some_key
    end

    it 'deep merges' do
      class ForgivingTrashWithMergeAndProperty < ForgivingTrashWithMerge
        property :some_other_key
      end
      hash = ForgivingTrashWithMergeAndProperty.new(some_ignored_key: 17, some_key: 12)
      expect(hash.deep_merge(some_other_key: 55, some_ignored_key: 18))
        .to eq(some_key: 12, some_other_key: 55)
    end
  end
end