File: objectified_hash_spec.rb

package info (click to toggle)
ruby-gitlab 5.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,660 kB
  • sloc: ruby: 12,582; makefile: 7; sh: 4
file content (72 lines) | stat: -rw-r--r-- 1,966 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
64
65
66
67
68
69
70
71
72
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::ObjectifiedHash do
  before do
    @hash = { a: 1, b: 2, 'string' => 'string', symbol: :symbol, array: ['string', { a: 1, b: 2 }] }
    @oh = described_class.new @hash
  end

  describe 'Hash behavior' do
    let(:hash) { { foo: 'bar' } }
    let(:oh) { described_class.new(hash) }

    it 'allows to call Hash methods' do
      expect(oh['foo']).to eq('bar')
      expect(oh.merge(key: :value)).to eq('foo' => 'bar', key: :value)
    end

    it 'warns about calling Hash methods' do
      warning = "WARNING: Please convert ObjectifiedHash object to hash before calling Hash methods on it.\n"
      expect { oh.values }.to output(warning).to_stderr
    end
  end

  it 'objectifies a hash' do
    expect(@oh.a).to eq(@hash[:a])
    expect(@oh.b).to eq(@hash[:b])
  end

  it 'objectifies a hash contained in an array' do
    expect(@oh.array[1].a).to eq(@hash[:array][1][:a])
    expect(@oh.array[1].b).to eq(@hash[:array][1][:b])
    expect(@oh.array[0]).to eq(@hash[:array][0])
  end

  it 'supports legacy addressing mode' do
    expect(@oh['a']).to eq(@hash[:a])
    expect(@oh['b']).to eq(@hash[:b])
  end

  describe '#to_hash' do
    it 'returns an original hash' do
      expect(@oh.to_hash).to eq(@hash)
    end

    it 'has an alias #to_h' do
      expect(@oh).to respond_to(:to_h)
    end
  end

  describe '#inspect' do
    it 'returns a formatted string' do
      pretty_string = "#<#{@oh.class.name}:#{@oh.object_id} {hash: #{@hash}}"
      expect(@oh.inspect).to eq(pretty_string)
    end
  end

  describe '#respond_to' do
    it 'returns true for methods object responds to through method_missing' do
      expect(@oh).to respond_to(:a)
    end

    it 'allows to use a symbol to reference a method' do
      expect(@oh).to respond_to(:symbol)
    end

    it 'allows to use a string to reference a method' do
      expect(@oh).to respond_to('string')
    end
  end
end