summaryrefslogtreecommitdiff
path: root/spec/ruby/core/kernel/freeze_spec.rb
blob: fa32d321cffb790d168b7e202a8927c3ba4d71ff (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
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_relative '../../spec_helper'
require_relative 'fixtures/classes'

describe "Kernel#freeze" do
  it "prevents self from being further modified" do
    o = mock('o')
    o.frozen?.should be_false
    o.freeze
    o.frozen?.should be_true
  end

  it "returns self" do
    o = Object.new
    o.freeze.should equal(o)
  end

  describe "on integers" do
    it "has no effect since they are already frozen" do
      1.frozen?.should be_true
      1.freeze

      bignum = bignum_value
      bignum.frozen?.should be_true
      bignum.freeze
    end
  end

  describe "on a Float" do
    it "has no effect since it is already frozen" do
      1.2.frozen?.should be_true
      1.2.freeze
    end
  end

  describe "on a Symbol" do
    it "has no effect since it is already frozen" do
      :sym.frozen?.should be_true
      :sym.freeze
    end
  end

  describe "on true, false and nil" do
    it "has no effect since they are already frozen" do
      nil.frozen?.should be_true
      true.frozen?.should be_true
      false.frozen?.should be_true

      nil.freeze
      true.freeze
      false.freeze
    end
  end

  describe "on a Complex" do
    it "has no effect since it is already frozen" do
      c = Complex(1.3, 3.1)
      c.frozen?.should be_true
      c.freeze
    end
  end

  describe "on a Rational" do
    it "has no effect since it is already frozen" do
      r = Rational(1, 3)
      r.frozen?.should be_true
      r.freeze
    end
  end

  it "causes mutative calls to raise RuntimeError" do
    o = Class.new do
      def mutate; @foo = 1; end
    end.new
    o.freeze
    -> {o.mutate}.should raise_error(RuntimeError)
  end

  it "causes instance_variable_set to raise RuntimeError" do
    o = Object.new
    o.freeze
    -> {o.instance_variable_set(:@foo, 1)}.should raise_error(RuntimeError)
  end

  it "freezes an object's singleton class" do
    o = Object.new
    c = o.singleton_class
    c.frozen?.should == false
    o.freeze
    c.frozen?.should == true
  end
end