Skip to content

Commit ff1342d

Browse files
committed
failing test custom validator keeping ref to instance var
1 parent 9f786ad commit ff1342d

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

spec/grape/api/custom_validations_spec.rb

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,54 @@
33
require 'spec_helper'
44

55
describe Grape::Validations do
6+
7+
context "when a validator uses an instance variable" do
8+
before do
9+
module CustomValidationsSpec
10+
module HelperMethods
11+
extend Grape::API::Helpers
12+
def max_ref(req_params)
13+
return @max unless @max.nil?
14+
@max = req_params[:max].to_i
15+
end
16+
end
17+
18+
class DefaultLength < Grape::Validations::Base
19+
include CustomValidationsSpec::HelperMethods
20+
def validate_param!(attr_name, params)
21+
return if params[attr_name].length <= max_ref(params)
22+
fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: "must be at the most #{max_ref(params)} characters long"
23+
end
24+
end
25+
end
26+
end
27+
28+
subject do
29+
Class.new(Grape::API) do
30+
params do
31+
requires :text, default_length: 140
32+
requires :max
33+
end
34+
get do
35+
'bacon'
36+
end
37+
end
38+
end
39+
40+
def app
41+
subject
42+
end
43+
44+
it 'between 2 calls, helper inside a validator does not keep old reference of instance variable' do
45+
get '/', text: 'a' * 130, max: 140
46+
expect(last_response.status).to eq 200
47+
48+
get '/', text: 'a' * 130, max: 120
49+
expect(last_response.status).to eq 400
50+
end
51+
end
52+
53+
654
context 'using a custom length validator' do
755
before do
856
module CustomValidationsSpec

0 commit comments

Comments
 (0)