Skip to content

Commit

Permalink
Added a custom validations spec.
Browse files Browse the repository at this point in the history
  • Loading branch information
dblock committed Apr 17, 2015
1 parent 8000ffd commit c96d42b
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
4 changes: 2 additions & 2 deletions README.md
Expand Up @@ -980,7 +980,7 @@ end
class AlphaNumeric < Grape::Validations::Base
def validate_param!(attr_name, params)
unless params[attr_name] =~ /^[[:alnum:]]+$/
raise Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: "must consist of alpha-numeric characters"
fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: "must consist of alpha-numeric characters"
end
end
end
Expand All @@ -998,7 +998,7 @@ You can also create custom classes that take parameters.
class Length < Grape::Validations::Base
def validate_param!(attr_name, params)
unless params[attr_name].length <= @option
raise Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: "must be at the most #{@option} characters long"
fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: "must be at the most #{@option} characters long"
end
end
end
Expand Down
47 changes: 47 additions & 0 deletions spec/grape/api/custom_validations_spec.rb
@@ -0,0 +1,47 @@
require 'spec_helper'

describe Grape::Validations do
before do
class DefaultLength < Grape::Validations::Base
def validate_param!(attr_name, params)
@option = params[:max].to_i if params.key?(:max)
unless params[attr_name].length <= @option
fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: "must be at the most #{@option} characters long"
end
end
end
end

subject do
Class.new(Grape::API) do
params do
requires :text, default_length: 140
end
get do
'bacon'
end
end
end

def app
subject
end

context 'using a custom length validator' do
it 'under 140 characters' do
get '/', text: 'abc'
expect(last_response.status).to eq 200
expect(last_response.body).to eq 'bacon'
end
it 'over 140 characters' do
get '/', text: 'a' * 141
expect(last_response.status).to eq 400
expect(last_response.body).to eq 'text must be at the most 140 characters long'
end
it 'specified in the query string' do
get '/', text: 'a' * 141, max: 141
expect(last_response.status).to eq 200
expect(last_response.body).to eq 'bacon'
end
end
end

0 comments on commit c96d42b

Please sign in to comment.