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

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

Open
ericproulx opened this issue Dec 29, 2024 · 0 comments

Comments

@ericproulx
Copy link
Contributor

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.

@ericproulx ericproulx changed the title LengthValidator will raise ArgumentException at runtime if options are not satisfied LengthValidator will raise ArgumentException at runtime if conditions aren't met Dec 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant