-
-
Notifications
You must be signed in to change notification settings - Fork 913
/
validate_uniqueness_of_matcher.rb
1141 lines (978 loc) · 35.2 KB
/
validate_uniqueness_of_matcher.rb
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
module Shoulda
module Matchers
module ActiveRecord
# The `validate_uniqueness_of` matcher tests usage of the
# `validates_uniqueness_of` validation. It first checks for an existing
# instance of your model in the database, creating one if necessary. It
# then takes a new instance of that model and asserts that it fails
# validation if the attribute or attributes you've specified in the
# validation are set to values which are the same as those of the
# pre-existing record (thereby failing the uniqueness check).
#
# class Post < ActiveRecord::Base
# validates :permalink, uniqueness: true
# end
#
# # RSpec
# RSpec.describe Post, type: :model do
# it { should validate_uniqueness_of(:permalink) }
# end
#
# # Minitest (Shoulda)
# class PostTest < ActiveSupport::TestCase
# should validate_uniqueness_of(:permalink)
# end
#
# #### Caveat
#
# This matcher works a bit differently than other matchers. As noted
# before, it will create an instance of your model if one doesn't already
# exist. Sometimes this step fails, especially if you have database-level
# restrictions on any attributes other than the one which is unique. In
# this case, the solution is to populate these attributes with values
# before you call `validate_uniqueness_of`.
#
# For example, say you have the following migration and model:
#
# class CreatePosts < ActiveRecord::Migration
# def change
# create_table :posts do |t|
# t.string :title
# t.text :content, null: false
# end
# end
# end
#
# class Post < ActiveRecord::Base
# validates :title, uniqueness: true
# end
#
# You may be tempted to test the model like this:
#
# RSpec.describe Post, type: :model do
# it { should validate_uniqueness_of(:title) }
# end
#
# However, running this test will fail with an exception such as:
#
# Shoulda::Matchers::ActiveRecord::ValidateUniquenessOfMatcher::ExistingRecordInvalid:
# validate_uniqueness_of works by matching a new record against an
# existing record. If there is no existing record, it will create one
# using the record you provide.
#
# While doing this, the following error was raised:
#
# PG::NotNullViolation: ERROR: null value in column "content" violates not-null constraint
# DETAIL: Failing row contains (1, null, null).
# : INSERT INTO "posts" DEFAULT VALUES RETURNING "id"
#
# The best way to fix this is to provide the matcher with a record where
# any required attributes are filled in with valid values beforehand.
#
# (The exact error message will differ depending on which database you're
# using, but you get the idea.)
#
# This happens because `validate_uniqueness_of` tries to create a new post
# but cannot do so because of the `content` attribute: though unrelated to
# this test, it nevertheless needs to be filled in. As indicated at the
# end of the error message, the solution is to build a custom Post object
# ahead of time with `content` filled in:
#
# RSpec.describe Post, type: :model do
# describe "validations" do
# subject { Post.create(content: "Here is the content") }
# it { should validate_uniqueness_of(:title) }
# end
# end
#
# Or, if you're using
# [FactoryBot](https://github.com/thoughtbot/factory_bot) and you have a
# `post` factory defined which automatically fills in `content`, you can
# say:
#
# RSpec.describe Post, type: :model do
# describe "validations" do
# subject { FactoryBot.create(:post) }
# it { should validate_uniqueness_of(:title) }
# end
# end
#
# #### Qualifiers
#
# Use `on` if your validation applies only under a certain context.
#
# class Post < ActiveRecord::Base
# validates :title, uniqueness: true, on: :create
# end
#
# # RSpec
# RSpec.describe Post, type: :model do
# it { should validate_uniqueness_of(:title).on(:create) }
# end
#
# # Minitest (Shoulda)
# class PostTest < ActiveSupport::TestCase
# should validate_uniqueness_of(:title).on(:create)
# end
#
# ##### with_message
#
# Use `with_message` if you are using a custom validation message.
#
# class Post < ActiveRecord::Base
# validates :title, uniqueness: true, message: 'Please choose another title'
# end
#
# # RSpec
# RSpec.describe Post, type: :model do
# it do
# should validate_uniqueness_of(:title).
# with_message('Please choose another title')
# end
# end
#
# # Minitest (Shoulda)
# class PostTest < ActiveSupport::TestCase
# should validate_uniqueness_of(:title).
# with_message('Please choose another title')
# end
#
# ##### scoped_to
#
# Use `scoped_to` to test usage of the `:scope` option. This asserts that
# a new record fails validation if not only the primary attribute is not
# unique, but the scoped attributes are not unique either.
#
# class Post < ActiveRecord::Base
# validates :slug, uniqueness: { scope: :journal_id }
# end
#
# # RSpec
# RSpec.describe Post, type: :model do
# it { should validate_uniqueness_of(:slug).scoped_to(:journal_id) }
# end
#
# # Minitest (Shoulda)
# class PostTest < ActiveSupport::TestCase
# should validate_uniqueness_of(:slug).scoped_to(:journal_id)
# end
#
# ##### case_insensitive
#
# Use `case_insensitive` to test usage of the `:case_sensitive` option
# with a false value. This asserts that the uniquable attributes fail
# validation even if their values are a different case than corresponding
# attributes in the pre-existing record.
#
# class Post < ActiveRecord::Base
# validates :key, uniqueness: { case_sensitive: false }
# end
#
# # RSpec
# RSpec.describe Post, type: :model do
# it { should validate_uniqueness_of(:key).case_insensitive }
# end
#
# # Minitest (Shoulda)
# class PostTest < ActiveSupport::TestCase
# should validate_uniqueness_of(:key).case_insensitive
# end
#
# ##### ignoring_case_sensitivity
#
# By default, `validate_uniqueness_of` will check that the
# validation is case sensitive: it asserts that uniquable attributes pass
# validation when their values are in a different case than corresponding
# attributes in the pre-existing record.
#
# Use `ignoring_case_sensitivity` to skip this check. This qualifier is
# particularly handy if your model has somehow changed the behavior of
# attribute you're testing so that it modifies the case of incoming values
# as they are set. For instance, perhaps you've overridden the writer
# method or added a `before_validation` callback to normalize the
# attribute.
#
# class User < ActiveRecord::Base
# validates :email, uniqueness: true
#
# def email=(value)
# super(value.downcase)
# end
# end
#
# # RSpec
# RSpec.describe Post, type: :model do
# it do
# should validate_uniqueness_of(:email).ignoring_case_sensitivity
# end
# end
#
# # Minitest (Shoulda)
# class PostTest < ActiveSupport::TestCase
# should validate_uniqueness_of(:email).ignoring_case_sensitivity
# end
#
# ##### allow_nil
#
# Use `allow_nil` to assert that the attribute allows nil.
#
# class Post < ActiveRecord::Base
# validates :author_id, uniqueness: true, allow_nil: true
# end
#
# # RSpec
# RSpec.describe Post, type: :model do
# it { should validate_uniqueness_of(:author_id).allow_nil }
# end
#
# # Minitest (Shoulda)
# class PostTest < ActiveSupport::TestCase
# should validate_uniqueness_of(:author_id).allow_nil
# end
#
# @return [ValidateUniquenessOfMatcher]
#
# ##### allow_blank
#
# Use `allow_blank` to assert that the attribute allows a blank value.
#
# class Post < ActiveRecord::Base
# validates :author_id, uniqueness: true, allow_blank: true
# end
#
# # RSpec
# RSpec.describe Post, type: :model do
# it { should validate_uniqueness_of(:author_id).allow_blank }
# end
#
# # Minitest (Shoulda)
# class PostTest < ActiveSupport::TestCase
# should validate_uniqueness_of(:author_id).allow_blank
# end
#
# @return [ValidateUniquenessOfMatcher]
#
def validate_uniqueness_of(attr)
ValidateUniquenessOfMatcher.new(attr)
end
# @private
class ValidateUniquenessOfMatcher < ActiveModel::ValidationMatcher
include ActiveModel::Helpers
def initialize(attribute)
super(attribute)
@expected_message = :taken
@options = {
case_sensitivity_strategy: :sensitive
}
@existing_record_created = false
@failure_reason = nil
@failure_reason_when_negated = nil
@attribute_setters = {
existing_record: AttributeSetters.new,
new_record: AttributeSetters.new
}
end
def scoped_to(*scopes)
@options[:scopes] = [*scopes].flatten.map(&:to_sym)
self
end
def case_insensitive
@options[:case_sensitivity_strategy] = :insensitive
self
end
def ignoring_case_sensitivity
@options[:case_sensitivity_strategy] = :ignore
self
end
def allow_nil
@options[:allow_nil] = true
self
end
def expects_to_allow_nil?
@options[:allow_nil] == true
end
def allow_blank
@options[:allow_blank] = true
self
end
def expects_to_allow_blank?
@options[:allow_blank] == true
end
def simple_description
description = "validate that :#{@attribute} is"
description << description_for_case_sensitive_qualifier
description << ' unique'
if @options[:scopes].present?
description << " within the scope of #{inspected_expected_scopes}"
end
description
end
def matches?(given_record)
@given_record = given_record
@all_records = model.all
matches_presence_of_attribute? &&
matches_presence_of_scopes? &&
matches_scopes_configuration? &&
matches_uniqueness_without_scopes? &&
matches_uniqueness_with_case_sensitivity_strategy? &&
matches_uniqueness_with_scopes? &&
matches_allow_nil? &&
matches_allow_blank?
ensure
Uniqueness::TestModels.remove_all
end
def does_not_match?(given_record)
@given_record = given_record
@all_records = model.all
does_not_match_presence_of_scopes? ||
does_not_match_scopes_configuration? ||
does_not_match_uniqueness_without_scopes? ||
does_not_match_uniqueness_with_case_sensitivity_strategy? ||
does_not_match_uniqueness_with_scopes? ||
does_not_match_allow_nil? ||
does_not_match_allow_blank?
ensure
Uniqueness::TestModels.remove_all
end
protected
def failure_reason
@failure_reason || super
end
def failure_reason_when_negated
@failure_reason_when_negated || super
end
def build_allow_or_disallow_value_matcher(args)
super.tap do |matcher|
matcher.failure_message_preface = method(:failure_message_preface)
matcher.attribute_changed_value_message =
method(:attribute_changed_value_message)
end
end
private
def case_sensitivity_strategy
@options[:case_sensitivity_strategy]
end
def new_record
unless defined?(@new_record)
build_new_record
end
@new_record
end
alias_method :subject, :new_record
def description_for_case_sensitive_qualifier
case case_sensitivity_strategy
when :sensitive
' case-sensitively'
when :insensitive
' case-insensitively'
else
''
end
end
def validations
model.validators_on(@attribute).select do |validator|
validator.is_a?(::ActiveRecord::Validations::UniquenessValidator)
end
end
def matches_scopes_configuration?
if scopes_match?
true
else
@failure_reason = 'Expected the validation '
if expected_scopes.empty?
@failure_reason << 'not to be scoped to anything, '
else
@failure_reason << "to be scoped to #{inspected_expected_scopes}, "
end
if actual_sets_of_scopes.any?
@failure_reason << 'but it was scoped to '
@failure_reason << "#{inspected_actual_scopes} instead."
else
@failure_reason << 'but it was not scoped to anything.'
end
false
end
end
def does_not_match_scopes_configuration?
if scopes_match?
@failure_reason = 'Expected the validation '
if expected_scopes.empty?
@failure_reason << 'to be scoped to nothing, '
@failure_reason << 'but it was scoped to '
@failure_reason << "#{inspected_actual_scopes} instead."
else
@failure_reason << 'not to be scoped to '
@failure_reason << inspected_expected_scopes
end
false
else
true
end
end
def scopes_match?
actual_sets_of_scopes.empty? && expected_scopes.empty? ||
actual_sets_of_scopes.any? { |scopes| scopes == expected_scopes }
end
def inspected_expected_scopes
expected_scopes.map(&:inspect).to_sentence
end
def inspected_actual_scopes
inspected_actual_sets_of_scopes.to_sentence(
words_connector: ' and ',
last_word_connector: ', and'
)
end
def inspected_actual_sets_of_scopes
inspected_sets_of_scopes = actual_sets_of_scopes.map do |scopes|
scopes.map(&:inspect)
end
if inspected_sets_of_scopes.many?
inspected_sets_of_scopes.map { |x| "(#{x.to_sentence})" }
else
inspected_sets_of_scopes.map(&:to_sentence)
end
end
def expected_scopes
Array.wrap(@options[:scopes])
end
def actual_sets_of_scopes
validations.map do |validation|
Array.wrap(validation.options[:scope]).map(&:to_sym)
end.reject(&:empty?)
end
def matches_allow_nil?
!expects_to_allow_nil? || (
update_existing_record!(nil) &&
allows_value_of(nil, @expected_message)
)
end
def does_not_match_allow_nil?
expects_to_allow_nil? && (
update_existing_record!(nil) &&
(@failure_reason = nil || disallows_value_of(nil, @expected_message))
)
end
def matches_allow_blank?
!expects_to_allow_blank? || (
update_existing_record!('') &&
allows_value_of('', @expected_message)
)
end
def does_not_match_allow_blank?
expects_to_allow_blank? && (
update_existing_record!('') &&
(@failure_reason = nil || disallows_value_of('', @expected_message))
)
end
def existing_record
unless defined?(@existing_record)
find_or_create_existing_record
end
@existing_record
end
def find_or_create_existing_record
@existing_record = find_existing_record
unless @existing_record
@existing_record = create_existing_record
@existing_record_created = true
end
end
def find_existing_record
record = model.first
if record.present?
record
else
nil
end
end
def create_existing_record
@given_record.tap do |existing_record|
existing_record.save(validate: false)
end
rescue ::ActiveRecord::StatementInvalid => error
raise ExistingRecordInvalid.create(underlying_exception: error)
end
def update_existing_record!(value)
if existing_value_read != value
set_attribute_on_existing_record!(@attribute, value)
# It would be nice if we could ensure that the record was valid,
# but that would break users' existing tests
existing_record.save(validate: false)
end
true
end
def arbitrary_non_blank_value
non_blank_value = dummy_value_for(@attribute)
limit = column_limit_for(@attribute)
is_string_value = non_blank_value.is_a?(String)
if is_string_value && limit && limit < non_blank_value.length
'x' * limit
else
non_blank_value
end
end
def has_secure_password?
Shoulda::Matchers::RailsShim.has_secure_password?(subject, @attribute)
end
def build_new_record
@new_record = existing_record.dup
attribute_names_under_test.each do |attribute_name|
set_attribute_on_new_record!(
attribute_name,
existing_record.public_send(attribute_name)
)
end
@new_record
end
def matches_presence_of_attribute?
if attribute_present_on_model?
true
else
@failure_reason =
":#{attribute} does not seem to be an attribute on #{model.name}."
false
end
end
def does_not_match_presence_of_attribute?
if attribute_present_on_model?
@failure_reason =
":#{attribute} seems to be an attribute on #{model.name}."
false
else
true
end
end
def attribute_present_on_model?
model.method_defined?("#{attribute}=") ||
model.columns_hash.key?(attribute.to_s)
end
def matches_presence_of_scopes?
if scopes_missing_on_model.none?
true
else
inspected_scopes = scopes_missing_on_model.map(&:inspect)
reason = ''
reason << inspected_scopes.to_sentence
if inspected_scopes.many?
reason << " do not seem to be attributes"
else
reason << " does not seem to be an attribute"
end
reason << " on #{model.name}."
@failure_reason = reason
false
end
end
def does_not_match_presence_of_scopes?
if scopes_missing_on_model.any?
true
else
inspected_scopes = scopes_present_on_model.map(&:inspect)
reason = ''
reason << inspected_scopes.to_sentence
if inspected_scopes.many?
reason << " seem to be attributes"
else
reason << " seems to be an attribute"
end
reason << " on #{model.name}."
@failure_reason = reason
false
end
end
def scopes_present_on_model
@_present_scopes ||= expected_scopes.select do |scope|
model.method_defined?("#{scope}=")
end
end
def scopes_missing_on_model
@_missing_scopes ||= expected_scopes.select do |scope|
!model.method_defined?("#{scope}=")
end
end
def matches_uniqueness_without_scopes?
if existing_value_read.blank?
update_existing_record!(arbitrary_non_blank_value)
end
disallows_value_of(existing_value_read, @expected_message)
end
def does_not_match_uniqueness_without_scopes?
@failure_reason = nil
if existing_value_read.blank?
update_existing_record!(arbitrary_non_blank_value)
end
allows_value_of(existing_value_read, @expected_message)
end
def matches_uniqueness_with_case_sensitivity_strategy?
if should_test_case_sensitivity?
value = existing_value_read
swapcased_value = value.swapcase
if case_sensitivity_strategy == :sensitive
if value == swapcased_value
raise NonCaseSwappableValueError.create(
model: model,
attribute: @attribute,
value: value
)
end
allows_value_of(swapcased_value, @expected_message)
else
disallows_value_of(swapcased_value, @expected_message)
end
else
true
end
end
def does_not_match_uniqueness_with_case_sensitivity_strategy?
if should_test_case_sensitivity?
@failure_reason = nil
value = existing_value_read
swapcased_value = value.swapcase
if case_sensitivity_strategy == :sensitive
disallows_value_of(swapcased_value, @expected_message)
else
if value == swapcased_value
raise NonCaseSwappableValueError.create(
model: model,
attribute: @attribute,
value: value
)
end
allows_value_of(swapcased_value, @expected_message)
end
else
true
end
end
def should_test_case_sensitivity?
case_sensitivity_strategy != :ignore &&
existing_value_read.respond_to?(:swapcase) &&
!existing_value_read.empty?
end
def model_class?(model_name)
model_name.constantize.ancestors.include?(::ActiveRecord::Base)
rescue NameError
false
end
def matches_uniqueness_with_scopes?
expected_scopes.none? ||
all_scopes_are_booleans? ||
expected_scopes.all? do |scope|
setting_next_value_for(scope) do
allows_value_of(existing_value_read, @expected_message)
end
end
end
def does_not_match_uniqueness_with_scopes?
expected_scopes.any? &&
!all_scopes_are_booleans? &&
expected_scopes.any? do |scope|
setting_next_value_for(scope) do
@failure_reason = nil
disallows_value_of(existing_value_read, @expected_message)
end
end
end
def setting_next_value_for(scope)
previous_value = @all_records.map(&scope).compact.max
next_value =
if previous_value.blank?
dummy_value_for(scope)
else
next_value_for(scope, previous_value)
end
set_attribute_on_new_record!(scope, next_value)
yield
ensure
set_attribute_on_new_record!(scope, previous_value)
end
def dummy_value_for(scope)
column = column_for(scope)
if column.respond_to?(:array) && column.array
[ dummy_scalar_value_for(column) ]
else
dummy_scalar_value_for(column)
end
end
def dummy_scalar_value_for(column)
Shoulda::Matchers::Util.dummy_value_for(column.type)
end
def next_value_for(scope, previous_value)
if previous_value.is_a?(Array)
[ next_scalar_value_for(scope, previous_value[0]) ]
else
next_scalar_value_for(scope, previous_value)
end
end
def next_scalar_value_for(scope, previous_value)
column = column_for(scope)
if column.type == :uuid
SecureRandom.uuid
elsif defined_as_enum?(scope)
available_values = available_enum_values_for(scope, previous_value)
available_values.keys.last
elsif polymorphic_type_attribute?(scope, previous_value)
Uniqueness::TestModels.create(previous_value).to_s
elsif previous_value.respond_to?(:next)
previous_value.next
elsif previous_value.respond_to?(:to_datetime)
previous_value.to_datetime.in(60).next
elsif boolean_value?(previous_value)
!previous_value
else
previous_value.to_s.next
end
end
def all_scopes_are_booleans?
@options[:scopes].all? do |scope|
@all_records.map(&scope).all? { |s| boolean_value?(s) }
end
end
def boolean_value?(value)
[true, false].include?(value)
end
def defined_as_enum?(scope)
model.respond_to?(:defined_enums) &&
new_record.defined_enums[scope.to_s]
end
def polymorphic_type_attribute?(scope, previous_value)
scope.to_s =~ /_type$/ && model_class?(previous_value)
end
def available_enum_values_for(scope, previous_value)
new_record.defined_enums[scope.to_s].reject do |key, _|
key == previous_value
end
end
def set_attribute_on!(record_type, record, attribute_name, value)
attribute_setter = build_attribute_setter(
record,
attribute_name,
value
)
attribute_setter.set!
@attribute_setters[record_type] << attribute_setter
end
def set_attribute_on_existing_record!(attribute_name, value)
set_attribute_on!(
:existing_record,
existing_record,
attribute_name,
value
)
end
def set_attribute_on_new_record!(attribute_name, value)
set_attribute_on!(
:new_record,
new_record,
attribute_name,
value
)
end
def attribute_setter_for_existing_record
@attribute_setters[:existing_record].last
end
def attribute_setters_for_new_record
@attribute_setters[:new_record] +
[last_attribute_setter_used_on_new_record]
end
def attribute_names_under_test
[@attribute] + expected_scopes
end
def build_attribute_setter(record, attribute_name, value)
Shoulda::Matchers::ActiveModel::AllowValueMatcher::AttributeSetter.new(
matcher_name: :validate_uniqueness_of,
object: record,
attribute_name: attribute_name,
value: value,
ignore_interference_by_writer: ignore_interference_by_writer
)
end
def existing_value_read
existing_record.public_send(@attribute)
end
def existing_value_written
if attribute_setter_for_existing_record
attribute_setter_for_existing_record.value_written
else
existing_value_read
end
end
def column_for(scope)
model.columns_hash[scope.to_s]
end
def column_limit_for(attribute)
column_for(attribute).try(:limit)
end
def model
@given_record.class
end
def failure_message_preface
prefix = ''
if @existing_record_created
prefix << "After taking the given #{model.name}"
if attribute_setter_for_existing_record
prefix << ', setting '
prefix << description_for_attribute_setter(
attribute_setter_for_existing_record
)
else
prefix << ", whose :#{attribute} is "
prefix << "‹#{existing_value_read.inspect}›"
end
prefix << ", and saving it as the existing record, then"
else
if attribute_setter_for_existing_record
prefix << "Given an existing #{model.name},"
prefix << ' after setting '
prefix << description_for_attribute_setter(
attribute_setter_for_existing_record
)
prefix << ', then'
else
prefix << "Given an existing #{model.name} whose :#{attribute}"
prefix << ' is '
prefix << Shoulda::Matchers::Util.inspect_value(
existing_value_read
)
prefix << ', after'
end
end
prefix << " making a new #{model.name} and setting "
prefix << descriptions_for_attribute_setters_for_new_record
prefix << ", the matcher expected the new #{model.name} to be"
prefix
end
def attribute_changed_value_message
<<-MESSAGE.strip
As indicated in the message above,
:#{last_attribute_setter_used_on_new_record.attribute_name} seems to be
changing certain values as they are set, and this could have something
to do with why this test is failing. If you or something else has
overridden the writer method for this attribute to normalize values by
changing their case in any way (for instance, ensuring that the
attribute is always downcased), then try adding
`ignoring_case_sensitivity` onto the end of the uniqueness matcher.
Otherwise, you may need to write the test yourself, or do something
different altogether.
MESSAGE
end
def description_for_attribute_setter(attribute_setter, same_as_existing: nil)
description = "its :#{attribute_setter.attribute_name} to "
if same_as_existing == false
description << 'a different value, '
end
description << Shoulda::Matchers::Util.inspect_value(
attribute_setter.value_written
)