forked from thoughtbot/shoulda-matchers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate_inclusion_of_matcher.rb
635 lines (579 loc) · 18.2 KB
/
validate_inclusion_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
require 'bigdecimal'
require 'date'
module Shoulda
module Matchers
# @private
class ExampleClass; end
module ActiveModel
# The `validate_inclusion_of` matcher tests usage of the
# `validates_inclusion_of` validation, asserting that an attribute can
# take a allowlist of values and cannot take values outside of this list.
#
# If your allowlist is an array of values, use `in_array`:
#
# class Issue
# include ActiveModel::Model
# attr_accessor :state
#
# validates_inclusion_of :state,
# in: ['open', 'resolved', 'unresolved']
# end
#
# # RSpec
# RSpec.describe Issue, type: :model do
# it do
# should validate_inclusion_of(:state).
# in_array(['open', 'resolved', 'unresolved'])
# end
# end
#
# # Minitest (Shoulda)
# class IssueTest < ActiveSupport::TestCase
# should validate_inclusion_of(:state).
# in_array(['open', 'resolved', 'unresolved'])
# end
#
# If your allowlist is a range of values, use `in_range`:
#
# class Issue
# include ActiveModel::Model
# attr_accessor :priority
#
# validates_inclusion_of :priority, in: 1..5
# end
#
# # RSpec
# RSpec.describe Issue, type: :model do
# it { should validate_inclusion_of(:priority).in_range(1..5) }
# end
#
# # Minitest (Shoulda)
# class IssueTest < ActiveSupport::TestCase
# should validate_inclusion_of(:priority).in_range(1..5)
# end
#
# #### Caveats
#
# We discourage using `validate_inclusion_of` with boolean columns. In
# fact, there is never a case where a boolean column will be anything but
# true, false, or nil, as ActiveRecord will type-cast an incoming value to
# one of these three values. That means there isn't any way we can refute
# this logic in a test. Hence, this will produce a warning:
#
# it do
# should validate_inclusion_of(:imported).
# in_array([true, false])
# end
#
# The only case where `validate_inclusion_of` *could* be appropriate is
# for ensuring that a boolean column accepts nil, but we recommend
# using `allow_value` instead, like this:
#
# it { should allow_value(nil).for(:imported) }
#
# #### Qualifiers
#
# Use `on` if your validation applies only under a certain context.
#
# class Issue
# include ActiveModel::Model
# attr_accessor :severity
#
# validates_inclusion_of :severity,
# in: %w(low medium high),
# on: :create
# end
#
# # RSpec
# RSpec.describe Issue, type: :model do
# it do
# should validate_inclusion_of(:severity).
# in_array(%w(low medium high)).
# on(:create)
# end
# end
#
# # Minitest (Shoulda)
# class IssueTest < ActiveSupport::TestCase
# should validate_inclusion_of(:severity).
# in_array(%w(low medium high)).
# on(:create)
# end
#
# ##### with_message
#
# Use `with_message` if you are using a custom validation message.
#
# class Issue
# include ActiveModel::Model
# attr_accessor :severity
#
# validates_inclusion_of :severity,
# in: %w(low medium high),
# message: 'Severity must be low, medium, or high'
# end
#
# # RSpec
# RSpec.describe Issue, type: :model do
# it do
# should validate_inclusion_of(:severity).
# in_array(%w(low medium high)).
# with_message('Severity must be low, medium, or high')
# end
# end
#
# # Minitest (Shoulda)
# class IssueTest < ActiveSupport::TestCase
# should validate_inclusion_of(:severity).
# in_array(%w(low medium high)).
# with_message('Severity must be low, medium, or high')
# end
#
# ##### with_low_message
#
# Use `with_low_message` if you have a custom validation message for when
# a given value is too low.
#
# class Person
# include ActiveModel::Model
# attr_accessor :age
#
# validate :age_must_be_valid
#
# private
#
# def age_must_be_valid
# if age < 65
# self.errors.add :age, 'You do not receive any benefits'
# end
# end
# end
#
# # RSpec
# RSpec.describe Person, type: :model do
# it do
# should validate_inclusion_of(:age).
# in_range(0..65).
# with_low_message('You do not receive any benefits')
# end
# end
#
# # Minitest (Shoulda)
# class PersonTest < ActiveSupport::TestCase
# should validate_inclusion_of(:age).
# in_range(0..65).
# with_low_message('You do not receive any benefits')
# end
#
# ##### with_high_message
#
# Use `with_high_message` if you have a custom validation message for
# when a given value is too high.
#
# class Person
# include ActiveModel::Model
# attr_accessor :age
#
# validate :age_must_be_valid
#
# private
#
# def age_must_be_valid
# if age > 21
# self.errors.add :age, "You're too old for this stuff"
# end
# end
# end
#
# # RSpec
# RSpec.describe Person, type: :model do
# it do
# should validate_inclusion_of(:age).
# in_range(0..21).
# with_high_message("You're too old for this stuff")
# end
# end
#
# # Minitest (Shoulda)
# class PersonTest < ActiveSupport::TestCase
# should validate_inclusion_of(:age).
# in_range(0..21).
# with_high_message("You're too old for this stuff")
# end
#
# ##### allow_nil
#
# Use `allow_nil` to assert that the attribute allows nil.
#
# class Issue
# include ActiveModel::Model
# attr_accessor :state
#
# validates_presence_of :state
# validates_inclusion_of :state,
# in: ['open', 'resolved', 'unresolved'],
# allow_nil: true
# end
#
# # RSpec
# RSpec.describe Issue, type: :model do
# it do
# should validate_inclusion_of(:state).
# in_array(['open', 'resolved', 'unresolved']).
# allow_nil
# end
# end
#
# # Minitest (Shoulda)
# class IssueTest < ActiveSupport::TestCase
# should validate_inclusion_of(:state).
# in_array(['open', 'resolved', 'unresolved']).
# allow_nil
# end
#
# ##### allow_blank
#
# Use `allow_blank` to assert that the attribute allows blank.
#
# class Issue
# include ActiveModel::Model
# attr_accessor :state
#
# validates_presence_of :state
# validates_inclusion_of :state,
# in: ['open', 'resolved', 'unresolved'],
# allow_blank: true
# end
#
# # RSpec
# RSpec.describe Issue, type: :model do
# it do
# should validate_inclusion_of(:state).
# in_array(['open', 'resolved', 'unresolved']).
# allow_blank
# end
# end
#
# # Minitest (Shoulda)
# class IssueTest < ActiveSupport::TestCase
# should validate_inclusion_of(:state).
# in_array(['open', 'resolved', 'unresolved']).
# allow_blank
# end
#
# @return [ValidateInclusionOfMatcher]
#
def validate_inclusion_of(attr)
ValidateInclusionOfMatcher.new(attr)
end
# @private
class ValidateInclusionOfMatcher < ValidationMatcher
BLANK_VALUES = ['', ' ', "\n", "\r", "\t", "\f"].freeze
ARBITRARY_OUTSIDE_STRING = Shoulda::Matchers::ExampleClass.name
ARBITRARY_OUTSIDE_INTEGER = 123456789
ARBITRARY_OUTSIDE_DECIMAL = BigDecimal('0.123456789')
ARBITRARY_OUTSIDE_DATE = Date.jd(9999999)
ARBITRARY_OUTSIDE_DATETIME = DateTime.jd(9999999)
ARBITRARY_OUTSIDE_TIME = Time.at(9999999999)
BOOLEAN_ALLOWS_BOOLEAN_MESSAGE = <<EOT.freeze
You are using `validate_inclusion_of` to assert that a boolean column allows
boolean values and disallows non-boolean ones. Be aware that it is not possible
to fully test this, as boolean columns will automatically convert non-boolean
values to boolean ones. Hence, you should consider removing this test.
EOT
BOOLEAN_ALLOWS_NIL_MESSAGE = <<EOT.freeze
You are using `validate_inclusion_of` to assert that a boolean column allows nil.
Be aware that it is not possible to fully test this, as anything other than
true, false or nil will be converted to false. Hence, you should consider
removing this test.
EOT
def initialize(attribute)
super(attribute)
@options = {}
@array = nil
@range = nil
@minimum = nil
@maximum = nil
@low_message = :inclusion
@high_message = :inclusion
end
def in_array(array)
@array = array
self
end
def in_range(range)
@range = range
@minimum = minimum_range_value
@maximum = maximum_range_value
self
end
def allow_nil
@options[:allow_nil] = true
self
end
def expects_to_allow_nil?
@options[:allow_nil]
end
def with_message(message)
if message
@expects_custom_validation_message = true
@low_message = message
@high_message = message
end
self
end
def with_low_message(message)
if message
@expects_custom_validation_message = true
@low_message = message
end
self
end
def with_high_message(message)
if message
@high_message = message
end
self
end
def simple_description
if @range
"validate that :#{@attribute} lies inside the range " +
Shoulda::Matchers::Util.inspect_range(@range)
else
description = "validate that :#{@attribute}"
description <<
if @array.count > 1
" is either #{inspected_array}"
else
" is #{inspected_array}"
end
description
end
end
def matches?(subject)
super(subject)
if @range
matches_for_range?
elsif @array
if matches_for_array?
true
else
@failure_message = "#{@array} doesn't match array in validation"
false
end
end
end
def does_not_match?(subject)
super(subject)
if @range
does_not_match_for_range?
elsif @array
if does_not_match_for_array?
true
else
@failure_message = "#{@array} matches array in validation"
false
end
end
end
private
def minimum_range_value
@range.begin
end
def maximum_range_value
if @range.exclude_end?
@range.end ? (@range.end - 1) : nil
else
@range.end
end
end
def matches_for_range?
disallows_lower_value &&
allows_minimum_value &&
allows_maximum_value &&
disallows_higher_value
end
def does_not_match_for_range?
allows_lower_value ||
disallows_minimum_value ||
disallows_maximum_value ||
allows_higher_value
end
def matches_for_array?
allows_all_values_in_array? &&
disallows_all_values_outside_of_array? &&
allows_nil_value? &&
allow_blank_matches?
end
def does_not_match_for_array?
disallows_any_values_in_array? ||
allows_any_value_outside_of_array? ||
disallows_nil_value? ||
allow_blank_does_not_match?
end
def allows_lower_value
@minimum &&
@minimum != 0 &&
allows_value_of(@minimum - 1, @low_message)
end
def disallows_lower_value
@minimum.nil? ||
@minimum == 0 ||
disallows_value_of(@minimum - 1, @low_message)
end
def allows_minimum_value
@minimum.nil? || allows_value_of(@minimum, @low_message)
end
def disallows_minimum_value
@minimum.nil? || disallows_value_of(@minimum, @low_message)
end
def allows_maximum_value
@maximum.nil? || allows_value_of(@maximum, @high_message)
end
def disallows_maximum_value
@maximum.nil? || disallows_value_of(@maximum, @high_message)
end
def allows_higher_value
@maximum.nil? || allows_value_of(@maximum + 1, @high_message)
end
def disallows_higher_value
@maximum.nil? || disallows_value_of(@maximum + 1, @high_message)
end
def allows_all_values_in_array?
@array.all? do |value|
allows_value_of(value, @low_message)
end
end
def disallows_any_values_in_array?
@array.any? do |value|
disallows_value_of(value, @low_message)
end
end
def allows_any_value_outside_of_array?
if attribute_type == :boolean
case @array
when [false, true], [true, false]
Shoulda::Matchers.warn BOOLEAN_ALLOWS_BOOLEAN_MESSAGE
return true
when [nil]
if attribute_column.null
Shoulda::Matchers.warn BOOLEAN_ALLOWS_NIL_MESSAGE
return true
else
raise NonNullableBooleanError.create(@attribute)
end
end
end
values_outside_of_array.any? do |value|
allows_value_of(value, @low_message)
end
end
def disallows_all_values_outside_of_array?
if attribute_type == :boolean
case @array
when [false, true], [true, false]
Shoulda::Matchers.warn BOOLEAN_ALLOWS_BOOLEAN_MESSAGE
return true
when [nil]
if attribute_column.null
Shoulda::Matchers.warn BOOLEAN_ALLOWS_NIL_MESSAGE
return true
else
raise NonNullableBooleanError.create(@attribute)
end
end
end
values_outside_of_array.all? do |value|
disallows_value_of(value, @low_message)
end
end
def values_outside_of_array
if !(@array & outside_values).empty?
raise CouldNotDetermineValueOutsideOfArray
else
outside_values
end
end
def outside_values
case attribute_type
when :boolean
boolean_outside_values
when :integer
[ARBITRARY_OUTSIDE_INTEGER]
when :decimal
[ARBITRARY_OUTSIDE_DECIMAL]
when :date
[ARBITRARY_OUTSIDE_DATE]
when :datetime
[ARBITRARY_OUTSIDE_DATETIME]
when :time
[ARBITRARY_OUTSIDE_TIME]
else
[ARBITRARY_OUTSIDE_STRING]
end
end
def boolean_outside_values
values = []
values << case @array
when [true] then false
when [false] then true
else raise CouldNotDetermineValueOutsideOfArray
end
if attribute_allows_nil?
values << nil
end
values
end
def attribute_type
if attribute_column
column_type_to_attribute_type(attribute_column.type)
else
value_to_attribute_type(@subject.__send__(@attribute))
end
end
def attribute_allows_nil?
if attribute_column
attribute_column.null
else
true
end
end
def attribute_column
if @subject.class.respond_to?(:columns_hash)
@subject.class.columns_hash[@attribute.to_s]
end
end
def column_type_to_attribute_type(type)
case type
when :float then :integer
when :timestamp then :datetime
else type
end
end
def value_to_attribute_type(value)
case value
when true, false then :boolean
when BigDecimal then :decimal
when Integer then :integer
when Date then :date
when DateTime then :datetime
when Time then :time
else :unknown
end
end
def allows_nil_value?
@options[:allow_nil] != true || allows_value_of(nil)
end
def disallows_nil_value?
@options[:allow_nil] && disallows_value_of(nil)
end
def inspected_array
Shoulda::Matchers::Util.inspect_values(@array).to_sentence(
two_words_connector: ' or ',
last_word_connector: ', or ',
)
end
end
end
end
end