-
-
Notifications
You must be signed in to change notification settings - Fork 908
/
validate_uniqueness_of_matcher.rb
435 lines (398 loc) · 13.7 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
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_uniqueness_of :permalink
# end
#
# # RSpec
# describe Post do
# it { should validate_uniqueness_of(:permalink) }
# end
#
# # Test::Unit
# 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:
#
# describe Post do
# it { should validate_uniqueness_of(:title) }
# end
#
# However, running this test will fail with something like:
#
# Failures:
#
# 1) Post should require case sensitive unique value for title
# Failure/Error: it { should validate_uniqueness_of(:title) }
# ActiveRecord::StatementInvalid:
# SQLite3::ConstraintException: posts.content may not be NULL: INSERT INTO "posts" ("title") VALUES (?)
#
# 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. The solution is to
# build a custom Post object ahead of time with `content` filled in:
#
# describe Post do
# describe "validations" do
# subject { Post.new(content: 'Here is the content') }
# it { should validate_uniqueness_of(:title) }
# end
# end
#
# Or, if you're using
# [FactoryGirl](http://github.com/thoughtbot/factory_girl) and you have a
# `post` factory defined which automatically fills in `content`, you can
# say:
#
# describe Post do
# describe "validations" do
# subject { FactoryGirl.build(:post) }
# it { should validate_uniqueness_of(:title) }
# end
# end
#
# #### Qualifiers
#
# ##### with_message
#
# Use `with_message` if you are using a custom validation message.
#
# class Post < ActiveRecord::Base
# validates_uniqueness_of :title, message: 'Please choose another title'
# end
#
# # RSpec
# describe Post do
# it do
# should validate_uniqueness_of(:title).
# with_message('Please choose another title')
# end
# end
#
# # Test::Unit
# 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_uniqueness_of :slug, scope: :user_id
# end
#
# # RSpec
# describe Post do
# it { should validate_uniqueness_of(:slug).scoped_to(:journal_id) }
# end
#
# # Test::Unit
# 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_uniqueness_of :key, case_sensitive: false
# end
#
# # RSpec
# describe Post do
# it { should validate_uniqueness_of(:key).case_insensitive }
# end
#
# # Test::Unit
# class PostTest < ActiveSupport::TestCase
# should validate_uniqueness_of(:key).case_insensitive
# end
#
# ##### allow_nil
#
# Use `allow_nil` to assert that the attribute allows nil.
#
# class Post < ActiveRecord::Base
# validates_uniqueness_of :author_id, allow_nil: true
# end
#
# # RSpec
# describe Post do
# it { should validate_uniqueness_of(:author_id).allow_nil }
# end
#
# # Test::Unit
# 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_uniqueness_of :author_id, allow_blank: true
# end
#
# # RSpec
# describe Post do
# it { should validate_uniqueness_of(:author_id).allow_blank }
# end
#
# # Test::Unit
# 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)
@options = {}
end
def scoped_to(*scopes)
@options[:scopes] = [*scopes].flatten
self
end
def with_message(message)
@expected_message = message
self
end
def case_insensitive
@options[:case_insensitive] = true
self
end
def allow_nil
@options[:allow_nil] = true
self
end
def allow_blank
@options[:allow_blank] = true
self
end
def description
result = "require "
result << "case sensitive " unless @options[:case_insensitive]
result << "unique value for #{@attribute}"
result << " scoped to #{@options[:scopes].join(', ')}" if @options[:scopes].present?
result
end
def matches?(subject)
@original_subject = subject
@subject = subject.class.new
@expected_message ||= :taken
set_scoped_attributes &&
validate_everything_except_duplicate_nils_or_blanks? &&
validate_after_scope_change? &&
allows_nil? &&
allows_blank?
ensure
Uniqueness::TestModels.remove_all
end
private
def allows_nil?
if @options[:allow_nil]
ensure_nil_record_in_database
allows_value_of(nil, @expected_message)
else
true
end
end
def allows_blank?
if @options[:allow_blank]
ensure_blank_record_in_database
allows_value_of('', @expected_message)
else
true
end
end
def existing_record
@existing_record ||= first_instance
end
def first_instance
@subject.class.first || create_record_in_database
end
def ensure_nil_record_in_database
unless existing_record_is_nil?
create_record_in_database(nil_value: true)
end
end
def ensure_blank_record_in_database
unless existing_record_is_blank?
create_record_in_database(blank_value: true)
end
end
def existing_record_is_nil?
@existing_record.present? && existing_value.nil?
end
def existing_record_is_blank?
@existing_record.present? && existing_value.strip == ''
end
def create_record_in_database(options = {})
@original_subject.tap do |instance|
instance.__send__("#{@attribute}=", value_for_new_record(options))
ensure_secure_password_set(instance)
instance.save(validate: false)
@created_record = instance
end
end
def ensure_secure_password_set(instance)
if has_secure_password?
instance.password = "password"
instance.password_confirmation = "password"
end
end
def value_for_new_record(options = {})
case
when options[:nil_value] then nil
when options[:blank_value] then ''
else 'a'
end
end
def has_secure_password?
@subject.class.ancestors.map(&:to_s).include?('ActiveModel::SecurePassword::InstanceMethodsOnActivation')
end
def set_scoped_attributes
if @options[:scopes].present?
@options[:scopes].all? do |scope|
setter = :"#{scope}="
if @subject.respond_to?(setter)
@subject.__send__(setter, existing_record.__send__(scope))
true
else
@failure_message = "#{class_name} doesn't seem to have a #{scope} attribute."
false
end
end
else
true
end
end
def validate_everything_except_duplicate_nils_or_blanks?
if (@options[:allow_nil] && existing_value.nil?) ||
(@options[:allow_blank] && existing_value.blank?)
create_record_with_value
end
disallows_value_of(existing_value, @expected_message)
end
def create_record_with_value
@existing_record = create_record_in_database
end
def model_class?(model_name)
model_name.constantize.ancestors.include?(::ActiveRecord::Base)
rescue NameError
false
end
def validate_after_scope_change?
if @options[:scopes].blank?
true
else
all_records = @subject.class.all
@options[:scopes].all? do |scope|
previous_value = all_records.map(&scope).max
# Assume the scope is a foreign key if the field is nil
previous_value ||= correct_type_for_column(@subject.class.columns_hash[scope.to_s])
next_value =
if @subject.class.respond_to?(:defined_enums) && @subject.defined_enums[scope.to_s]
available_values = @subject.defined_enums[scope.to_s].reject do |key, _|
key == previous_value
end
available_values.keys.last
elsif scope.to_s =~ /_type$/ && model_class?(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.next
else
previous_value.to_s.next
end
@subject.__send__("#{scope}=", next_value)
if allows_value_of(existing_value, @expected_message)
@subject.__send__("#{scope}=", previous_value)
@failure_message_when_negated <<
" (with different value of #{scope})"
true
else
@failure_message << " (with different value of #{scope})"
false
end
end
end
end
def correct_type_for_column(column)
if column.type == :string
'0'
elsif column.type == :datetime
DateTime.now
elsif column.type == :uuid
SecureRandom.uuid
else
0
end
end
def class_name
@subject.class.name
end
def existing_value
value = existing_record.__send__(@attribute)
if @options[:case_insensitive] && value.respond_to?(:swapcase!)
value.swapcase!
end
value
end
end
end
end
end