-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathuniqueness_of.rb
38 lines (33 loc) · 1.16 KB
/
uniqueness_of.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
module RSpecRailsMatchers
module Validations
module UniquenessOf
def validate_uniqueness_of(attribute, options = {})
RSpec::Matchers::Matcher.new :validate_uniqueness_of, attribute do |_attr_|
match do |model|
duplicate = create_duplicate_record(model, _attr_, options[:scope])
if options[:scope]
model.send("#{options[:scope]}=", duplicate.send(options[:scope]))
end
model.send("#{_attr_}=", "foobar")
model.invalid? &&
model.errors[_attr_].include?(
I18n::t('activerecord.errors.messages.taken')
)
end
failure_message_for_should do |model|
RSpecRailsMatchers::Message.error(
:expected =>
[ "%s to validate uniqueness of %s, %s", model, _attr_, options ]
)
end
def create_duplicate_record( model, attr, scope )
m = model.class.new(attr => 'foobar')
m.send("#{scope}=", 11) if scope
m.save(:validate => false)
m
end
end
end
end
end
end