File: defining_attributes_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 (86 lines) | stat: -rw-r--r-- 2,392 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
require 'spec_helper'

describe "virtus attribute definitions" do

  before do
    module Examples
      class Person
        include Virtus

        attribute :name, String
        attribute :age, Integer
        attribute :doctor, Boolean
        attribute :salary, Decimal
      end

      class Manager < Person

      end
    end
  end

  subject(:person) { Examples::Person.new(attributes) }

  let(:attributes) { {} }

  specify 'virtus creates accessor methods' do
    person.name = 'Peter'
    expect(person.name).to eq('Peter')
  end

  specify 'the constructor accepts a hash for mass-assignment' do
    john = Examples::Person.new(:name => 'John', :age => 13)
    expect(john.name).to eq('John')
    expect(john.age).to eq(13)
  end

  specify 'Boolean attributes have a predicate method' do
    expect(person).not_to be_doctor
    person.doctor = true
    expect(person).to be_doctor
  end

  context 'with attributes' do
    let(:attributes) { {:name => 'Jane', :age => 45, :doctor => true, :salary => 4500} }

    specify "#attributes returns the object's attributes as a hash" do
      expect(person.attributes).to eq(attributes)
    end

    specify "#to_hash returns the object's attributes as a hash" do
      expect(person.to_hash).to eq(attributes)
    end

    specify "#to_h returns the object's attributes as a hash" do
      expect(person.to_h).to eql(attributes)
    end
  end

  context 'inheritance' do
    specify 'inherits all the attributes from the base class' do
      fred = Examples::Manager.new(:name => 'Fred', :age => 29)
      expect(fred.name).to eq('Fred')
      expect(fred.age).to eq(29)
    end

    specify 'lets you add attributes to the base class at runtime' do
      frank = Examples::Manager.new(:name => 'Frank')
      Examples::Person.attribute :just_added, String
      frank.just_added = 'it works!'
      expect(frank.just_added).to eq('it works!')
    end

    specify 'lets you add attributes to the subclass at runtime' do
      person_jack = Examples::Person.new(:name => 'Jack')
      manager_frank = Examples::Manager.new(:name => 'Frank')

      Examples::Manager.attribute :just_added, String

      manager_frank.just_added = 'awesome!'

      expect(manager_frank.just_added).to eq('awesome!')
      expect(person_jack).not_to respond_to(:just_added)
      expect(person_jack).not_to respond_to(:just_added=)
    end
  end
end