Skip to content

LengthValidator will raise ArgumentException at runtime if conditions aren't met #2519

@ericproulx

Description

@ericproulx

The length validator will raise an ArgumentError at runtime if min, max or is conditions aren't met.

For instance

describe '/negative_max' do
  let(:app) do
    Class.new(Grape::API) do
      params do
        requires :list, type: [Integer], length: { max: -3 }
      end
      post 'negative_max'
    end
  end

  context 'it raises an error' do
    it do
      expect { post 'negative_max', list: [12] }.to raise_error(ArgumentError, 'max must be an integer greater than or equal to zero')
    end
  end
end

This test will succeed but it doesn't seem right since its caused by the way its declared and not by the input. I think this kind of error should occur a loading time like when we're coercing values, except and default values.

For instance, this will raise an error when the api is loaded.

describe 'only integers' do
  subject { Class.new(Grape::API) }
  
  context 'values are not integers' do
    it 'raises exception' do
      expect do
        subject.params { optional :numbers, type: Set[Integer], values: %w[a b] }
      end.to raise_error Grape::Exceptions::IncompatibleOptionValues
    end
  end
end

IMO this early exception helps the users to fix the issue right away instead of waiting at runtime when its already too late.

I'm working on something to initialize validators at loading time instead of runtime. The validators are saved per API and their state won't change at runtime since its just validating the input.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions