Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

custom validator keeping ref to instance variable #1593

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions spec/grape/api/custom_validations_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,54 @@
require 'spec_helper'

describe Grape::Validations do

context "when a validator uses an instance variable" do
before do
module CustomValidationsSpec
module HelperMethods
extend Grape::API::Helpers
def max_ref(req_params)
return @max unless @max.nil?
@max = req_params[:max].to_i
end
end

class DefaultLength < Grape::Validations::Base
include CustomValidationsSpec::HelperMethods
def validate_param!(attr_name, params)
return if params[attr_name].length <= max_ref(params)
fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: "must be at the most #{max_ref(params)} characters long"
end
end
end
end

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

def app
subject
end

it 'between 2 calls, helper inside a validator does not keep old reference of instance variable' do
get '/', text: 'a' * 130, max: 140
expect(last_response.status).to eq 200

get '/', text: 'a' * 130, max: 120
expect(last_response.status).to eq 400
end
end


context 'using a custom length validator' do
before do
module CustomValidationsSpec
Expand Down