forked from thoughtbot/shoulda-matchers
-
Notifications
You must be signed in to change notification settings - Fork 1
/
validate_acceptance_of_matcher.rb
105 lines (101 loc) · 3.02 KB
/
validate_acceptance_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
module Shoulda
module Matchers
module ActiveModel
# The `validate_acceptance_of` matcher tests usage of the
# `validates_acceptance_of` validation.
#
# class Registration
# include ActiveModel::Model
# attr_accessor :eula
#
# validates_acceptance_of :eula
# end
#
# # RSpec
# RSpec.describe Registration, type: :model do
# it { should validate_acceptance_of(:eula) }
# end
#
# # Minitest (Shoulda)
# class RegistrationTest < ActiveSupport::TestCase
# should validate_acceptance_of(:eula)
# end
#
# #### Qualifiers
#
# ##### on
#
# Use `on` if your validation applies only under a certain context.
#
# class Registration
# include ActiveModel::Model
# attr_accessor :terms_of_service
#
# validates_acceptance_of :terms_of_service, on: :create
# end
#
# # RSpec
# RSpec.describe Registration, type: :model do
# it do
# should validate_acceptance_of(:terms_of_service).
# on(:create)
# end
# end
#
# # Minitest (Shoulda)
# class RegistrationTest < ActiveSupport::TestCase
# should validate_acceptance_of(:terms_of_service).on(:create)
# end
#
# ##### with_message
#
# Use `with_message` if you are using a custom validation message.
#
# class Registration
# include ActiveModel::Model
# attr_accessor :terms_of_service
#
# validates_acceptance_of :terms_of_service,
# message: 'You must accept the terms of service'
# end
#
# # RSpec
# RSpec.describe Registration, type: :model do
# it do
# should validate_acceptance_of(:terms_of_service).
# with_message('You must accept the terms of service')
# end
# end
#
# # Minitest (Shoulda)
# class RegistrationTest < ActiveSupport::TestCase
# should validate_acceptance_of(:terms_of_service).
# with_message('You must accept the terms of service')
# end
#
# @return [ValidateAcceptanceOfMatcher]
#
def validate_acceptance_of(attr)
ValidateAcceptanceOfMatcher.new(attr)
end
# @private
class ValidateAcceptanceOfMatcher < ValidationMatcher
def initialize(attribute)
super
@expected_message = :accepted
end
def matches?(subject)
super(subject)
disallows_value_of(false, @expected_message)
end
def does_not_match?(subject)
super(subject)
allows_value_of(false, @expected_message)
end
def simple_description
%(validate that :#{@attribute} has been set to "1")
end
end
end
end
end