Skip to content

Commit c96d42b

Browse files
committed
Added a custom validations spec.
1 parent 8000ffd commit c96d42b

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -980,7 +980,7 @@ end
980980
class AlphaNumeric < Grape::Validations::Base
981981
def validate_param!(attr_name, params)
982982
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"
984984
end
985985
end
986986
end
@@ -998,7 +998,7 @@ You can also create custom classes that take parameters.
998998
class Length < Grape::Validations::Base
999999
def validate_param!(attr_name, params)
10001000
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"
10021002
end
10031003
end
10041004
end
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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

0 commit comments

Comments
 (0)