File tree Expand file tree Collapse file tree 2 files changed +49
-2
lines changed Expand file tree Collapse file tree 2 files changed +49
-2
lines changed Original file line number Diff line number Diff line change 980
980
class AlphaNumeric < Grape ::Validations ::Base
981
981
def validate_param! (attr_name , params )
982
982
unless params[attr_name] =~ /^[[:alnum:] ]+$/
983
- raise Grape ::Exceptions ::Validation , params: [@scope .full_name(attr_name)], message: " must consist of alpha-numeric characters"
983
+ fail Grape ::Exceptions ::Validation , params: [@scope .full_name(attr_name)], message: " must consist of alpha-numeric characters"
984
984
end
985
985
end
986
986
end
@@ -998,7 +998,7 @@ You can also create custom classes that take parameters.
998
998
class Length < Grape ::Validations ::Base
999
999
def validate_param! (attr_name , params )
1000
1000
unless params[attr_name].length <= @option
1001
- raise Grape ::Exceptions ::Validation , params: [@scope .full_name(attr_name)], message: " must be at the most #{ @option } characters long"
1001
+ fail Grape ::Exceptions ::Validation , params: [@scope .full_name(attr_name)], message: " must be at the most #{ @option } characters long"
1002
1002
end
1003
1003
end
1004
1004
end
Original file line number Diff line number Diff line change
1
+ require 'spec_helper'
2
+
3
+ describe Grape ::Validations do
4
+ before do
5
+ class DefaultLength < Grape ::Validations ::Base
6
+ def validate_param! ( attr_name , params )
7
+ @option = params [ :max ] . to_i if params . key? ( :max )
8
+ unless params [ attr_name ] . length <= @option
9
+ fail Grape ::Exceptions ::Validation , params : [ @scope . full_name ( attr_name ) ] , message : "must be at the most #{ @option } characters long"
10
+ end
11
+ end
12
+ end
13
+ end
14
+
15
+ subject do
16
+ Class . new ( Grape ::API ) do
17
+ params do
18
+ requires :text , default_length : 140
19
+ end
20
+ get do
21
+ 'bacon'
22
+ end
23
+ end
24
+ end
25
+
26
+ def app
27
+ subject
28
+ end
29
+
30
+ context 'using a custom length validator' do
31
+ it 'under 140 characters' do
32
+ get '/' , text : 'abc'
33
+ expect ( last_response . status ) . to eq 200
34
+ expect ( last_response . body ) . to eq 'bacon'
35
+ end
36
+ it 'over 140 characters' do
37
+ get '/' , text : 'a' * 141
38
+ expect ( last_response . status ) . to eq 400
39
+ expect ( last_response . body ) . to eq 'text must be at the most 140 characters long'
40
+ end
41
+ it 'specified in the query string' do
42
+ get '/' , text : 'a' * 141 , max : 141
43
+ expect ( last_response . status ) . to eq 200
44
+ expect ( last_response . body ) . to eq 'bacon'
45
+ end
46
+ end
47
+ end
You can’t perform that action at this time.
0 commit comments