File: coerce_spec.rb

package info (click to toggle)
ruby-virtus 2.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 660 kB
  • sloc: ruby: 4,378; makefile: 2
file content (91 lines) | stat: -rw-r--r-- 2,057 bytes parent folder | download | duplicates (3)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
require 'spec_helper'

describe Virtus::Attribute::EmbeddedValue, '#coerce' do
  subject { object.coerce(input) }

  let(:object)  { described_class.build(model, options) }
  let(:options) { {} }

  context 'when primitive is OpenStruct' do
    let(:model)  { OpenStruct }

    context 'when input is an attribute hash' do
      let(:input) { Hash[name: 'Piotr', age: 30] }

      it { is_expected.to be_instance_of(model) }

      describe '#name' do
        subject { super().name }
        it { is_expected.to eql('Piotr') }
      end

      describe '#age' do
        subject { super().age }
        it { is_expected.to eql(30) }
      end
    end

    context 'when input is nil' do
      let(:input) { nil }

      it { is_expected.to be(nil) }
    end

    context 'when input is a model instance' do
      let(:input) { OpenStruct.new }

      it { is_expected.to be(input) }
    end
  end

  context 'when primitive is Struct' do
    let(:model)  { Struct.new(:name, :age) }

    context 'when input is an attribute hash' do
      let(:input) { ['Piotr', 30] }

      it { is_expected.to be_instance_of(model) }

      describe '#name' do
        subject { super().name }
        it { is_expected.to eql('Piotr') }
      end

      describe '#age' do
        subject { super().age }
        it { is_expected.to eql(30) }
      end
    end

    context 'when input is nil' do
      let(:input) { nil }

      it { is_expected.to be(nil) }
    end

    context 'when input is a model instance' do
      let(:input) { model.new('Piotr', 30) }

      it { is_expected.to be(input) }
    end
  end

  context 'when :strict mode is enabled' do
    let(:model)   { Struct.new(:name) }
    let(:options) { { :strict => true } }

    context 'when input is coercible' do
      let(:input) { ['Piotr'] }

      it { is_expected.to eql(model.new('Piotr')) }
    end

    context 'when input is not coercible' do
      let(:input) { nil }

      it 'raises error' do
        expect { subject }.to raise_error(Virtus::CoercionError)
      end
    end
  end
end