forked from thoughtbot/shoulda-matchers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
have_secure_password_matcher.rb
92 lines (79 loc) · 2.46 KB
/
have_secure_password_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
module Shoulda
module Matchers
module ActiveModel
# The `have_secure_password` matcher tests usage of the
# `has_secure_password` macro.
#
# #### Example
#
# class User
# include ActiveModel::Model
# include ActiveModel::SecurePassword
# attr_accessor :password
#
# has_secure_password
# end
#
# # RSpec
# describe User do
# it { should have_secure_password }
# end
#
# # Minitest (Shoulda)
# class UserTest < ActiveSupport::TestCase
# should have_secure_password
# end
#
# @return [HaveSecurePasswordMatcher]
#
def have_secure_password
HaveSecurePasswordMatcher.new
end
# @private
class HaveSecurePasswordMatcher
attr_reader :failure_message
CORRECT_PASSWORD = "aBcDe12345"
INCORRECT_PASSWORD = "password"
EXPECTED_METHODS = [
:authenticate,
:password=,
:password_confirmation=,
:password_digest,
:password_digest=,
]
MESSAGES = {
authenticated_incorrect_password: "expected %{subject} to not authenticate an incorrect password",
did_not_authenticate_correct_password: "expected %{subject} to authenticate the correct password",
method_not_found: "expected %{subject} to respond to %{methods}"
}
def description
"have a secure password"
end
def matches?(subject)
@subject = subject
if failure = validate
key, params = failure
@failure_message = MESSAGES[key] % { subject: subject.class }.merge(params)
end
failure.nil?
end
protected
attr_reader :subject
def validate
missing_methods = EXPECTED_METHODS.select {|m| !subject.respond_to?(m) }
if missing_methods.present?
[:method_not_found, { methods: missing_methods.to_sentence }]
else
subject.password = CORRECT_PASSWORD
subject.password_confirmation = CORRECT_PASSWORD
if not subject.authenticate(CORRECT_PASSWORD)
[:did_not_authenticate_correct_password, {}]
elsif subject.authenticate(INCORRECT_PASSWORD)
[:authenticated_incorrect_password, {}]
end
end
end
end
end
end
end