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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
|
require 'spec_helper'
describe Hashie::Mash do
subject { Hashie::Mash.new }
include_context 'with a logger'
it 'inherits from Hash' do
expect(subject.is_a?(Hash)).to be_truthy
end
it 'sets hash values through method= calls' do
subject.test = 'abc'
expect(subject['test']).to eq 'abc'
end
it 'retrieves set values through method calls' do
subject['test'] = 'abc'
expect(subject.test).to eq 'abc'
end
it 'retrieves set values through blocks' do
subject['test'] = 'abc'
value = nil
subject.[]('test') { |v| value = v }
expect(value).to eq 'abc'
end
it 'retrieves set values through blocks with method calls' do
subject['test'] = 'abc'
value = nil
subject.test { |v| value = v }
expect(value).to eq 'abc'
end
it 'tests for already set values when passed a ? method' do
expect(subject.test?).to be_falsy
subject.test = 'abc'
expect(subject.test?).to be_truthy
end
it 'returns false on a ? method if a value has been set to nil or false' do
subject.test = nil
expect(subject).not_to be_test
subject.test = false
expect(subject).not_to be_test
end
it 'makes all [] and []= into strings for consistency' do
subject['abc'] = 123
expect(subject.key?('abc')).to be_truthy
expect(subject['abc']).to eq 123
end
it 'has a to_s that is identical to its inspect' do
subject.abc = 123
expect(subject.to_s).to eq subject.inspect
end
it 'returns nil instead of raising an error for attribute-esque method calls' do
expect(subject.abc).to be_nil
end
it 'returns the default value if set like Hash' do
subject.default = 123
expect(subject.abc).to eq 123
end
it 'gracefully handles being accessed with arguments' do
expect(subject.abc('foobar')).to eq nil
subject.abc = 123
expect(subject.abc('foobar')).to eq 123
end
# Added due to downstream gems assuming indifferent access to be true for Mash
# When this is not, bump major version so that downstream gems can target
# correct version and fix accordingly.
# See https://github.com/hashie/hashie/pull/197
it 'maintains indifferent access when nested' do
subject[:a] = { b: 'c' }
expect(subject[:a][:b]).to eq 'c'
expect(subject[:a]['b']).to eq 'c'
end
it 'returns a Hashie::Mash when passed a bang method to a non-existenct key' do
expect(subject.abc!.is_a?(Hashie::Mash)).to be_truthy
end
it 'returns the existing value when passed a bang method for an existing key' do
subject.name = 'Bob'
expect(subject.name!).to eq 'Bob'
end
it 'returns a Hashie::Mash when passed an under bang method to a non-existenct key' do
expect(subject.abc_.is_a?(Hashie::Mash)).to be_truthy
end
it 'returns the existing value when passed an under bang method for an existing key' do
subject.name = 'Bob'
expect(subject.name_).to eq 'Bob'
end
it '#initializing_reader returns a Hashie::Mash when passed a non-existent key' do
expect(subject.initializing_reader(:abc).is_a?(Hashie::Mash)).to be_truthy
end
it 'allows for multi-level assignment through bang methods' do
subject.author!.name = 'Michael Bleigh'
expect(subject.author).to eq Hashie::Mash.new(name: 'Michael Bleigh')
subject.author!.website!.url = 'http://www.mbleigh.com/'
expect(subject.author.website).to eq Hashie::Mash.new(url: 'http://www.mbleigh.com/')
end
it 'allows for multi-level under bang testing' do
expect(subject.author_.website_.url).to be_nil
expect(subject.author_.website_.url?).to eq false
expect(subject.author).to be_nil
end
it 'does not call super if id is not a key' do
expect(subject.id).to eq nil
end
it 'returns the value if id is a key' do
subject.id = 'Steve'
expect(subject.id).to eq 'Steve'
end
it 'does not call super if type is not a key' do
expect(subject.type).to eq nil
end
it 'returns the value if type is a key' do
subject.type = 'Steve'
expect(subject.type).to eq 'Steve'
end
include_context 'with a logger' do
it 'logs a warning when overriding built-in methods' do
Hashie::Mash.new('object_id' => { 'two' => 2 })
expect(logger_output).to match('Hashie::Mash#object_id')
end
it 'can set keys more than once and does not warn when doing so' do
mash = Hashie::Mash.new
mash[:test_key] = 'Test value'
expect { mash[:test_key] = 'A new value' }.not_to raise_error
expect(logger_output).to be_empty
end
it 'does not write to the logger when warnings are disabled' do
mash_class = Class.new(Hashie::Mash) do
disable_warnings
end
mash_class.new('trust' => { 'two' => 2 })
expect(logger_output).to be_empty
end
it 'does not write to the logger when setting most affixed keys' do
underbang = Hashie::Mash.new('foo_' => 'foo')
bang = Hashie::Mash.new('foo!' => 'foo')
query = Hashie::Mash.new('foo?' => 'foo')
expect(logger_output).to be_empty
expect(underbang.foo_).to eq 'foo'
expect(bang.foo!).to eq 'foo'
expect(query.foo?).to eq 'foo'
end
it 'warns when setting a key that looks like a setter' do
setter = Hashie::Mash.new('foo=' => 'foo')
expect(logger_output).to match 'Hashie::Mash#foo='
expect('setter.foo=').not_to parse_as_valid_ruby
setter.foo = 'bar'
expect(setter.to_h).to eq 'foo=' => 'foo'
end
it 'cannot disable logging on the base Mash' do
expected_error = Hashie::Extensions::KeyConflictWarning::CannotDisableMashWarnings
expect { Hashie::Mash.disable_warnings }.to raise_error(expected_error)
end
it 'carries over the disable for warnings on grandchild classes' do
child_class = Class.new(Hashie::Mash) do
disable_warnings
end
grandchild_class = Class.new(child_class)
grandchild_class.new('trust' => { 'two' => 2 })
expect(logger_output).to be_empty
end
it 'writes to logger when a key is overridden that is not ignored' do
mash_class = Class.new(Hashie::Mash) do
disable_warnings :merge
end
mash_class.new('address' => { 'zip' => '90210' })
expect(logger_output).not_to be_empty
end
it 'does not write to logger when a key is overridden that is ignored' do
mash_class = Class.new(Hashie::Mash) do
disable_warnings :zip
end
mash_class.new('address' => { 'zip' => '90210' })
expect(logger_output).to be_empty
end
it 'carries over the ignored warnings list for warnings on grandchild classes' do
child_class = Class.new(Hashie::Mash) do
disable_warnings :zip, :merge
end
grandchild_class = Class.new(child_class)
grandchild_class.new('address' => { 'zip' => '90210' }, 'merge' => true)
expect(grandchild_class.disabled_warnings).to eq(%i[zip merge])
expect(logger_output).to be_empty
end
context 'multiple disable_warnings calls' do
context 'calling disable_warnings multiple times with parameters' do
it 'appends each new parameter to the ignore list' do
child_class = Class.new(Hashie::Mash) do
disable_warnings :zip
disable_warnings :merge
disable_warnings :cycle
end
expect(child_class.disabled_warnings).to eq(%i[zip merge cycle])
end
end
context 'calling disable_warnings without keys after calling with keys' do
it 'uses the last call to determine the ignore list' do
child_class = Class.new(Hashie::Mash) do
disable_warnings :zip
disable_warnings
end
child_class.new('address' => { 'zip' => '90210' }, 'merge' => true, 'cycle' => 'bi')
expect(child_class.disabled_warnings).to eq([])
expect(logger_output).to be_empty
end
end
context 'calling disable_parameters with keys after calling without keys' do
it 'only ignores logging for ignored methods' do
child_class = Class.new(Hashie::Mash) do
disable_warnings
disable_warnings :zip
end
child_class.new('address' => { 'zip' => '90210' }, 'merge' => true)
expect(logger_output).to match(/#{child_class}#merge/)
expect(logger_output).not_to match(/#{child_class}#zip/)
end
end
end
end
context 'updating' do
subject do
described_class.new(
first_name: 'Michael',
last_name: 'Bleigh',
details: {
email: 'michael@asf.com',
address: 'Nowhere road'
}
)
end
describe '#deep_update' do
it 'recursively Hashie::Mash Hashie::Mashes and hashes together' do
subject.deep_update(details: { email: 'michael@intridea.com', city: 'Imagineton' })
expect(subject.first_name).to eq 'Michael'
expect(subject.details.email).to eq 'michael@intridea.com'
expect(subject.details.address).to eq 'Nowhere road'
expect(subject.details.city).to eq 'Imagineton'
end
it 'converts values only once' do
class ConvertedMash < Hashie::Mash
end
rhs = ConvertedMash.new(email: 'foo@bar.com')
expect(subject).to receive(:convert_value).exactly(1).times
subject.deep_update(rhs)
end
it 'makes #update deep by default' do
expect(subject.update(details: { address: 'Fake street' })).to eql(subject)
expect(subject.details.address).to eq 'Fake street'
expect(subject.details.email).to eq 'michael@asf.com'
end
it 'clones before a #deep_merge' do
duped = subject.deep_merge(details: { address: 'Fake street' })
expect(duped).not_to eql(subject)
expect(duped.details.address).to eq 'Fake street'
expect(subject.details.address).to eq 'Nowhere road'
expect(duped.details.email).to eq 'michael@asf.com'
end
it 'default #merge is deep' do
duped = subject.merge(details: { email: 'michael@intridea.com' })
expect(duped).not_to eql(subject)
expect(duped.details.email).to eq 'michael@intridea.com'
expect(duped.details.address).to eq 'Nowhere road'
end
# http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-update
it 'accepts a block' do
duped = subject.merge(details: { address: 'Pasadena CA' }) do |_, oldv, newv|
[oldv, newv].join(', ')
end
expect(duped.details.address).to eq 'Nowhere road, Pasadena CA'
end
it 'copies values for non-duplicate keys when a block is supplied' do
m_hash = { details: { address: 'Pasadena CA', state: 'West Thoughtleby' } }
duped = subject.merge(m_hash) { |_, oldv, _| oldv }
expect(duped.details.address).to eq 'Nowhere road'
expect(duped.details.state).to eq 'West Thoughtleby'
end
it 'does not raise an exception when default_proc raises an error' do
hash = described_class.new(a: 1) { |_k, _v| raise('Should not be raise I') }
other_has = described_class.new(a: 2, b: 2) { |_k, _v| raise('Should not be raise II') }
expected_hash = described_class.new(a: 2, b: 2)
res = hash.merge(other_has)
expect(res).to eq(expected_hash)
end
end
describe 'shallow update' do
it 'shallowly Hashie::Mash Hashie::Mashes and hashes together' do
expect(subject.shallow_update(details: { email: 'michael@intridea.com',
city: 'Imagineton' })).to eql(subject)
expect(subject.first_name).to eq 'Michael'
expect(subject.details.email).to eq 'michael@intridea.com'
expect(subject.details.address).to be_nil
expect(subject.details.city).to eq 'Imagineton'
end
it 'clones before a #regular_merge' do
duped = subject.shallow_merge(details: { address: 'Fake street' })
expect(duped).not_to eql(subject)
end
it 'default #merge is shallow' do
duped = subject.shallow_merge(details: { address: 'Fake street' })
expect(duped.details.address).to eq 'Fake street'
expect(subject.details.address).to eq 'Nowhere road'
expect(duped.details.email).to be_nil
end
end
describe '#replace' do
before do
subject.replace(
middle_name: 'Cain',
details: { city: 'Imagination' }
)
end
it 'returns self' do
expect(subject.replace(foo: 'bar').to_hash).to eq('foo' => 'bar')
end
it 'sets all specified keys to their corresponding values' do
expect(subject.middle_name?).to be_truthy
expect(subject.details?).to be_truthy
expect(subject.middle_name).to eq 'Cain'
expect(subject.details.city?).to be_truthy
expect(subject.details.city).to eq 'Imagination'
end
it 'leaves only specified keys' do
expect(subject.keys.sort).to eq %w[details middle_name]
expect(subject.first_name?).to be_falsy
expect(subject).not_to respond_to(:first_name)
expect(subject.last_name?).to be_falsy
expect(subject).not_to respond_to(:last_name)
end
end
describe 'delete' do
it 'deletes with String key' do
subject.delete('details')
expect(subject.details).to be_nil
expect(subject).not_to be_respond_to :details
end
it 'deletes with Symbol key' do
subject.delete(:details)
expect(subject.details).to be_nil
expect(subject).not_to be_respond_to :details
end
end
end
it 'converts hash assignments into Hashie::Mashes' do
subject.details = { email: 'randy@asf.com', address: { state: 'TX' } }
expect(subject.details.email).to eq 'randy@asf.com'
expect(subject.details.address.state).to eq 'TX'
end
it 'does not convert the type of Hashie::Mashes childs to Hashie::Mash' do
class MyMash < Hashie::Mash
end
record = MyMash.new
record.son = MyMash.new
expect(record.son.class).to eq MyMash
end
it 'does not change the class of Mashes when converted' do
class SubMash < Hashie::Mash
end
record = Hashie::Mash.new
son = SubMash.new
record['submash'] = son
expect(record['submash']).to be_kind_of(SubMash)
end
it 'respects the class when passed a bang method for a non-existent key' do
record = Hashie::Mash.new
expect(record.non_existent!).to be_kind_of(Hashie::Mash)
class SubMash < Hashie::Mash
end
son = SubMash.new
expect(son.non_existent!).to be_kind_of(SubMash)
end
it 'respects the class when passed an under bang method for a non-existent key' do
record = Hashie::Mash.new
expect(record.non_existent_).to be_kind_of(Hashie::Mash)
class SubMash < Hashie::Mash
end
son = SubMash.new
expect(son.non_existent_).to be_kind_of(SubMash)
end
it 'respects the class when converting the value' do
record = Hashie::Mash.new
record.details = Hashie::Mash.new(email: 'randy@asf.com')
expect(record.details).to be_kind_of(Hashie::Mash)
end
it 'respects another subclass when converting the value' do
record = Hashie::Mash.new
class SubMash < Hashie::Mash
end
son = SubMash.new(email: 'foo@bar.com')
record.details = son
expect(record.details).to be_kind_of(SubMash)
end
describe '#respond_to?' do
subject do
Hashie::Mash.new(abc: 'def')
end
it 'responds to a normal method' do
expect(subject).to be_respond_to(:key?)
end
it 'responds to a set key' do
expect(subject).to be_respond_to(:abc)
expect(subject.method(:abc)).to_not be_nil
end
it 'responds to a set key with a suffix' do
%w[= ? ! _].each do |suffix|
expect(subject).to be_respond_to(:"abc#{suffix}")
end
end
it 'is able to access the suffixed key as a method' do
%w[= ? ! _].each do |suffix|
expect(subject.method(:"abc#{suffix}")).to_not be_nil
end
end
it 'responds to an unknown key with a suffix' do
%w[= ? ! _].each do |suffix|
expect(subject).to be_respond_to(:"xyz#{suffix}")
end
end
it 'is able to access an unknown suffixed key as a method' do
# See https://github.com/intridea/hashie/pull/285 for more information
pending_for(engine: 'ruby', versions: %w[2.2.0 2.2.1 2.2.2])
%w[= ? ! _].each do |suffix|
expect(subject.method(:"xyz#{suffix}")).to_not be_nil
end
end
it 'does not respond to an unknown key without a suffix' do
expect(subject).not_to be_respond_to(:xyz)
expect { subject.method(:xyz) }.to raise_error(NameError)
end
end
context '#initialize' do
it 'converts an existing hash to a Hashie::Mash' do
converted = Hashie::Mash.new(abc: 123, name: 'Bob')
expect(converted.abc).to eq 123
expect(converted.name).to eq 'Bob'
end
it 'converts hashes recursively into Hashie::Mashes' do
converted = Hashie::Mash.new(a: { b: 1, c: { d: 23 } })
expect(converted.a.is_a?(Hashie::Mash)).to be_truthy
expect(converted.a.b).to eq 1
expect(converted.a.c.d).to eq 23
end
it 'converts hashes in arrays into Hashie::Mashes' do
converted = Hashie::Mash.new(a: [{ b: 12 }, 23])
expect(converted.a.first.b).to eq 12
expect(converted.a.last).to eq 23
end
it 'converts an existing Hashie::Mash into a Hashie::Mash' do
initial = Hashie::Mash.new(name: 'randy', address: { state: 'TX' })
copy = Hashie::Mash.new(initial)
expect(initial.name).to eq copy.name
expect(initial.__id__).not_to eq copy.__id__
expect(copy.address.state).to eq 'TX'
copy.address.state = 'MI'
expect(initial.address.state).to eq 'TX'
expect(copy.address.__id__).not_to eq initial.address.__id__
end
it 'accepts a default block' do
initial = Hashie::Mash.new { |h, i| h[i] = [] }
expect(initial.default_proc).not_to be_nil
expect(initial.default).to be_nil
expect(initial.test).to eq []
expect(initial.test?).to be_truthy
end
it 'allows propagation of a default block' do
h = Hashie::Mash.new { |mash, key| mash[key] = mash.class.new(&mash.default_proc) }
expect { h[:x][:y][:z] = :xyz }.not_to raise_error
expect(h.x.y.z).to eq(:xyz)
expect(h[:x][:y][:z]).to eq(:xyz)
end
it 'allows assignment of an empty array in a default block' do
initial = Hashie::Mash.new { |h, k| h[k] = [] }
initial.hello << 100
expect(initial.hello).to eq [100]
initial['hi'] << 100
expect(initial['hi']).to eq [100]
end
it 'allows assignment of a non-empty array in a default block' do
initial = Hashie::Mash.new { |h, k| h[k] = [100] }
initial.hello << 200
expect(initial.hello).to eq [100, 200]
initial['hi'] << 200
expect(initial['hi']).to eq [100, 200]
end
it 'allows assignment of an empty hash in a default block' do
initial = Hashie::Mash.new { |h, k| h[k] = {} }
initial.hello[:a] = 100
expect(initial.hello).to eq Hashie::Mash.new(a: 100)
initial[:hi][:a] = 100
expect(initial[:hi]).to eq Hashie::Mash.new(a: 100)
end
it 'allows assignment of a non-empty hash in a default block' do
initial = Hashie::Mash.new { |h, k| h[k] = { a: 100 } }
initial.hello[:b] = 200
expect(initial.hello).to eq Hashie::Mash.new(a: 100, b: 200)
initial[:hi][:b] = 200
expect(initial[:hi]).to eq Hashie::Mash.new(a: 100, b: 200)
end
it 'converts Hashie::Mashes within Arrays back to Hashes' do
initial_hash = { 'a' => [{ 'b' => 12, 'c' => ['d' => 50, 'e' => 51] }, 23] }
converted = Hashie::Mash.new(initial_hash)
expect(converted.to_hash['a'].first.is_a?(Hashie::Mash)).to be_falsy
expect(converted.to_hash['a'].first.is_a?(Hash)).to be_truthy
expect(converted.to_hash['a'].first['c'].first.is_a?(Hashie::Mash)).to be_falsy
end
it 'only stringifies keys which can be converted to symbols' do
initial_hash = { 1 => 'a', ['b'] => 2, 'c' => 3, d: 4 }
converted = Hashie::Mash.new(initial_hash)
expect(converted).to eq(1 => 'a', ['b'] => 2, 'c' => 3, 'd' => 4)
end
it 'preserves keys which cannot be converted to symbols' do
initial_hash = { 1 => 'a', '1' => 'b', :'1' => 'c' }
converted = Hashie::Mash.new(initial_hash)
expect(converted).to eq(1 => 'a', '1' => 'c')
end
end
describe '#fetch' do
let(:hash) { { one: 1, other: false } }
let(:mash) { Hashie::Mash.new(hash) }
context 'when key exists' do
it 'returns the value' do
expect(mash.fetch(:one)).to eql(1)
end
it 'returns the value even if the value is falsy' do
expect(mash.fetch(:other)).to eql(false)
end
context 'when key has other than original but acceptable type' do
it 'returns the value' do
expect(mash.fetch('one')).to eql(1)
end
end
end
context 'when key does not exist' do
it 'raises KeyError' do
error = RUBY_VERSION =~ /1.8/ ? IndexError : KeyError
expect { mash.fetch(:two) }.to raise_error(error)
end
context 'with default value given' do
it 'returns default value' do
expect(mash.fetch(:two, 8)).to eql(8)
end
it 'returns default value even if it is falsy' do
expect(mash.fetch(:two, false)).to eql(false)
end
end
context 'with block given' do
it 'returns default value' do
expect(mash.fetch(:two) do
'block default value'
end).to eql('block default value')
end
end
end
end
describe '#to_hash' do
let(:hash) { { 'outer' => { 'inner' => 42 }, 'testing' => [1, 2, 3] } }
let(:mash) { Hashie::Mash.new(hash) }
it 'returns a standard Hash' do
expect(mash.to_hash).to be_a(::Hash)
end
it 'includes all keys' do
expect(mash.to_hash.keys).to eql(%w[outer testing])
end
it 'converts keys to symbols when symbolize_keys option is true' do
expect(mash.to_hash(symbolize_keys: true).keys).to include(:outer)
expect(mash.to_hash(symbolize_keys: true).keys).not_to include('outer')
end
it 'leaves keys as strings when symbolize_keys option is false' do
expect(mash.to_hash(symbolize_keys: false).keys).to include('outer')
expect(mash.to_hash(symbolize_keys: false).keys).not_to include(:outer)
end
it 'symbolizes keys recursively' do
expect(mash.to_hash(symbolize_keys: true)[:outer].keys).to include(:inner)
expect(mash.to_hash(symbolize_keys: true)[:outer].keys).not_to include('inner')
end
end
describe '#stringify_keys' do
it 'turns all keys into strings recursively' do
hash = Hashie::Mash[:a => 'hey', 123 => { 345 => 'hey' }]
hash.stringify_keys!
expect(hash).to eq Hashie::Hash['a' => 'hey', '123' => { '345' => 'hey' }]
end
end
describe '#values_at' do
let(:hash) { { 'key_one' => 1, :key_two => 2 } }
let(:mash) { Hashie::Mash.new(hash) }
context 'when the original type is given' do
it 'returns the values' do
expect(mash.values_at('key_one', :key_two)).to eq([1, 2])
end
end
context 'when a different, but acceptable type is given' do
it 'returns the values' do
expect(mash.values_at(:key_one, 'key_two')).to eq([1, 2])
end
end
context 'when a key is given that is not in the Mash' do
it 'returns nil for that value' do
expect(mash.values_at('key_one', :key_three)).to eq([1, nil])
end
end
end
describe '.load(filename, options = {})' do
let(:config) do
{
'production' => {
'foo' => 'production_foo'
}
}
end
let(:path) { 'database.yml' }
let(:parser) { double(:parser) }
subject { described_class.load(path, parser: parser) }
before do |ex|
unless ex.metadata == :test_cache
described_class.instance_variable_set('@_mashes', nil) # clean the cached mashes
end
end
context 'if the file exists' do
before do
expect(File).to receive(:file?).with(path).and_return(true)
expect(parser).to receive(:perform).with(path, {}).and_return(config)
end
it { is_expected.to be_a(Hashie::Mash) }
it 'return a Mash from a file' do
expect(subject.production).not_to be_nil
expect(subject.production.keys).to eq config['production'].keys
expect(subject.production.foo).to eq config['production']['foo']
end
it 'freeze the attribtues' do
expect { subject.production = {} }.to raise_exception(RuntimeError, /can't modify frozen/)
end
end
context 'if the fils does not exists' do
before do
expect(File).to receive(:file?).with(path).and_return(false)
end
it 'raise an ArgumentError' do
expect { subject }.to raise_exception(ArgumentError)
end
end
context 'if the file is passed as Pathname' do
require 'pathname'
let(:path) { Pathname.new('database.yml') }
before do
expect(File).to receive(:file?).with(path).and_return(true)
expect(parser).to receive(:perform).with(path, {}).and_return(config)
end
it 'return a Mash from a file' do
expect(subject.production.foo).to eq config['production']['foo']
end
end
describe 'results are cached' do
let(:parser) { double(:parser) }
subject { described_class.load(path, parser: parser) }
before do
expect(File).to receive(:file?).with(path).and_return(true)
expect(File).to receive(:file?).with("#{path}+1").and_return(true)
expect(parser).to receive(:perform).once.with(path, {}).and_return(config)
expect(parser).to receive(:perform).once.with("#{path}+1", {}).and_return(config)
end
it 'cache the loaded yml file', :test_cache do
2.times do
expect(subject).to be_a(described_class)
expect(described_class.load("#{path}+1", parser: parser)).to be_a(described_class)
end
expect(subject.object_id).to eq subject.object_id
end
end
context 'when the file has aliases in it' do
it 'can use the aliases and does not raise an error' do
mash = Hashie::Mash.load('spec/fixtures/yaml_with_aliases.yml')
expect(mash.company_a.accounts.admin.password).to eq('secret')
end
it 'can override the value of aliases' do
require 'psych'
if Gem::Version.new(Psych::VERSION) >= Gem::Version.new('5')
expect do
Hashie::Mash.load('spec/fixtures/yaml_with_aliases.yml', aliases: false)
end.to raise_error Psych::AliasesNotEnabled, /Alias parsing was not enabled/
else
expect do
Hashie::Mash.load('spec/fixtures/yaml_with_aliases.yml', aliases: false)
end.to raise_error Psych::BadAlias, /base_accounts/
end
end
end
context 'when the file has symbols' do
it 'can override the value of permitted_classes' do
mash = Hashie::Mash.load('spec/fixtures/yaml_with_symbols.yml', permitted_classes: [Symbol])
expect(mash.user_icon.width).to eq(200)
end
it 'uses defaults for permitted_classes' do
expect do
Hashie::Mash.load('spec/fixtures/yaml_with_symbols.yml')
end.to raise_error Psych::DisallowedClass, /Symbol/
end
it 'can override the value of permitted_symbols' do
mash = Hashie::Mash.load('spec/fixtures/yaml_with_symbols.yml',
permitted_classes: [Symbol],
permitted_symbols: %i[
user_icon
width
height
])
expect(mash.user_icon.width).to eq(200)
end
it 'raises an error on insufficient permitted_symbols' do
expect do
Hashie::Mash.load('spec/fixtures/yaml_with_symbols.yml',
permitted_classes: [Symbol],
permitted_symbols: %i[
user_icon
width
])
end.to raise_error Psych::DisallowedClass, /Symbol/
end
end
end
describe '#to_module(mash_method_name)' do
let(:mash) { described_class.new }
subject { Class.new.extend mash.to_module }
it 'defines a settings method on the klass class that extends the module' do
expect(subject).to respond_to(:settings)
expect(subject.settings).to eq mash
end
context 'when a settings_method_name is set' do
let(:mash_method_name) { 'config' }
subject { Class.new.extend mash.to_module(mash_method_name) }
it 'defines a settings method on the klass class that extends the module' do
expect(subject).to respond_to(mash_method_name.to_sym)
expect(subject.send(mash_method_name.to_sym)).to eq mash
end
end
end
describe '#reverse_merge' do
subject { described_class.new(a: 1, b: 2) }
it 'unifies strings and symbols' do
expect(subject.reverse_merge(a: 2).length).to eq 2
expect(subject.reverse_merge('a' => 2).length).to eq 2
end
it 'does not overwrite values' do
expect(subject.reverse_merge(a: 5).a).to eq subject.a
end
context 'when using with subclass' do
let(:subclass) { Class.new(Hashie::Mash) }
subject { subclass.new(a: 1) }
it 'creates an instance of subclass' do
expect(subject.reverse_merge(a: 5)).to be_kind_of(subclass)
end
end
end
describe '#invert' do
subject(:mash) { described_class.new(a: 'apple', b: 4) }
it 'returns a Hashie::Mash' do
expect(mash.invert).to be_kind_of(described_class)
end
it 'returns a mash with the keys and values inverted' do
expect(mash.invert).to eq('apple' => 'a', 4 => 'b')
end
context 'when using with subclass' do
let(:subclass) { Class.new(Hashie::Mash) }
subject(:sub_mash) { subclass.new(a: 1, b: nil) }
it 'creates an instance of subclass' do
expect(sub_mash.invert).to be_kind_of(subclass)
end
end
end
describe '#reject' do
subject(:mash) { described_class.new(a: 1, b: nil) }
it 'returns a Hashie::Mash' do
expect(mash.reject { |_k, v| v.nil? }).to be_kind_of(described_class)
end
it 'rejects keys for which the block returns true' do
expect(mash.reject { |_k, v| v.nil? }).to eq('a' => 1)
end
context 'when using with subclass' do
let(:subclass) { Class.new(Hashie::Mash) }
subject(:sub_mash) { subclass.new(a: 1, b: nil) }
it 'creates an instance of subclass' do
expect(sub_mash.reject { |_k, v| v.nil? }).to be_kind_of(subclass)
end
end
end
describe '#select' do
subject(:mash) { described_class.new(a: 'apple', b: 4) }
it 'returns a Hashie::Mash' do
expect(mash.select { |_k, v| v.is_a? String }).to be_kind_of(described_class)
end
it 'selects keys for which the block returns true' do
expect(mash.select { |_k, v| v.is_a? String }).to eq('a' => 'apple')
end
context 'when using with subclass' do
let(:subclass) { Class.new(Hashie::Mash) }
subject(:sub_mash) { subclass.new(a: 1, b: nil) }
it 'creates an instance of subclass' do
expect(sub_mash.select { |_k, v| v.is_a? String }).to be_kind_of(subclass)
end
end
end
describe '.quiet' do
it 'returns a subclass of the calling class' do
expect(Hashie::Mash.quiet.new).to be_a(Hashie::Mash)
end
it 'memoizes and returns classes' do
call_one = Hashie::Mash.quiet
call_two = Hashie::Mash.quiet
expect(Hashie::Mash.instance_variable_get('@memoized_classes').count).to eq(1)
expect(call_one).to eq(call_two)
end
end
with_minimum_ruby('2.3.0') do
describe '#dig' do
subject { described_class.new(a: { b: 1 }) }
it 'accepts both string and symbol as key' do
expect(subject.dig(:a, :b)).to eq(1)
expect(subject.dig('a', 'b')).to eq(1)
end
context 'when the Mash wraps a Hashie::Array' do
it 'handles digging into an array' do
mash = described_class.new(alphabet: { first_three: Hashie::Array['a', 'b', 'c'] })
expect(mash.dig(:alphabet, :first_three, 0)).to eq 'a'
end
end
end
end
with_minimum_ruby('2.4.0') do
describe '#transform_values' do
subject(:mash) { described_class.new(a: 1) }
it 'returns a Hashie::Mash' do
expect(mash.transform_values(&:to_s)).to be_kind_of(described_class)
end
it 'transforms the value' do
expect(mash.transform_values(&:to_s).a).to eql('1')
end
context 'when using with subclass' do
let(:subclass) { Class.new(Hashie::Mash) }
subject(:sub_mash) { subclass.new(a: 1).transform_values { |a| a + 2 } }
it 'creates an instance of subclass' do
expect(sub_mash).to be_kind_of(subclass)
end
end
end
describe '#compact' do
subject(:mash) { described_class.new(a: 1, b: nil) }
it 'returns a Hashie::Mash' do
expect(mash.compact).to be_kind_of(described_class)
end
it 'removes keys with nil values' do
expect(mash.compact).to eq('a' => 1)
end
context 'when using with subclass' do
let(:subclass) { Class.new(Hashie::Mash) }
subject(:sub_mash) { subclass.new(a: 1, b: nil) }
it 'creates an instance of subclass' do
expect(sub_mash.compact).to be_kind_of(subclass)
end
end
end
end
with_minimum_ruby('2.5.0') do
describe '#slice' do
subject(:mash) { described_class.new(a: 1, b: 2) }
it 'returns a Hashie::Mash' do
expect(mash.slice(:a)).to be_kind_of(described_class)
end
it 'returns a Mash with only the keys passed' do
expect(mash.slice(:a).to_hash).to eq('a' => 1)
end
context 'when using with subclass' do
let(:subclass) { Class.new(Hashie::Mash) }
subject(:sub_mash) { subclass.new(a: 1, b: 2) }
it 'creates an instance of subclass' do
expect(sub_mash.slice(:a)).to be_kind_of(subclass)
end
end
end
describe '#transform_keys' do
subject(:mash) { described_class.new(a: 1, b: 2) }
it 'returns a Hashie::Mash' do
expect(mash.transform_keys { |k| k + k }).to be_kind_of(described_class)
end
it 'returns a Mash with transformed keys' do
expect(mash.transform_keys { |k| k + k }).to eq('aa' => 1, 'bb' => 2)
end
context 'when using with subclass' do
let(:subclass) { Class.new(Hashie::Mash) }
subject(:sub_mash) { subclass.new(a: 1, b: 2) }
it 'creates an instance of subclass' do
expect(sub_mash.transform_keys { |k| k + k }).to be_kind_of(subclass)
end
end
end
end
with_minimum_ruby('2.6.0') do
context 'ruby 2.6 merging' do
subject(:mash) { Hashie::Mash.new(model: 'Honda') }
it 'merges multiple hashes and mashes passeed to #merge' do
first_hash = { model: 'Ford' }
second_hash = { model: 'DeLorean' }
expect(mash.merge(first_hash, second_hash)).to eq('model' => 'DeLorean')
end
end
end
with_minimum_ruby('3.0.0') do
context '#except' do
subject(:mash) { described_class.new(a: 'A', b: 'B') }
it 'return a Hashie::Mash' do
expect(mash.except(:b)).to be_kind_of(described_class)
end
it 'excludes keys' do
expect(mash.except(:b)).to eq('a' => 'A')
end
end
end
end
|