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 92 93 94 95 96 97 98 99 100 101 102
|
require 'spec_helper'
describe Hashie::Extensions::KeyConversion do
subject do
klass = Class.new(::Hash)
klass.send :include, Hashie::Extensions::KeyConversion
klass
end
let(:instance){ subject.new }
describe '#stringify_keys!' do
it 'should convert keys to strings' do
instance[:abc] = 'abc'
instance[123] = '123'
instance.stringify_keys!
(instance.keys & %w(abc 123)).size.should == 2
end
it 'should do deep conversion within nested hashes' do
instance[:ab] = subject.new
instance[:ab][:cd] = subject.new
instance[:ab][:cd][:ef] = 'abcdef'
instance.stringify_keys!
instance.should == {'ab' => {'cd' => {'ef' => 'abcdef'}}}
end
it 'should do deep conversion within nested arrays' do
instance[:ab] = []
instance[:ab] << subject.new
instance[:ab] << subject.new
instance[:ab][0][:cd] = 'abcd'
instance[:ab][1][:ef] = 'abef'
instance.stringify_keys!
instance.should == {'ab' => [{'cd' => 'abcd'}, {'ef' => 'abef'}]}
end
it 'should return itself' do
instance.stringify_keys!.should == instance
end
end
describe '#stringify_keys' do
it 'should convert keys to strings' do
instance[:abc] = 'def'
copy = instance.stringify_keys
copy['abc'].should == 'def'
end
it 'should not alter the original' do
instance[:abc] = 'def'
copy = instance.stringify_keys
instance.keys.should == [:abc]
copy.keys.should == %w(abc)
end
end
describe '#symbolize_keys!' do
it 'should convert keys to symbols' do
instance['abc'] = 'abc'
instance['def'] = 'def'
instance.symbolize_keys!
(instance.keys & [:abc, :def]).size.should == 2
end
it 'should do deep conversion within nested hashes' do
instance['ab'] = subject.new
instance['ab']['cd'] = subject.new
instance['ab']['cd']['ef'] = 'abcdef'
instance.symbolize_keys!
instance.should == {:ab => {:cd => {:ef => 'abcdef'}}}
end
it 'should do deep conversion within nested arrays' do
instance['ab'] = []
instance['ab'] << subject.new
instance['ab'] << subject.new
instance['ab'][0]['cd'] = 'abcd'
instance['ab'][1]['ef'] = 'abef'
instance.symbolize_keys!
instance.should == {:ab => [{:cd => 'abcd'}, {:ef => 'abef'}]}
end
it 'should return itself' do
instance.symbolize_keys!.should == instance
end
end
describe '#symbolize_keys' do
it 'should convert keys to symbols' do
instance['abc'] = 'def'
copy = instance.symbolize_keys
copy[:abc].should == 'def'
end
it 'should not alter the original' do
instance['abc'] = 'def'
copy = instance.symbolize_keys
instance.keys.should == ['abc']
copy.keys.should == [:abc]
end
end
end
|