repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/path_spec.rb
spec/grape/path_spec.rb
# frozen_string_literal: true describe Grape::Path do describe '#origin' do context 'mount_path' do it 'is not included when it is nil' do path = described_class.new(nil, nil, mount_path: '/foo/bar') expect(path.origin).to eql '/foo/bar' end it 'is included when it is not nil' do path = described_class.new(nil, nil, {}) expect(path.origin).to eql('/') end end context 'root_prefix' do it 'is not included when it is nil' do path = described_class.new(nil, nil, {}) expect(path.origin).to eql('/') end it 'is included after the mount path' do path = described_class.new( nil, nil, mount_path: '/foo', root_prefix: '/hello' ) expect(path.origin).to eql('/foo/hello') end end it 'uses the namespace after the mount path and root prefix' do path = described_class.new( nil, 'namespace', mount_path: '/foo', root_prefix: '/hello' ) expect(path.origin).to eql('/foo/hello/namespace') end it 'uses the raw path after the namespace' do path = described_class.new( 'raw_path', 'namespace', mount_path: '/foo', root_prefix: '/hello' ) expect(path.origin).to eql('/foo/hello/namespace/raw_path') end end describe '#suffix' do context 'when using a specific format' do it 'accepts specified format' do path = described_class.new(nil, nil, format: 'json', content_types: 'application/json') expect(path.suffix).to eql('(.json)') end end context 'when path versioning is used' do it "includes a '/'" do path = described_class.new(nil, nil, version: :v1, version_options: { using: :path }) expect(path.suffix).to eql('(/.:format)') end end context 'when path versioning is not used' do it "does not include a '/' when the path has a namespace" do path = described_class.new(nil, 'namespace', {}) expect(path.suffix).to eql('(.:format)') end it "does not include a '/' when the path has a path" do path = described_class.new('/path', nil, version: :v1, version_options: { using: :path }) expect(path.suffix).to eql('(.:format)') end it "includes a '/' otherwise" do path = described_class.new(nil, nil, version: :v1, version_options: { using: :path }) expect(path.suffix).to eql('(/.:format)') end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api_remount_spec.rb
spec/grape/api_remount_spec.rb
# frozen_string_literal: true require 'shared/versioning_examples' describe Grape::API do subject(:a_remounted_api) { Class.new(described_class) } let(:root_api) { Class.new(described_class) } let(:app) { root_api } describe 'remounting an API' do context 'with a defined route' do before do a_remounted_api.get '/votes' do '10 votes' end end context 'when mounting one instance' do before do root_api.mount a_remounted_api end it 'can access the endpoint' do get '/votes' expect(last_response.body).to eql '10 votes' end end context 'when mounting twice' do before do root_api.mount a_remounted_api => '/posts' root_api.mount a_remounted_api => '/comments' end it 'can access the votes in both places' do get '/posts/votes' expect(last_response.body).to eql '10 votes' get '/comments/votes' expect(last_response.body).to eql '10 votes' end end context 'when mounting on namespace' do before do stub_const('StaticRefToAPI', a_remounted_api) root_api.namespace 'posts' do mount StaticRefToAPI end root_api.namespace 'comments' do mount StaticRefToAPI end end it 'can access the votes in both places' do get '/posts/votes' expect(last_response.body).to eql '10 votes' get '/comments/votes' expect(last_response.body).to eql '10 votes' end end end describe 'with dynamic configuration' do context 'when mounting an endpoint conditional on a configuration' do subject(:a_remounted_api) do Class.new(described_class) do get 'always' do 'success' end given configuration[:mount_sometimes] do get 'sometimes' do 'sometimes' end end end end it 'mounts the endpoints only when configured to do so' do root_api.mount({ a_remounted_api => 'with_conditional' }, with: { mount_sometimes: true }) root_api.mount({ a_remounted_api => 'without_conditional' }, with: { mount_sometimes: false }) get '/with_conditional/always' expect(last_response.body).to eq 'success' get '/with_conditional/sometimes' expect(last_response.body).to eq 'sometimes' get '/without_conditional/always' expect(last_response.body).to eq 'success' get '/without_conditional/sometimes' expect(last_response).to be_not_found end end context 'when using an expression derived from a configuration' do subject(:a_remounted_api) do Class.new(described_class) do get(mounted { "api_name_#{configuration[:api_name]}" }) do 'success' end end end before do root_api.mount a_remounted_api, with: { api_name: 'a_name' } end it 'mounts the endpoint with the name' do get 'api_name_a_name' expect(last_response.body).to eq 'success' end it 'does not mount the endpoint with a null name' do get 'api_name_' expect(last_response.body).not_to eq 'success' end context 'when the expression lives in a namespace' do subject(:a_remounted_api) do Class.new(described_class) do namespace :base do get(mounted { "api_name_#{configuration[:api_name]}" }) do 'success' end end end end it 'mounts the endpoint with the name' do get 'base/api_name_a_name' expect(last_response.body).to eq 'success' end it 'does not mount the endpoint with a null name' do get 'base/api_name_' expect(last_response.body).not_to eq 'success' end end end context 'when the params are configured via a configuration' do subject(:a_remounted_api) do Class.new(described_class) do params do requires configuration[:required_attr_name], type: String end get(mounted { configuration[:endpoint] }) do status 200 end end end context 'when the configured param is my_attr' do it 'requires the configured params' do root_api.mount a_remounted_api, with: { required_attr_name: 'my_attr', endpoint: 'test' } get 'test?another_attr=1' expect(last_response).to be_bad_request get 'test?my_attr=1' expect(last_response).to be_successful root_api.mount a_remounted_api, with: { required_attr_name: 'another_attr', endpoint: 'test_b' } get 'test_b?another_attr=1' expect(last_response).to be_successful get 'test_b?my_attr=1' expect(last_response).to be_bad_request end end end context 'when executing a standard block within a `mounted` block with all dynamic params' do subject(:a_remounted_api) do Class.new(described_class) do mounted do desc configuration[:description] do headers configuration[:headers] end get configuration[:endpoint] do configuration[:response] end end end end let(:api_endpoint) { 'custom_endpoint' } let(:api_response) { 'custom response' } let(:endpoint_description) { 'this is a custom API' } let(:headers) do { 'XAuthToken' => { 'description' => 'Validates your identity', 'required' => true } } end it 'mounts the API and obtains the description and headers definition' do root_api.mount a_remounted_api, with: { description: endpoint_description, headers: headers, endpoint: api_endpoint, response: api_response } get api_endpoint expect(last_response.body).to eq api_response expect(a_remounted_api.instances.last.endpoints.first.options[:route_options][:description]) .to eq endpoint_description expect(a_remounted_api.instances.last.endpoints.first.options[:route_options][:headers]) .to eq headers end end context 'when executing a custom block on mount' do subject(:a_remounted_api) do Class.new(described_class) do get 'always' do 'success' end mounted do configuration[:endpoints].each do |endpoint_name, endpoint_response| get endpoint_name do endpoint_response end end end end end it 'mounts the endpoints only when configured to do so' do root_api.mount a_remounted_api, with: { endpoints: { 'api_name' => 'api_response' } } get 'api_name' expect(last_response.body).to eq 'api_response' end end context 'when the configuration is part of the arguments of a method' do subject(:a_remounted_api) do Class.new(described_class) do get configuration[:endpoint_name] do 'success' end end end it 'mounts the endpoint in the location it is configured' do root_api.mount a_remounted_api, with: { endpoint_name: 'some_location' } get '/some_location' expect(last_response.body).to eq 'success' get '/different_location' expect(last_response).to be_not_found root_api.mount a_remounted_api, with: { endpoint_name: 'new_location' } get '/new_location' expect(last_response.body).to eq 'success' end context 'when the configuration is the value in a key-arg pair' do subject(:a_remounted_api) do Class.new(described_class) do version 'v1', using: :param, parameter: configuration[:version_param] get 'endpoint' do 'version 1' end version 'v2', using: :param, parameter: configuration[:version_param] get 'endpoint' do 'version 2' end end end it 'takes the param from the configuration' do root_api.mount a_remounted_api, with: { version_param: 'param_name' } get '/endpoint?param_name=v1' expect(last_response.body).to eq 'version 1' get '/endpoint?param_name=v2' expect(last_response.body).to eq 'version 2' get '/endpoint?wrong_param_name=v2' expect(last_response.body).to eq 'version 1' end end end context 'on the DescSCope' do subject(:a_remounted_api) do Class.new(described_class) do desc 'The description of this' do tags ['not_configurable_tag', configuration[:a_configurable_tag]] end get 'location' do route.tags end end end it 'mounts the endpoint with the appropiate tags' do root_api.mount({ a_remounted_api => 'integer' }, with: { a_configurable_tag: 'a configured tag' }) get '/integer/location', param_key: 'a' expect(JSON.parse(last_response.body)).to eq ['not_configurable_tag', 'a configured tag'] end end context 'on the ParamScope' do subject(:a_remounted_api) do Class.new(described_class) do params do requires configuration[:required_param], type: configuration[:required_type] end get 'location' do 'success' end end end it 'mounts the endpoint in the location it is configured' do root_api.mount({ a_remounted_api => 'string' }, with: { required_param: 'param_key', required_type: String }) root_api.mount({ a_remounted_api => 'integer' }, with: { required_param: 'param_integer', required_type: Integer }) get '/string/location', param_key: 'a' expect(last_response.body).to eq 'success' get '/string/location', param_integer: 1 expect(last_response).to be_bad_request get '/integer/location', param_integer: 1 expect(last_response.body).to eq 'success' get '/integer/location', param_integer: 'a' expect(last_response).to be_bad_request end context 'on dynamic checks' do subject(:a_remounted_api) do Class.new(described_class) do params do optional :restricted_values, values: -> { [configuration[:allowed_value], 'always'] } end get 'location' do 'success' end end end it 'can read the configuration on lambdas' do root_api.mount a_remounted_api, with: { allowed_value: 'sometimes' } get '/location', restricted_values: 'always' expect(last_response.body).to eq 'success' get '/location', restricted_values: 'sometimes' expect(last_response.body).to eq 'success' get '/location', restricted_values: 'never' expect(last_response).to be_bad_request end end end context 'when the configuration is read within a namespace' do before do a_remounted_api.namespace 'api' do params do requires configuration[:required_param] end get "/#{configuration[:path]}" do '10 votes' end end root_api.mount a_remounted_api, with: { path: 'votes', required_param: 'param_key' } root_api.mount a_remounted_api, with: { path: 'scores', required_param: 'param_key' } end it 'uses the dynamic configuration on all routes' do get 'api/votes', param_key: 'a' expect(last_response.body).to eql '10 votes' get 'api/scores', param_key: 'a' expect(last_response.body).to eql '10 votes' get 'api/votes' expect(last_response).to be_bad_request end end context 'a very complex configuration example' do before do top_level_api = Class.new(described_class) do remounted_api = Class.new(Grape::API) do get configuration[:endpoint_name] do configuration[:response] end end expression_namespace = mounted { configuration[:namespace].to_s * 2 } given(mounted { configuration[:should_mount_expressed] != false }) do namespace expression_namespace do mount remounted_api, with: { endpoint_name: configuration[:endpoint_name], response: configuration[:endpoint_response] } end end end root_api.mount top_level_api, with: configuration_options end context 'when the namespace should be mounted' do let(:configuration_options) do { should_mount_expressed: true, namespace: 'bang', endpoint_name: 'james', endpoint_response: 'bond' } end it 'gets a response' do get 'bangbang/james' expect(last_response.body).to eq 'bond' end end context 'when should be mounted is nil' do let(:configuration_options) do { should_mount_expressed: nil, namespace: 'bang', endpoint_name: 'james', endpoint_response: 'bond' } end it 'gets a response' do get 'bangbang/james' expect(last_response.body).to eq 'bond' end end context 'when it should not be mounted' do let(:configuration_options) do { should_mount_expressed: false, namespace: 'bang', endpoint_name: 'james', endpoint_response: 'bond' } end it 'gets a response' do get 'bangbang/james' expect(last_response.body).not_to eq 'bond' end end end context 'when the configuration is read in a helper' do subject(:a_remounted_api) do Class.new(described_class) do helpers do def printed_response configuration[:some_value] end end get 'location' do printed_response end end end it 'uses the dynamic configuration on all routes' do root_api.mount(a_remounted_api, with: { some_value: 'response value' }) get '/location' expect(last_response.body).to eq 'response value' end end context 'when the configuration is read within the response block' do subject(:a_remounted_api) do Class.new(described_class) do get 'location' do configuration[:some_value] end end end it 'uses the dynamic configuration on all routes' do root_api.mount(a_remounted_api, with: { some_value: 'response value' }) get '/location' expect(last_response.body).to eq 'response value' end end end context 'with route settings' do before do a_remounted_api.desc 'Identical description' a_remounted_api.route_setting :custom, key: 'value' a_remounted_api.route_setting :custom_diff, key: 'foo' a_remounted_api.get '/api1' do status 200 end a_remounted_api.desc 'Identical description' a_remounted_api.route_setting :custom, key: 'value' a_remounted_api.route_setting :custom_diff, key: 'bar' a_remounted_api.get '/api2' do status 200 end end it 'has all the settings for both routes' do expect(a_remounted_api.routes.count).to be(2) expect(a_remounted_api.routes[0].settings).to include( { description: { description: 'Identical description' }, custom: { key: 'value' }, custom_diff: { key: 'foo' } } ) expect(a_remounted_api.routes[1].settings).to include( { description: { description: 'Identical description' }, custom: { key: 'value' }, custom_diff: { key: 'bar' } } ) end context 'when mounting it' do before do root_api.mount a_remounted_api end it 'still has all the settings for both routes' do expect(root_api.routes.count).to be(2) expect(root_api.routes[0].settings).to include( { description: { description: 'Identical description' }, custom: { key: 'value' }, custom_diff: { key: 'foo' } } ) expect(root_api.routes[1].settings).to include( { description: { description: 'Identical description' }, custom: { key: 'value' }, custom_diff: { key: 'bar' } } ) end end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/content_types_spec.rb
spec/grape/content_types_spec.rb
# frozen_string_literal: true describe Grape::ContentTypes do describe 'DEFAULTS' do subject { described_class::DEFAULTS } let(:expected_value) do { xml: 'application/xml', serializable_hash: 'application/json', json: 'application/json', binary: 'application/octet-stream', txt: 'text/plain' }.freeze end it { is_expected.to eq(expected_value) } end describe 'MIME_TYPES' do subject { described_class::MIME_TYPES } let(:expected_value) do { 'application/xml' => :xml, 'application/json' => :json, 'application/octet-stream' => :binary, 'text/plain' => :txt }.freeze end it { is_expected.to eq(expected_value) } end describe '.content_types_for' do subject { described_class.content_types_for(from_settings) } context 'when from_settings is present' do let(:from_settings) { { a: :b } } it { is_expected.to eq(from_settings) } end context 'when from_settings is not present' do let(:from_settings) { nil } it { is_expected.to be(described_class::DEFAULTS) } end end describe '.mime_types_for' do subject { described_class.mime_types_for(from_settings) } context 'when from_settings is equal to Grape::ContentTypes::DEFAULTS' do let(:from_settings) do { xml: 'application/xml', serializable_hash: 'application/json', json: 'application/json', binary: 'application/octet-stream', txt: 'text/plain' }.freeze end it { is_expected.to be(described_class::MIME_TYPES) } end context 'when from_settings is not equal to Grape::ContentTypes::DEFAULTS' do let(:from_settings) do { xml: 'application/xml;charset=utf-8' } end it { is_expected.to eq('application/xml' => :xml) } end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/named_api_spec.rb
spec/grape/named_api_spec.rb
# frozen_string_literal: true describe Grape::API do subject(:api_name) { NamedAPI.endpoints.last.options[:for].to_s } let(:api) do Class.new(Grape::API) do get 'test' do 'response' end end end let(:name) { 'NamedAPI' } before { stub_const(name, api) } it 'can access the name of the API' do expect(api_name).to eq name end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/request_spec.rb
spec/grape/request_spec.rb
# frozen_string_literal: true describe Grape::Request do let(:default_method) { Rack::GET } let(:default_params) { {} } let(:default_options) do { method: method, params: params } end let(:default_env) do Rack::MockRequest.env_for('/', options) end let(:method) { default_method } let(:params) { default_params } let(:options) { default_options } let(:env) { default_env } let(:request) do described_class.new(env) end describe '#params' do let(:params) do { a: '123', b: 'xyz' } end it 'by default returns stringified parameter keys' do expect(request.params).to eq(ActiveSupport::HashWithIndifferentAccess.new('a' => '123', 'b' => 'xyz')) end context 'when build_params_with: Grape::Extensions::Hash::ParamBuilder is specified' do let(:request) do described_class.new(env, build_params_with: :hash) end it 'returns symbolized params' do expect(request.params).to eq(a: '123', b: 'xyz') end end describe 'with grape.routing_args' do let(:options) do default_options.merge('grape.routing_args' => routing_args) end let(:routing_args) do { version: '123', route_info: '456', c: 'ccc' } end it 'cuts version and route_info' do expect(request.params).to eq(ActiveSupport::HashWithIndifferentAccess.new(a: '123', b: 'xyz', c: 'ccc')) end end context 'when rack_params raises an EOF error' do before do allow(request).to receive(:rack_params).and_raise(EOFError) end let(:message) { Grape::Exceptions::EmptyMessageBody.new(nil).to_s } it 'raises an Grape::Exceptions::EmptyMessageBody' do expect { request.params }.to raise_error(Grape::Exceptions::EmptyMessageBody, message) end end context 'when rack_params raises a Rack::Multipart::MultipartPartLimitError' do before do allow(request).to receive(:rack_params).and_raise(Rack::Multipart::MultipartPartLimitError) end let(:message) { Grape::Exceptions::TooManyMultipartFiles.new(Rack::Utils.multipart_part_limit).to_s } it 'raises an Rack::Multipart::MultipartPartLimitError' do expect { request.params }.to raise_error(Grape::Exceptions::TooManyMultipartFiles, message) end end context 'when rack_params raises a Rack::Multipart::MultipartTotalPartLimitError' do before do allow(request).to receive(:rack_params).and_raise(Rack::Multipart::MultipartTotalPartLimitError) end let(:message) { Grape::Exceptions::TooManyMultipartFiles.new(Rack::Utils.multipart_part_limit).to_s } it 'raises an Rack::Multipart::MultipartPartLimitError' do expect { request.params }.to raise_error(Grape::Exceptions::TooManyMultipartFiles, message) end end context 'when rack_params raises a Rack::QueryParser::ParamsTooDeepError' do before do allow(request).to receive(:rack_params).and_raise(Rack::QueryParser::ParamsTooDeepError) end let(:message) { Grape::Exceptions::TooDeepParameters.new(Rack::Utils.param_depth_limit).to_s } it 'raises a Grape::Exceptions::TooDeepParameters' do expect { request.params }.to raise_error(Grape::Exceptions::TooDeepParameters, message) end end context 'when rack_params raises a Rack::Utils::ParameterTypeError' do before do allow(request).to receive(:rack_params).and_raise(Rack::Utils::ParameterTypeError) end let(:message) { Grape::Exceptions::ConflictingTypes.new.to_s } it 'raises a Grape::Exceptions::ConflictingTypes' do expect { request.params }.to raise_error(Grape::Exceptions::ConflictingTypes, message) end end context 'when rack_params raises a Rack::Utils::InvalidParameterError' do before do allow(request).to receive(:rack_params).and_raise(Rack::Utils::InvalidParameterError) end let(:message) { Grape::Exceptions::InvalidParameters.new.to_s } it 'raises an Rack::Multipart::MultipartPartLimitError' do expect { request.params }.to raise_error(Grape::Exceptions::InvalidParameters, message) end end end describe '#headers' do let(:options) do default_options.merge(request_headers) end describe 'with http headers in env' do let(:request_headers) do { 'HTTP_X_GRAPE_IS_COOL' => 'yeah' } end let(:x_grape_is_cool_header) do 'x-grape-is-cool' end it 'cuts HTTP_ prefix and capitalizes header name words' do expect(request.headers).to eq(x_grape_is_cool_header => 'yeah') end end describe 'with non-HTTP_* stuff in env' do let(:request_headers) do { 'HTP_X_GRAPE_ENTITY_TOO' => 'but now we are testing Grape' } end it 'does not include them' do expect(request.headers).to eq({}) end end describe 'with symbolic header names' do let(:request_headers) do { HTTP_GRAPE_LIKES_SYMBOLIC: 'it is true' } end let(:env) do default_env.merge(request_headers) end let(:grape_likes_symbolic_header) do 'grape-likes-symbolic' end it 'converts them to string' do expect(request.headers).to eq(grape_likes_symbolic_header => 'it is true') end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api_spec.rb
spec/grape/api_spec.rb
# frozen_string_literal: true require 'shared/versioning_examples' describe Grape::API do subject { Class.new(described_class) } let(:app) { subject } describe '.prefix' do it 'routes root through with the prefix' do subject.prefix 'awesome/sauce' subject.get do 'Hello there.' end get 'awesome/sauce/' expect(last_response).to be_successful expect(last_response.body).to eql 'Hello there.' end it 'routes through with the prefix' do subject.prefix 'awesome/sauce' subject.get :hello do 'Hello there.' end get 'awesome/sauce/hello' expect(last_response.body).to eql 'Hello there.' get '/hello' expect(last_response).to be_not_found end it 'supports OPTIONS' do subject.prefix 'awesome/sauce' subject.get do 'Hello there.' end options 'awesome/sauce' expect(last_response).to be_no_content expect(last_response.body).to be_blank end it 'disallows POST' do subject.prefix 'awesome/sauce' subject.get post 'awesome/sauce' expect(last_response).to be_method_not_allowed end end describe '.version' do context 'when defined' do it 'returns version value' do subject.version 'v1' expect(subject.version).to eq('v1') end end context 'when not defined' do it 'returns nil' do expect(subject.version).to be_nil end end end describe '.version using path' do it_behaves_like 'versioning' do let(:macro_options) do { using: :path } end end end describe '.version using param' do it_behaves_like 'versioning' do let(:macro_options) do { using: :param, parameter: 'apiver' } end end end describe '.version using header' do it_behaves_like 'versioning' do let(:macro_options) do { using: :header, vendor: 'mycompany', format: 'json' } end end end describe '.version using accept_version_header' do it_behaves_like 'versioning' do let(:macro_options) do { using: :accept_version_header } end end end describe '.represent' do it 'requires a :with option' do expect { subject.represent Object, {} }.to raise_error(Grape::Exceptions::InvalidWithOptionForRepresent) end it 'adds the association to the :representations setting' do dummy_presenter_klass = Class.new represent_object = Class.new subject.represent represent_object, with: dummy_presenter_klass expect(subject.inheritable_setting.namespace_stackable[:representations]).to eq([represent_object => dummy_presenter_klass]) end end describe '.namespace' do it 'is retrievable and converted to a path' do internal_namespace = nil subject.namespace :awesome do internal_namespace = namespace end expect(internal_namespace).to eql('/awesome') end it 'comes after the prefix and version' do subject.prefix :rad subject.version 'v1', using: :path subject.namespace :awesome do get('/hello') { 'worked' } end get '/rad/v1/awesome/hello' expect(last_response.body).to eq('worked') end it 'cancels itself after the block is over' do internal_namespace = nil subject.namespace :awesome do internal_namespace = namespace end expect(subject.namespace).to eql('/') end it 'is stackable' do internal_namespace = nil internal_second_namespace = nil subject.namespace :awesome do internal_namespace = namespace namespace :rad do internal_second_namespace = namespace end end expect(internal_namespace).to eq('/awesome') expect(internal_second_namespace).to eq('/awesome/rad') end it 'accepts path segments correctly' do inner_namespace = nil subject.namespace :members do namespace '/:member_id' do inner_namespace = namespace get '/' do params[:member_id] end end end get '/members/23' expect(last_response.body).to eq('23') expect(inner_namespace).to eq('/members/:member_id') end it 'is callable with nil just to push onto the stack' do subject.namespace do version 'v2', using: :path get('/hello') { 'inner' } end subject.get('/hello') { 'outer' } get '/v2/hello' expect(last_response.body).to eq('inner') get '/hello' expect(last_response.body).to eq('outer') end %w[group resource resources segment].each do |als| it "`.#{als}` is an alias" do inner_namespace = nil subject.__send__(als, :awesome) do inner_namespace = namespace end expect(inner_namespace).to eq '/awesome' end end end describe '.call' do context 'it does not add to the app setup' do it 'calls the app' do expect(subject).not_to receive(:add_setup) subject.call({}) end end end describe '.route_param' do it 'adds a parameterized route segment namespace' do subject.namespace :users do route_param :id do get do params[:id] end end end get '/users/23' expect(last_response.body).to eq('23') end it 'defines requirements with a single hash' do subject.namespace :users do route_param :id, requirements: /[0-9]+/ do get do params[:id] end end end get '/users/michael' expect(last_response).to be_not_found get '/users/23' expect(last_response).to be_successful end context 'with param type definitions' do it 'is used by passing to options' do subject.namespace :route_param do route_param :foo, type: Integer do get { params.to_json } end end get '/route_param/1234' expect(last_response.body).to eq('{"foo":1234}') end end end describe '.route' do it 'allows for no path' do subject.namespace :votes do get do 'Votes' end post do 'Created a Vote' end end get '/votes' expect(last_response.body).to eql 'Votes' post '/votes' expect(last_response.body).to eql 'Created a Vote' end it 'handles empty calls' do subject.get '/' get '/' expect(last_response.body).to eql '' end describe 'root routes should work with' do before do subject.format :txt subject.content_type :json, 'application/json' subject.formatter :json, ->(object, _env) { object } def subject.enable_root_route! get('/') { 'root' } end end shared_examples_for 'a root route' do it 'returns root' do expect(last_response.body).to eql 'root' end end describe 'path versioned APIs' do before do subject.version version, using: :path subject.enable_root_route! end context 'when a single version provided' do let(:version) { 'v1' } context 'without a format' do before do versioned_get '/', 'v1', using: :path end it_behaves_like 'a root route' end context 'with a format' do before do get '/v1/.json' end it_behaves_like 'a root route' end end context 'when array of versions provided' do let(:version) { %w[v1 v2] } context 'when v1' do before do versioned_get '/', 'v1', using: :path end it_behaves_like 'a root route' end context 'when v2' do before do versioned_get '/', 'v2', using: :path end it_behaves_like 'a root route' end end end context 'when header versioned APIs' do before do subject.version 'v1', using: :header, vendor: 'test' subject.enable_root_route! versioned_get '/', 'v1', using: :header, vendor: 'test' end it_behaves_like 'a root route' end context 'when header versioned APIs with multiple headers' do before do subject.version %w[v1 v2], using: :header, vendor: 'test' subject.enable_root_route! end context 'when v1' do before do versioned_get '/', 'v1', using: :header, vendor: 'test' end it_behaves_like 'a root route' end context 'when v2' do before do versioned_get '/', 'v2', using: :header, vendor: 'test' end it_behaves_like 'a root route' end end context 'param versioned APIs' do before do subject.version 'v1', using: :param subject.enable_root_route! versioned_get '/', 'v1', using: :param end it_behaves_like 'a root route' end context 'when Accept-Version header versioned APIs' do before do subject.version 'v1', using: :accept_version_header subject.enable_root_route! versioned_get '/', 'v1', using: :accept_version_header end it_behaves_like 'a root route' end context 'unversioned APIss' do before do subject.enable_root_route! get '/' end it_behaves_like 'a root route' end end it 'allows for multiple paths' do subject.get(['/abc', '/def']) do 'foo' end get '/abc' expect(last_response.body).to eql 'foo' get '/def' expect(last_response.body).to eql 'foo' end context 'format' do before do dummy_class = Class.new do def to_json(*_rest) 'abc' end def to_txt 'def' end end subject.get('/abc') do dummy_class.new end end it 'allows .json' do get '/abc.json' expect(last_response).to be_successful expect(last_response.body).to eql 'abc' # json-encoded symbol end it 'allows .txt' do get '/abc.txt' expect(last_response).to be_successful expect(last_response.body).to eql 'def' # raw text end end it 'allows for format without corrupting a param' do subject.get('/:id') do { 'id' => params[:id] } end get '/awesome.json' expect(last_response.body).to eql '{"id":"awesome"}' end it 'allows for format in namespace with no path' do subject.namespace :abc do get do ['json'] end end get '/abc.json' expect(last_response.body).to eql '["json"]' end it 'allows for multiple verbs' do subject.route(%i[get post], '/abc') do 'hiya' end subject.endpoints.first.routes.each do |route| expect(route.path).to eql '/abc(.:format)' end get '/abc' expect(last_response.body).to eql 'hiya' post '/abc' expect(last_response.body).to eql 'hiya' end objects = ['string', :symbol, 1, -1.1, {}, [], true, false, nil].freeze %i[put post].each do |verb| context verb.to_s do objects.each do |object| it "allows a(n) #{object.class} json object in params" do subject.format :json subject.__send__(verb) do env[Grape::Env::API_REQUEST_BODY] end __send__ verb, '/', Grape::Json.dump(object), 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq(verb == :post ? 201 : 200) expect(last_response.body).to eql Grape::Json.dump(object) expect(last_request.params).to eql({}) end it 'stores input in api.request.input' do subject.format :json subject.__send__(verb) do env[Grape::Env::API_REQUEST_INPUT] end __send__ verb, '/', Grape::Json.dump(object), 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq(verb == :post ? 201 : 200) expect(last_response.body).to eql Grape::Json.dump(object).to_json end context 'chunked transfer encoding' do it 'stores input in api.request.input' do subject.format :json subject.__send__(verb) do env[Grape::Env::API_REQUEST_INPUT] end __send__ verb, '/', Grape::Json.dump(object), 'CONTENT_TYPE' => 'application/json', 'HTTP_TRANSFER_ENCODING' => 'chunked' expect(last_response.status).to eq(verb == :post ? 201 : 200) expect(last_response.body).to eql Grape::Json.dump(object).to_json end end end end end it 'allows for multipart paths' do subject.route(%i[get post], '/:id/first') do 'first' end subject.route(%i[get post], '/:id') do 'ola' end subject.route(%i[get post], '/:id/first/second') do 'second' end get '/1' expect(last_response.body).to eql 'ola' post '/1' expect(last_response.body).to eql 'ola' get '/1/first' expect(last_response.body).to eql 'first' post '/1/first' expect(last_response.body).to eql 'first' get '/1/first/second' expect(last_response.body).to eql 'second' end it 'allows for :any as a verb' do subject.route(:any, '/abc') do 'lol' end %w[get post put delete options patch].each do |m| __send__(m, '/abc') expect(last_response.body).to eql 'lol' end end it 'allows for catch-all in a namespace' do subject.namespace :nested do get do 'root' end get 'something' do 'something' end route :any, '*path' do 'catch-all' end end get 'nested' expect(last_response.body).to eql 'root' get 'nested/something' expect(last_response.body).to eql 'something' get 'nested/missing' expect(last_response.body).to eql 'catch-all' post 'nested' expect(last_response.body).to eql 'catch-all' post 'nested/something' expect(last_response.body).to eql 'catch-all' end verbs = %w[post get head delete put options patch] verbs.each do |verb| it "allows and properly constrain a #{verb.upcase} method" do subject.__send__(verb, '/example') do verb end __send__(verb, '/example') expect(last_response.body).to eql verb == 'head' ? '' : verb # Call it with all methods other than the properly constrained one. (verbs - [verb]).each do |other_verb| __send__(other_verb, '/example') expected_rc = if other_verb == 'options' then 204 elsif other_verb == 'head' && verb == 'get' then 200 else 405 end expect(last_response.status).to eql expected_rc end end end it 'returns a 201 response code for POST by default' do subject.post('example') do 'Created' end post '/example' expect(last_response).to be_created expect(last_response.body).to eql 'Created' end it 'returns a 405 for an unsupported method with an X-Custom-Header' do subject.before { header 'X-Custom-Header', 'foo' } subject.get 'example' do 'example' end put '/example' expect(last_response).to be_method_not_allowed expect(last_response.body).to eql '405 Not Allowed' expect(last_response.headers['X-Custom-Header']).to eql 'foo' end it 'runs only the before filter on 405 bad method' do subject.namespace :example do before { header 'X-Custom-Header', 'foo' } before_validation { raise 'before_validation filter should not run' } after_validation { raise 'after_validation filter should not run' } after { raise 'after filter should not run' } params { requires :only_for_get } get end post '/example' expect(last_response).to be_method_not_allowed expect(last_response.headers['X-Custom-Header']).to eql 'foo' end it 'runs before filter exactly once on 405 bad method' do already_run = false subject.namespace :example do before do raise 'before filter ran twice' if already_run already_run = true header 'X-Custom-Header', 'foo' end get end post '/example' expect(last_response).to be_method_not_allowed expect(last_response.headers['X-Custom-Header']).to eql 'foo' end it 'runs all filters and body with a custom OPTIONS method' do subject.namespace :example do before { header 'X-Custom-Header-1', 'foo' } before_validation { header 'X-Custom-Header-2', 'foo' } after_validation { header 'X-Custom-Header-3', 'foo' } after { header 'X-Custom-Header-4', 'foo' } options { 'yup' } get end options '/example' expect(last_response).to be_successful expect(last_response.body).to eql 'yup' expect(last_response.headers['Allow']).to be_nil expect(last_response.headers['X-Custom-Header-1']).to eql 'foo' expect(last_response.headers['X-Custom-Header-2']).to eql 'foo' expect(last_response.headers['X-Custom-Header-3']).to eql 'foo' expect(last_response.headers['X-Custom-Header-4']).to eql 'foo' end context 'when format is xml' do it 'returns a 405 for an unsupported method' do subject.format :xml subject.get 'example' do 'example' end put '/example' expect(last_response).to be_method_not_allowed expect(last_response.body).to eq <<~XML <?xml version="1.0" encoding="UTF-8"?> <error> <message>405 Not Allowed</message> </error> XML end end context 'when accessing env' do it 'returns a 405 for an unsupported method' do subject.before do _customheader1 = headers['X-Custom-Header'] _customheader2 = env['HTTP_X_CUSTOM_HEADER'] end subject.get 'example' do 'example' end put '/example' expect(last_response).to be_method_not_allowed expect(last_response.body).to eql '405 Not Allowed' end end specify '405 responses includes an Allow header specifying supported methods' do subject.get 'example' do 'example' end subject.post 'example' do 'example' end put '/example' expect(last_response.headers['Allow']).to eql 'OPTIONS, GET, POST, HEAD' end specify '405 responses includes an Content-Type header' do subject.get 'example' do 'example' end subject.post 'example' do 'example' end put '/example' expect(last_response.content_type).to eql 'text/plain' end describe 'adds an OPTIONS route that' do before do subject.before { header 'X-Custom-Header', 'foo' } subject.before_validation { header 'X-Custom-Header-2', 'bar' } subject.after_validation { header 'X-Custom-Header-3', 'baz' } subject.after { header 'X-Custom-Header-4', 'bing' } subject.params { requires :only_for_get } subject.get 'example' do 'example' end subject.route :any, '*path' do error! :not_found, 404 end options '/example' end it 'returns a 204' do expect(last_response).to be_no_content end it 'has an empty body' do expect(last_response.body).to be_blank end it 'has an Allow header' do expect(last_response.headers['Allow']).to eql 'OPTIONS, GET, HEAD' end it 'calls before hook' do expect(last_response.headers['X-Custom-Header']).to eql 'foo' end it 'does not call before_validation hook' do expect(last_response.headers.key?('X-Custom-Header-2')).to be false end it 'does not call after_validation hook' do expect(last_response.headers.key?('X-Custom-Header-3')).to be false end it 'calls after hook' do expect(last_response.headers['X-Custom-Header-4']).to eq 'bing' end it 'has no Content-Type' do expect(last_response.content_type).to be_nil end it 'has no Content-Length' do expect(last_response.content_length).to be_nil end end describe 'when a resource routes by POST, GET, PATCH, PUT, and DELETE' do before do subject.namespace :example do get do 'example' end patch do 'example' end post do 'example' end delete do 'example' end put do 'example' end end options '/example' end describe 'it adds an OPTIONS route for namespaced endpoints that' do it 'returns a 204' do expect(last_response).to be_no_content end it 'has an empty body' do expect(last_response.body).to be_blank end it 'has an Allow header' do expect(last_response.headers['Allow']).to eql 'OPTIONS, GET, PATCH, POST, DELETE, PUT, HEAD' end end end describe 'adds an OPTIONS route for namespaced endpoints that' do before do subject.before { header 'X-Custom-Header', 'foo' } subject.namespace :example do before { header 'X-Custom-Header-2', 'foo' } get :inner do 'example/inner' end end options '/example/inner' end it 'returns a 204' do expect(last_response).to be_no_content end it 'has an empty body' do expect(last_response.body).to be_blank end it 'has an Allow header' do expect(last_response.headers['Allow']).to eql 'OPTIONS, GET, HEAD' end it 'calls the outer before filter' do expect(last_response.headers['X-Custom-Header']).to eql 'foo' end it 'calls the inner before filter' do expect(last_response.headers['X-Custom-Header-2']).to eql 'foo' end it 'has no Content-Type' do expect(last_response.content_type).to be_nil end it 'has no Content-Length' do expect(last_response.content_length).to be_nil end end describe 'adds a 405 Not Allowed route that' do before do subject.before { header 'X-Custom-Header', 'foo' } subject.post :example do 'example' end get '/example' end it 'returns a 405' do expect(last_response).to be_method_not_allowed end it 'contains error message in body' do expect(last_response.body).to eq '405 Not Allowed' end it 'has an Allow header' do expect(last_response.headers['Allow']).to eql 'OPTIONS, POST' end it 'has a X-Custom-Header' do expect(last_response.headers['X-Custom-Header']).to eql 'foo' end end describe 'when hook behaviour is controlled by attributes on the route' do before do subject.before do error!('Access Denied', 401) unless route.options[:secret] == params[:secret] end subject.namespace 'example' do before do error!('Access Denied', 401) unless route.options[:namespace_secret] == params[:namespace_secret] end desc 'it gets with secret', secret: 'password' get { status(params[:id] == '504' ? 200 : 404) } desc 'it post with secret', secret: 'password', namespace_secret: 'namespace_password' post {} end end context 'when HTTP method is not defined' do let(:response) { delete('/example') } it 'responds with a 405 status' do expect(response).to be_method_not_allowed end end context 'when HTTP method is defined with attribute' do let(:response) { post('/example?secret=incorrect_password') } it 'responds with the defined error in the before hook' do expect(response).to be_unauthorized end end context 'when HTTP method is defined and the underlying before hook expectation is not met' do let(:response) { post('/example?secret=password&namespace_secret=wrong_namespace_password') } it 'ends up in the endpoint' do expect(response).to be_unauthorized end end context 'when HTTP method is defined and everything is like the before hooks expect' do let(:response) { post('/example?secret=password&namespace_secret=namespace_password') } it 'ends up in the endpoint' do expect(response).to be_created end end context 'when HEAD is called for the defined GET' do let(:response) { head('/example?id=504') } it 'responds with 401 because before expectations in before hooks are not met' do expect(response).to be_unauthorized end end context 'when HEAD is called for the defined GET' do let(:response) { head('/example?id=504&secret=password') } it 'responds with 200 because before hooks are not called' do expect(response).to be_successful end end end context 'allows HEAD on a GET request that' do before do subject.get 'example' do 'example' end subject.route :any, '*path' do error! :not_found, 404 end head '/example' end it 'returns a 200' do expect(last_response).to be_successful end it 'has an empty body' do expect(last_response.body).to eql '' end end it 'overwrites the default HEAD request' do subject.head 'example' do error! 'nothing to see here', 400 end subject.get 'example' do 'example' end head '/example' expect(last_response).to be_bad_request end end context 'do_not_route_head!' do before do subject.do_not_route_head! subject.get 'example' do 'example' end end it 'options does not contain HEAD' do options '/example' expect(last_response).to be_no_content expect(last_response.body).to eql '' expect(last_response.headers['Allow']).to eql 'OPTIONS, GET' end it 'does not allow HEAD on a GET request' do head '/example' expect(last_response).to be_method_not_allowed end end context 'do_not_route_options!' do before do subject.do_not_route_options! subject.get 'example' do 'example' end end it 'does not create an OPTIONS route' do options '/example' expect(last_response).to be_method_not_allowed end it 'does not include OPTIONS in Allow header' do options '/example' expect(last_response).to be_method_not_allowed expect(last_response.headers['Allow']).to eql 'GET, HEAD' end end describe '.compile!' do let(:base_instance) { app.base_instance } before do allow(base_instance).to receive(:compile!).and_return(:compiled!) end it 'returns compiled!' do expect(app.__send__(:compile!)).to eq(:compiled!) end end describe 'filters' do it 'adds a before filter' do subject.before { @foo = 'first' } subject.before { @bar = 'second' } subject.get '/' do "#{@foo} #{@bar}" end get '/' expect(last_response.body).to eql 'first second' end it 'adds a before filter to current and child namespaces only' do subject.get '/' do "root - #{@foo if instance_variable_defined?(:@foo)}" end subject.namespace :blah do before { @foo = 'foo' } get '/' do "blah - #{@foo}" end namespace :bar do get '/' do "blah - bar - #{@foo}" end end end get '/' expect(last_response.body).to eql 'root - ' get '/blah' expect(last_response.body).to eql 'blah - foo' get '/blah/bar' expect(last_response.body).to eql 'blah - bar - foo' end it 'adds a after_validation filter' do subject.after_validation { @foo = "first #{params[:id]}:#{params[:id].class}" } subject.after_validation { @bar = 'second' } subject.params do requires :id, type: Integer end subject.get '/' do "#{@foo} #{@bar}" end get '/', id: '32' expect(last_response.body).to eql "first 32:#{integer_class_name} second" end it 'adds a after filter' do m = double('after mock') subject.after { m.do_something! } subject.after { m.do_something! } subject.get '/' do @var ||= 'default' end expect(m).to receive(:do_something!).twice get '/' expect(last_response.body).to eql 'default' end it 'calls all filters when validation passes' do a = double('before mock') b = double('before_validation mock') c = double('after_validation mock') d = double('after mock') subject.params do requires :id, type: Integer end subject.resource ':id' do before { a.do_something! } before_validation { b.do_something! } after_validation { c.do_something! } after { d.do_something! } get do 'got it' end end expect(a).to receive(:do_something!).once expect(b).to receive(:do_something!).once expect(c).to receive(:do_something!).once expect(d).to receive(:do_something!).once get '/123' expect(last_response).to be_successful expect(last_response.body).to eql 'got it' end it 'calls only before filters when validation fails' do a = double('before mock') b = double('before_validation mock') c = double('after_validation mock') d = double('after mock') subject.params do requires :id, type: Integer, values: [1, 2, 3] end subject.resource ':id' do before { a.do_something! } before_validation { b.do_something! } after_validation { c.do_something! } after { d.do_something! } get do 'got it' end end expect(a).to receive(:do_something!).once expect(b).to receive(:do_something!).once expect(c).to receive(:do_something!).exactly(0).times expect(d).to receive(:do_something!).exactly(0).times get '/4' expect(last_response).to be_bad_request expect(last_response.body).to eql 'id does not have a valid value' end it 'calls filters in the correct order' do i = 0 a = double('before mock') b = double('before_validation mock') c = double('after_validation mock') d = double('after mock') subject.params do requires :id, type: Integer end subject.resource ':id' do before { a.here(i += 1) } before_validation { b.here(i += 1) } after_validation { c.here(i += 1) } after { d.here(i += 1) } get do 'got it' end end expect(a).to receive(:here).with(1).once expect(b).to receive(:here).with(2).once expect(c).to receive(:here).with(3).once expect(d).to receive(:here).with(4).once get '/123' expect(last_response).to be_successful expect(last_response.body).to eql 'got it' end end context 'format' do before do subject.get('/foo') { 'bar' } end it 'sets content type for txt format' do get '/foo' expect(last_response.content_type).to eq('text/plain') end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
true
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations_spec.rb
spec/grape/validations_spec.rb
# frozen_string_literal: true describe Grape::Validations do subject { Class.new(Grape::API) } let(:app) { subject } describe 'params' do context 'optional' do before do subject.params do optional :a_number, regexp: /^[0-9]+$/ optional :attachment, type: File end subject.get '/optional' do 'optional works!' end end it 'validates when params is present' do get '/optional', a_number: 'string' expect(last_response.status).to eq(400) expect(last_response.body).to eq('a_number is invalid') get '/optional', a_number: 45 expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional works!') end it "doesn't validate when param not present" do get '/optional', a_number: nil, attachment: nil expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional works!') end it 'adds to declared parameters' do subject.params do optional :some_param end subject.format :json subject.get('/') do declared(params) end env = Rack::MockRequest.env_for('/', method: Rack::GET) response = Rack::MockResponse[*subject.call(env)] expect(JSON.parse(response.body)).to eq('some_param' => nil) end end context 'optional using Grape::Entity documentation' do def define_optional_using documentation = { field_a: { type: String }, field_b: { type: String } } subject.params do optional :all, using: documentation end end before do define_optional_using subject.get '/optional' do 'optional with using works' end end it 'adds entity documentation to declared params' do define_optional_using subject.format :json subject.get('/') do declared(params) end env = Rack::MockRequest.env_for('/', method: Rack::GET, params: { field_a: 'field_a', field_b: 'field_b' }) response = Rack::MockResponse[*subject.call(env)] expect(JSON.parse(response.body)).to eq('field_a' => 'field_a', 'field_b' => 'field_b') end it 'works when field_a and field_b are not present' do get '/optional' expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional with using works') end it 'works when field_a is present' do get '/optional', field_a: 'woof' expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional with using works') end it 'works when field_b is present' do get '/optional', field_b: 'woof' expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional with using works') end end context 'required' do before do subject.params do requires :key, type: String end subject.get('/required') { 'required works' } subject.put('/required') { { key: params[:key] }.to_json } end it 'errors when param not present' do get '/required' expect(last_response.status).to eq(400) expect(last_response.body).to eq('key is missing') end it "doesn't throw a missing param when param is present" do get '/required', key: 'cool' expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end it 'adds to declared parameters' do subject.params do requires :some_param end subject.format :json subject.get('/') do declared(params) end env = Rack::MockRequest.env_for('/', method: Rack::GET, params: { some_param: 'some_param' }) response = Rack::MockResponse[*subject.call(env)] expect(JSON.parse(response.body)).to eq('some_param' => 'some_param') end it 'works when required field is present but nil' do put '/required', { key: nil }.to_json, 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq(200) expect(JSON.parse(last_response.body)).to eq('key' => nil) end end context 'requires with nested params' do before do subject.params do requires :first_level, type: Hash do optional :second_level, type: Array do requires :value, type: Integer optional :name, type: String optional :third_level, type: Array do requires :value, type: Integer optional :name, type: String optional :fourth_level, type: Array do requires :value, type: Integer optional :name, type: String end end end end end subject.put('/required') { 'required works' } end let(:request_params) do { first_level: { second_level: [ { value: 1, name: 'Lisa' }, { value: 2, name: 'James', third_level: [ { value: 'three', name: 'Sophie' }, { value: 4, name: 'Jenny', fourth_level: [ { name: 'Samuel' }, { value: 6, name: 'Jane' } ] } ] } ] } } end it 'validates correctly in deep nested params' do put '/required', request_params.to_json, 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq(400) expect(last_response.body).to eq( 'first_level[second_level][1][third_level][0][value] is invalid, ' \ 'first_level[second_level][1][third_level][1][fourth_level][0][value] is missing' ) end end context 'requires :all using Grape::Entity documentation' do def define_requires_all documentation = { required_field: { type: String, required: true, param_type: 'query' }, optional_field: { type: String }, optional_array_field: { type: Array[String], is_array: true } } subject.params do requires :all, except: %i[optional_field optional_array_field], using: documentation end end before do define_requires_all subject.get '/required' do 'required works' end end it 'adds entity documentation to declared params' do define_requires_all subject.format :json subject.get('/') do declared(params) end env = Rack::MockRequest.env_for('/', method: Rack::GET, params: { required_field: 'required_field', optional_field: 'optional_field', optional_array_field: ['optional_array_field'] }) response = Rack::MockResponse[*subject.call(env)] expect(JSON.parse(response.body)).to eq('required_field' => 'required_field', 'optional_field' => 'optional_field', 'optional_array_field' => ['optional_array_field']) end it 'errors when required_field is not present' do get '/required' expect(last_response.status).to eq(400) expect(last_response.body).to eq('required_field is missing') end it 'works when required_field is present' do get '/required', required_field: 'woof' expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end end context 'requires :none using Grape::Entity documentation' do def define_requires_none documentation = { required_field: { type: String, example: 'Foo' }, optional_field: { type: Integer, format: 'int64' } } subject.params do requires :none, except: :required_field, using: documentation end end before do define_requires_none subject.get '/required' do 'required works' end end it 'adds entity documentation to declared params' do define_requires_none subject.format :json subject.get('/') do declared(params) end env = Rack::MockRequest.env_for('/', method: Rack::GET, params: { required_field: 'required_field', optional_field: 1 }) response = Rack::MockResponse[*subject.call(env)] expect(JSON.parse(response.body)).to eq('required_field' => 'required_field', 'optional_field' => 1) end it 'errors when required_field is not present' do get '/required' expect(last_response.status).to eq(400) expect(last_response.body).to eq('required_field is missing') end it 'works when required_field is present' do get '/required', required_field: 'woof' expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end end context 'requires :all or :none but except a non-existent field using Grape::Entity documentation' do context 'requires :all' do def define_requires_all documentation = { required_field: { type: String }, optional_field: { type: String } } subject.params do requires :all, except: :non_existent_field, using: documentation end end it 'adds only the entity documentation to declared params, nothing more' do define_requires_all subject.format :json subject.get('/') do declared(params) end env = Rack::MockRequest.env_for('/', method: Rack::GET, params: { required_field: 'required_field', optional_field: 'optional_field' }) response = Rack::MockResponse[*subject.call(env)] expect(JSON.parse(response.body)).to eq('required_field' => 'required_field', 'optional_field' => 'optional_field') end end context 'requires :none' do def define_requires_none documentation = { required_field: { type: String }, optional_field: { type: String } } subject.params do requires :none, except: :non_existent_field, using: documentation end end it 'adds only the entity documentation to declared params, nothing more' do expect { define_requires_none }.to raise_error(ArgumentError) end end end context 'required with an Array block' do before do subject.params do requires :items, type: Array do requires :key end end subject.get('/required') { 'required works' } subject.put('/required') { { items: params[:items] }.to_json } end it 'errors when param not present' do get '/required' expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is missing') end it 'errors when param is not an Array' do get '/required', items: 'hello' expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid') get '/required', items: { key: 'foo' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid') end it "doesn't throw a missing param when param is present" do get '/required', items: [{ key: 'hello' }, { key: 'world' }] expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end it "doesn't throw a missing param when param is present but empty" do put '/required', { items: [] }.to_json, 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq(200) expect(JSON.parse(last_response.body)).to eq('items' => []) end it 'adds to declared parameters' do subject.format :json subject.params do requires :items, type: Array do requires :key end end subject.get('/') do declared(params) end env = Rack::MockRequest.env_for('/', method: Rack::GET, params: { items: [key: 'my_key'] }) response = Rack::MockResponse[*subject.call(env)] expect(JSON.parse(response.body)).to eq('items' => ['key' => 'my_key']) end end # Ensure there is no leakage between declared Array types and # subsequent Hash types context 'required with an Array and a Hash block' do before do subject.params do requires :cats, type: Array[String], default: [] requires :items, type: Hash do requires :key end end subject.get '/required' do 'required works' end end it 'does not output index [0] for Hash types' do get '/required', cats: ['Garfield'], items: { foo: 'bar' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('items[key] is missing') end end context 'required with a Hash block' do before do subject.params do requires :items, type: Hash do requires :key end end subject.get '/required' do 'required works' end end it 'errors when param not present' do get '/required' expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is missing, items[key] is missing') end it 'errors when nested param not present' do get '/required', items: { foo: 'bar' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('items[key] is missing') end it 'errors when param is not a Hash' do get '/required', items: 'hello' expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid, items[key] is missing') get '/required', items: [{ key: 'foo' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid') end it "doesn't throw a missing param when param is present" do get '/required', items: { key: 'hello' } expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end it 'adds to declared parameters' do subject.params do requires :items, type: Array do requires :key end end subject.format :json subject.get('/') do declared(params) end env = Rack::MockRequest.env_for('/', method: Rack::GET, params: { items: [key: :my_key] }) response = Rack::MockResponse[*subject.call(env)] expect(JSON.parse(response.body)).to eq('items' => ['key' => 'my_key']) end end context 'hash with a required param with validation' do before do subject.params do requires :items, type: Hash do requires :key, type: String, values: %w[a b] end end subject.get '/required' do 'required works' end end it 'errors when param is not a Hash' do get '/required', items: 'not a hash' expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid, items[key] is missing, items[key] is invalid') get '/required', items: [{ key: 'hash in array' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid, items[key] does not have a valid value') end it 'works when all params match' do get '/required', items: { key: 'a' } expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end end context 'group' do before do subject.params do group :items, type: Array do requires :key end end subject.get '/required' do 'required works' end end it 'errors when param not present' do get '/required' expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is missing') end it "doesn't throw a missing param when param is present" do get '/required', items: [key: 'hello'] expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end it 'adds to declared parameters' do subject.format :json subject.params do group :items, type: Array do requires :key end end subject.get('/') do declared(params) end env = Rack::MockRequest.env_for('/', method: Rack::GET, params: { items: [key: :my_key] }) response = Rack::MockResponse[*subject.call(env)] expect(JSON.parse(response.body)).to eq('items' => ['key' => 'my_key']) end end context 'group params with nested params which has a type' do let(:invalid_items) { { items: '' } } before do subject.params do optional :items, type: Array do optional :key1, type: String optional :key2, type: String end end subject.post '/group_with_nested' do 'group with nested works' end end it 'errors when group param is invalid' do post '/group_with_nested', items: invalid_items expect(last_response.status).to eq(400) end end context 'custom validator for a Hash' do let(:date_range_validator) do Class.new(Grape::Validations::Validators::Base) do def validate_param!(attr_name, params) return if params[attr_name][:from] <= params[attr_name][:to] raise Grape::Exceptions::Validation.new(params: [@scope.full_name(attr_name)], message: "'from' must be lower or equal to 'to'") end end end before do stub_const('DateRangeValidator', date_range_validator) described_class.register(DateRangeValidator) subject.params do optional :date_range, date_range: true, type: Hash do requires :from, type: Integer requires :to, type: Integer end end subject.get('/optional') do 'optional works' end subject.params do requires :date_range, date_range: true, type: Hash do requires :from, type: Integer requires :to, type: Integer end end subject.get('/required') do 'required works' end end after do described_class.deregister(:date_range) end context 'which is optional' do it "doesn't throw an error if the validation passes" do get '/optional', date_range: { from: 1, to: 2 } expect(last_response.status).to eq(200) end it 'errors if the validation fails' do get '/optional', date_range: { from: 2, to: 1 } expect(last_response.status).to eq(400) end end context 'which is required' do it "doesn't throw an error if the validation passes" do get '/required', date_range: { from: 1, to: 2 } expect(last_response.status).to eq(200) end it 'errors if the validation fails' do get '/required', date_range: { from: 2, to: 1 } expect(last_response.status).to eq(400) end end end context 'validation within arrays' do before do subject.params do group :children, type: Array do requires :name group :parents, type: Array do requires :name, allow_blank: false end end end subject.get '/within_array' do 'within array works' end end it 'can handle new scopes within child elements' do get '/within_array', children: [ { name: 'John', parents: [{ name: 'Jane' }, { name: 'Bob' }] }, { name: 'Joe', parents: [{ name: 'Josie' }] } ] expect(last_response.status).to eq(200) expect(last_response.body).to eq('within array works') end it 'errors when a parameter is not present' do get '/within_array', children: [ { name: 'Jim', parents: [{ name: 'Joy' }] }, { name: 'Job', parents: [{}] } ] # NOTE: with body parameters in json or XML or similar this # should actually fail with: children[parents][name] is missing. expect(last_response.status).to eq(400) expect(last_response.body).to eq('children[1][parents] is missing, children[0][parents][1][name] is missing, children[0][parents][1][name] is empty') end it 'errors when a parameter is not present in array within array' do get '/within_array', children: [ { name: 'Jim', parents: [{ name: 'Joy' }] }, { name: 'Job', parents: [{ name: 'Bill' }, { name: '' }] } ] expect(last_response.status).to eq(400) expect(last_response.body).to eq('children[1][parents][1][name] is empty') end it 'handle errors for all array elements' do get '/within_array', children: [ { name: 'Jim', parents: [] }, { name: 'Job', parents: [] } ] expect(last_response.status).to eq(400) expect(last_response.body).to eq( 'children[0][parents][0][name] is missing, ' \ 'children[1][parents][0][name] is missing' ) end it 'safely handles empty arrays and blank parameters' do # NOTE: with body parameters in json or XML or similar this # should actually return 200, since an empty array is valid. get '/within_array', children: [] expect(last_response.status).to eq(400) expect(last_response.body).to eq( 'children[0][name] is missing, ' \ 'children[0][parents] is missing, ' \ 'children[0][parents] is invalid, ' \ 'children[0][parents][0][name] is missing, ' \ 'children[0][parents][0][name] is empty' ) get '/within_array', children: [name: 'Jay'] expect(last_response.status).to eq(400) expect(last_response.body).to eq('children[0][parents] is missing, children[0][parents][0][name] is missing, children[0][parents][0][name] is empty') end it 'errors when param is not an Array' do get '/within_array', children: 'hello' expect(last_response.status).to eq(400) expect(last_response.body).to eq('children is invalid') get '/within_array', children: { name: 'foo' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('children is invalid') get '/within_array', children: [name: 'Jay', parents: { name: 'Fred' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('children[0][parents] is invalid') end end context 'with block param' do before do subject.params do requires :planets, type: Array do requires :name end end subject.get '/req' do 'within array works' end subject.put '/req' do '' end subject.params do group :stars, type: Array do requires :name end end subject.get '/grp' do 'within array works' end subject.put '/grp' do '' end subject.params do requires :name optional :moons, type: Array do requires :name end end subject.get '/opt' do 'within array works' end subject.put '/opt' do '' end end it 'requires defaults to Array type' do get '/req', planets: 'Jupiter, Saturn' expect(last_response.status).to eq(400) expect(last_response.body).to eq('planets is invalid') get '/req', planets: { name: 'Jupiter' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('planets is invalid') get '/req', planets: [{ name: 'Venus' }, { name: 'Mars' }] expect(last_response.status).to eq(200) put_with_json '/req', planets: [] expect(last_response.status).to eq(200) end it 'optional defaults to Array type' do get '/opt', name: 'Jupiter', moons: 'Europa, Ganymede' expect(last_response.status).to eq(400) expect(last_response.body).to eq('moons is invalid') get '/opt', name: 'Jupiter', moons: { name: 'Ganymede' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('moons is invalid') get '/opt', name: 'Jupiter', moons: [{ name: 'Io' }, { name: 'Callisto' }] expect(last_response.status).to eq(200) put_with_json '/opt', name: 'Venus' expect(last_response.status).to eq(200) put_with_json '/opt', name: 'Mercury', moons: [] expect(last_response.status).to eq(200) end it 'group defaults to Array type' do get '/grp', stars: 'Sun' expect(last_response.status).to eq(400) expect(last_response.body).to eq('stars is invalid') get '/grp', stars: { name: 'Sun' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('stars is invalid') get '/grp', stars: [{ name: 'Sun' }] expect(last_response.status).to eq(200) put_with_json '/grp', stars: [] expect(last_response.status).to eq(200) end end context 'validation within arrays with JSON' do before do subject.params do group :children, type: Array do requires :name group :parents, type: Array do requires :name end end end subject.put '/within_array' do 'within array works' end end it 'can handle new scopes within child elements' do put_with_json '/within_array', children: [ { name: 'John', parents: [{ name: 'Jane' }, { name: 'Bob' }] }, { name: 'Joe', parents: [{ name: 'Josie' }] } ] expect(last_response.status).to eq(200) expect(last_response.body).to eq('within array works') end it 'errors when a parameter is not present' do put_with_json '/within_array', children: [ { name: 'Jim', parents: [{}] }, { name: 'Job', parents: [{ name: 'Joy' }] } ] expect(last_response.status).to eq(400) expect(last_response.body).to eq('children[0][parents][0][name] is missing') end it 'safely handles empty arrays and blank parameters' do put_with_json '/within_array', children: [] expect(last_response.status).to eq(200) put_with_json '/within_array', children: [name: 'Jay'] expect(last_response.status).to eq(400) expect(last_response.body).to eq('children[0][parents] is missing, children[0][parents][0][name] is missing') end end context 'optional with an Array block' do before do subject.params do optional :items, type: Array do requires :key end end subject.get '/optional_group' do 'optional group works' end end it "doesn't throw a missing param when the group isn't present" do get '/optional_group' expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional group works') end it "doesn't throw a missing param when both group and param are given" do get '/optional_group', items: [{ key: 'foo' }] expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional group works') end it 'errors when group is present, but required param is not' do get '/optional_group', items: [{ not_key: 'foo' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('items[0][key] is missing') end it "errors when param is present but isn't an Array" do get '/optional_group', items: 'hello' expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid') get '/optional_group', items: { key: 'foo' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid') end it 'adds to declared parameters' do subject.format :json subject.params do optional :items, type: Array do requires :key end end subject.get('/') do declared(params) end env = Rack::MockRequest.env_for('/', method: Rack::GET, params: { items: [key: :my_key] }) response = Rack::MockResponse[*subject.call(env)] expect(JSON.parse(response.body)).to eq('items' => ['key' => 'my_key']) end end context 'nested optional Array blocks' do before do subject.params do optional :items, type: Array do requires :key optional(:optional_subitems, type: Array) { requires :value } requires(:required_subitems, type: Array) { requires :value } end end subject.get('/nested_optional_group') { 'nested optional group works' } end it 'does no internal validations if the outer group is blank' do get '/nested_optional_group' expect(last_response.status).to eq(200) expect(last_response.body).to eq('nested optional group works') end it 'does internal validations if the outer group is present' do get '/nested_optional_group', items: [{ key: 'foo' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('items[0][required_subitems] is missing, items[0][required_subitems][0][value] is missing') get '/nested_optional_group', items: [{ key: 'foo', required_subitems: [{ value: 'bar' }] }] expect(last_response.status).to eq(200) expect(last_response.body).to eq('nested optional group works') end it 'handles deep nesting' do get '/nested_optional_group', items: [{ key: 'foo', required_subitems: [{ value: 'bar' }], optional_subitems: [{ not_value: 'baz' }] }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('items[0][optional_subitems][0][value] is missing') get '/nested_optional_group', items: [{ key: 'foo', required_subitems: [{ value: 'bar' }], optional_subitems: [{ value: 'baz' }] }] expect(last_response.status).to eq(200) expect(last_response.body).to eq('nested optional group works') end it 'handles validation within arrays' do get '/nested_optional_group', items: [{ key: 'foo' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('items[0][required_subitems] is missing, items[0][required_subitems][0][value] is missing') get '/nested_optional_group', items: [{ key: 'foo', required_subitems: [{ value: 'bar' }] }] expect(last_response.status).to eq(200) expect(last_response.body).to eq('nested optional group works') get '/nested_optional_group', items: [{ key: 'foo', required_subitems: [{ value: 'bar' }], optional_subitems: [{ not_value: 'baz' }] }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('items[0][optional_subitems][0][value] is missing') end it 'adds to declared parameters' do subject.params do optional :items, type: Array do requires :key optional(:optional_subitems, type: Array) { requires :value } requires(:required_subitems, type: Array) { requires :value } end end subject.format :json subject.get('/') do declared(params) end env = Rack::MockRequest.env_for('/', method: Rack::GET, params: { items: [{ key: :my_key, required_subitems: [value: 'my_value'] }] })
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
true
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/router_spec.rb
spec/grape/router_spec.rb
# frozen_string_literal: true describe Grape::Router do describe '.normalize_path' do subject { described_class.normalize_path(path) } context 'when no leading slash' do let(:path) { 'foo%20bar%20baz' } it { is_expected.to eq '/foo%20bar%20baz' } end context 'when path ends with slash' do let(:path) { '/foo%20bar%20baz/' } it { is_expected.to eq '/foo%20bar%20baz' } end context 'when path has recurring slashes' do let(:path) { '////foo%20bar%20baz' } it { is_expected.to eq '/foo%20bar%20baz' } end context 'when not greedy' do let(:path) { '/foo%20bar%20baz' } it { is_expected.to eq '/foo%20bar%20baz' } end context 'when encoded string in lowercase' do let(:path) { '/foo%aabar%aabaz' } it { is_expected.to eq '/foo%AAbar%AAbaz' } end context 'when nil' do let(:path) { nil } it { is_expected.to eq '/' } end context 'when empty string' do let(:path) { '' } it { is_expected.to eq '/' } end context 'when encoding is different' do subject { described_class.normalize_path(path).encoding } let(:path) { '/foo%AAbar%AAbaz'.b } it { is_expected.to eq(Encoding::BINARY) } end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/loading_spec.rb
spec/grape/loading_spec.rb
# frozen_string_literal: true describe Grape::API do subject do context = self Class.new(Grape::API) do format :json mount context.combined_api => '/' end end let(:jobs_api) do Class.new(Grape::API) do namespace :one do namespace :two do namespace :three do get :one do end get :two do end end end end end end let(:combined_api) do context = self Class.new(Grape::API) do version :v1, using: :accept_version_header, cascade: true mount context.jobs_api end end def app subject end it 'execute first request in reasonable time' do started = Time.now get '/mount1/nested/test_method' expect(Time.now - started).to be < 5 end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/parser_spec.rb
spec/grape/parser_spec.rb
# frozen_string_literal: true describe Grape::Parser do subject { described_class } describe '.parser_for' do let(:options) { {} } it 'returns parser correctly' do expect(subject.parser_for(:json)).to eq(Grape::Parser::Json) end context 'when parser is available' do let(:parsers) do { customized_json: Grape::Parser::Json } end it 'returns registered parser if available' do expect(subject.parser_for(:customized_json, parsers)).to eq(Grape::Parser::Json) end end context 'when parser does not exist' do it 'returns nil' do expect(subject.parser_for(:undefined)).to be_nil end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/util/media_type_spec.rb
spec/grape/util/media_type_spec.rb
# frozen_string_literal: true RSpec.describe Grape::Util::MediaType do shared_examples 'MediaType' do it { is_expected.to eq(described_class.new(type: type, subtype: subtype)) } end describe '.parse' do subject(:media_type) { described_class.parse(header) } context 'when header blank?' do let(:header) { nil } it { is_expected.to be_nil } end context 'when header is not a mime type' do let(:header) { 'abc' } it { is_expected.to be_nil } end context 'when header is a valid mime type' do let(:header) { [type, subtype].join('/') } let(:type) { 'text' } let(:subtype) { 'html' } it_behaves_like 'MediaType' context 'when header is a vendor mime type' do let(:type) { 'application' } let(:subtype) { 'vnd.test-v1+json' } it_behaves_like 'MediaType' end context 'when header is a vendor mime type without version' do let(:type) { 'application' } let(:subtype) { 'vnd.ms-word' } it_behaves_like 'MediaType' end end end describe '.match?' do subject { described_class.match?(media_type) } context 'when media_type is blank?' do let(:media_type) { nil } it { is_expected.to be_falsey } end context 'when header is not a mime type' do let(:media_type) { 'abc' } it { is_expected.to be_falsey } end context 'when header is a valid mime type but not vendor' do let(:media_type) { 'text/html' } it { is_expected.to be_falsey } end context 'when header is a vendor mime type' do let(:media_type) { 'application/vnd.test-v1+json' } it { is_expected.to be_truthy } end end describe '.best_quality' do subject(:media_type) { described_class.best_quality(header, available_media_types) } let(:available_media_types) { %w[application/json text/html] } context 'when header is blank?' do let(:header) { nil } let(:type) { 'application' } let(:subtype) { 'json' } it_behaves_like 'MediaType' end context 'when header is not blank' do let(:header) { [type, subtype].join('/') } let(:type) { 'text' } let(:subtype) { 'html' } it 'calls Rack::Utils.best_q_match' do allow(Rack::Utils).to receive(:best_q_match).and_call_original expect(media_type).to eq(described_class.new(type: type, subtype: subtype)) end end end describe '.==' do subject { described_class.new(type: type, subtype: subtype) } let(:type) { 'application' } let(:subtype) { 'vnd.test-v1+json' } let(:other_media_type_class) { Class.new(Struct.new(:type, :subtype, :vendor, :version, :format)) } let(:other_media_type_instance) { other_media_type_class.new(type, subtype, 'test', 'v1', 'json') } it { is_expected.not_to eq(other_media_type_class.new(type, subtype, 'test', 'v1', 'json')) } end describe '.hash' do subject { Set.new([described_class.new(type: type, subtype: subtype)]) } let(:type) { 'text' } let(:subtype) { 'html' } it { is_expected.to include(described_class.new(type: type, subtype: subtype)) } end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/util/inheritable_setting_spec.rb
spec/grape/util/inheritable_setting_spec.rb
# frozen_string_literal: true describe Grape::Util::InheritableSetting do before do described_class.reset_global! subject.inherit_from parent end let(:parent) do described_class.new.tap do |settings| settings.global[:global_thing] = :global_foo_bar settings.namespace[:namespace_thing] = :namespace_foo_bar settings.namespace_inheritable[:namespace_inheritable_thing] = :namespace_inheritable_foo_bar settings.namespace_stackable[:namespace_stackable_thing] = :namespace_stackable_foo_bar settings.namespace_reverse_stackable[:namespace_reverse_stackable_thing] = :namespace_reverse_stackable_foo_bar settings.route[:route_thing] = :route_foo_bar end end let(:other_parent) do described_class.new.tap do |settings| settings.namespace[:namespace_thing] = :namespace_foo_bar_other settings.namespace_inheritable[:namespace_inheritable_thing] = :namespace_inheritable_foo_bar_other settings.namespace_stackable[:namespace_stackable_thing] = :namespace_stackable_foo_bar_other settings.namespace_reverse_stackable[:namespace_reverse_stackable_thing] = :namespace_reverse_stackable_foo_bar_other settings.route[:route_thing] = :route_foo_bar_other end end describe '#global' do it 'sets a global value' do subject.global[:some_thing] = :foo_bar expect(subject.global[:some_thing]).to eq :foo_bar subject.global[:some_thing] = :foo_bar_next expect(subject.global[:some_thing]).to eq :foo_bar_next end it 'sets the global inherited values' do expect(subject.global[:global_thing]).to eq :global_foo_bar end it 'overrides global values' do subject.global[:global_thing] = :global_new_foo_bar expect(parent.global[:global_thing]).to eq :global_new_foo_bar end it 'handles different parents' do subject.global[:global_thing] = :global_new_foo_bar subject.inherit_from other_parent expect(parent.global[:global_thing]).to eq :global_new_foo_bar expect(other_parent.global[:global_thing]).to eq :global_new_foo_bar end end describe '#api_class' do it 'is specific to the class' do subject.api_class[:some_thing] = :foo_bar parent.api_class[:some_thing] = :some_thing expect(subject.api_class[:some_thing]).to eq :foo_bar expect(parent.api_class[:some_thing]).to eq :some_thing end end describe '#namespace' do it 'sets a value until the end of a namespace' do subject.namespace[:some_thing] = :foo_bar expect(subject.namespace[:some_thing]).to eq :foo_bar end it 'uses new values when a new namespace starts' do subject.namespace[:namespace_thing] = :new_namespace_foo_bar expect(subject.namespace[:namespace_thing]).to eq :new_namespace_foo_bar expect(parent.namespace[:namespace_thing]).to eq :namespace_foo_bar end end describe '#namespace_inheritable' do it 'works with inheritable values' do expect(subject.namespace_inheritable[:namespace_inheritable_thing]).to eq :namespace_inheritable_foo_bar end it 'handles different parents' do expect(subject.namespace_inheritable[:namespace_inheritable_thing]).to eq :namespace_inheritable_foo_bar subject.inherit_from other_parent expect(subject.namespace_inheritable[:namespace_inheritable_thing]).to eq :namespace_inheritable_foo_bar_other subject.inherit_from parent expect(subject.namespace_inheritable[:namespace_inheritable_thing]).to eq :namespace_inheritable_foo_bar subject.inherit_from other_parent subject.namespace_inheritable[:namespace_inheritable_thing] = :my_thing expect(subject.namespace_inheritable[:namespace_inheritable_thing]).to eq :my_thing subject.inherit_from parent expect(subject.namespace_inheritable[:namespace_inheritable_thing]).to eq :my_thing end end describe '#namespace_stackable' do it 'works with stackable values' do expect(subject.namespace_stackable[:namespace_stackable_thing]).to eq [:namespace_stackable_foo_bar] subject.inherit_from other_parent expect(subject.namespace_stackable[:namespace_stackable_thing]).to eq [:namespace_stackable_foo_bar_other] end end describe '#namespace_reverse_stackable' do it 'works with reverse stackable values' do expect(subject.namespace_reverse_stackable[:namespace_reverse_stackable_thing]).to eq [:namespace_reverse_stackable_foo_bar] subject.inherit_from other_parent expect(subject.namespace_reverse_stackable[:namespace_reverse_stackable_thing]).to eq [:namespace_reverse_stackable_foo_bar_other] end end describe '#route' do it 'sets a value until the next route' do subject.route[:some_thing] = :foo_bar expect(subject.route[:some_thing]).to eq :foo_bar subject.route_end expect(subject.route[:some_thing]).to be_nil end it 'works with route values' do expect(subject.route[:route_thing]).to eq :route_foo_bar end end describe '#api_class' do it 'is specific to the class' do subject.api_class[:some_thing] = :foo_bar expect(subject.api_class[:some_thing]).to eq :foo_bar end end describe '#inherit_from' do it 'notifies clones' do new_settings = subject.point_in_time_copy expect(new_settings).to receive(:inherit_from).with(other_parent) subject.inherit_from other_parent end end describe '#point_in_time_copy' do let!(:cloned_obj) { subject.point_in_time_copy } it 'resets point_in_time_copies' do expect(cloned_obj.point_in_time_copies).to be_empty end it 'decouples namespace values' do subject.namespace[:namespace_thing] = :namespace_foo_bar cloned_obj.namespace[:namespace_thing] = :new_namespace_foo_bar expect(subject.namespace[:namespace_thing]).to eq :namespace_foo_bar end it 'decouples namespace inheritable values' do expect(cloned_obj.namespace_inheritable[:namespace_inheritable_thing]).to eq :namespace_inheritable_foo_bar subject.namespace_inheritable[:namespace_inheritable_thing] = :my_thing expect(subject.namespace_inheritable[:namespace_inheritable_thing]).to eq :my_thing expect(cloned_obj.namespace_inheritable[:namespace_inheritable_thing]).to eq :namespace_inheritable_foo_bar cloned_obj.namespace_inheritable[:namespace_inheritable_thing] = :my_cloned_thing expect(cloned_obj.namespace_inheritable[:namespace_inheritable_thing]).to eq :my_cloned_thing expect(subject.namespace_inheritable[:namespace_inheritable_thing]).to eq :my_thing end it 'decouples namespace stackable values' do expect(cloned_obj.namespace_stackable[:namespace_stackable_thing]).to eq [:namespace_stackable_foo_bar] subject.namespace_stackable[:namespace_stackable_thing] = :other_thing expect(subject.namespace_stackable[:namespace_stackable_thing]).to eq %i[namespace_stackable_foo_bar other_thing] expect(cloned_obj.namespace_stackable[:namespace_stackable_thing]).to eq [:namespace_stackable_foo_bar] end it 'decouples namespace reverse stackable values' do expect(cloned_obj.namespace_reverse_stackable[:namespace_reverse_stackable_thing]).to eq [:namespace_reverse_stackable_foo_bar] subject.namespace_reverse_stackable[:namespace_reverse_stackable_thing] = :other_thing expect(subject.namespace_reverse_stackable[:namespace_reverse_stackable_thing]).to eq %i[other_thing namespace_reverse_stackable_foo_bar] expect(cloned_obj.namespace_reverse_stackable[:namespace_reverse_stackable_thing]).to eq [:namespace_reverse_stackable_foo_bar] end it 'decouples route values' do expect(cloned_obj.route[:route_thing]).to eq :route_foo_bar subject.route[:route_thing] = :new_route_foo_bar expect(cloned_obj.route[:route_thing]).to eq :route_foo_bar end it 'adds itself to original as clone' do expect(subject.point_in_time_copies).to include(cloned_obj) end end describe '#to_hash' do it 'return all settings as a hash' do subject.global[:global_thing] = :global_foo_bar subject.namespace[:namespace_thing] = :namespace_foo_bar subject.namespace_inheritable[:namespace_inheritable_thing] = :namespace_inheritable_foo_bar subject.namespace_stackable[:namespace_stackable_thing] = [:namespace_stackable_foo_bar] subject.namespace_reverse_stackable[:namespace_reverse_stackable_thing] = [:namespace_reverse_stackable_foo_bar] subject.route[:route_thing] = :route_foo_bar expect(subject.to_hash).to match( global: { global_thing: :global_foo_bar }, namespace: { namespace_thing: :namespace_foo_bar }, namespace_inheritable: { namespace_inheritable_thing: :namespace_inheritable_foo_bar }, namespace_stackable: { namespace_stackable_thing: [:namespace_stackable_foo_bar, [:namespace_stackable_foo_bar]] }, namespace_reverse_stackable: { namespace_reverse_stackable_thing: [[:namespace_reverse_stackable_foo_bar], :namespace_reverse_stackable_foo_bar] }, route: { route_thing: :route_foo_bar } ) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/util/stackable_values_spec.rb
spec/grape/util/stackable_values_spec.rb
# frozen_string_literal: true describe Grape::Util::StackableValues do subject { described_class.new(parent) } let(:parent) { described_class.new } describe '#keys' do it 'returns all keys' do subject[:some_thing] = :foo_bar subject[:some_thing_else] = :foo_bar expect(subject.keys).to eq %i[some_thing some_thing_else].sort end it 'returns merged keys with parent' do parent[:some_thing] = :foo parent[:some_thing_else] = :foo subject[:some_thing] = :foo_bar subject[:some_thing_more] = :foo_bar expect(subject.keys).to eq %i[some_thing some_thing_else some_thing_more].sort end end describe '#delete' do it 'deletes a key' do subject[:some_thing] = :new_foo_bar subject.delete :some_thing expect(subject[:some_thing]).to eq [] end it 'does not delete parent values' do parent[:some_thing] = :foo subject[:some_thing] = :new_foo_bar subject.delete :some_thing expect(subject[:some_thing]).to eq [:foo] end end describe '#[]' do it 'returns an array of values' do subject[:some_thing] = :foo expect(subject[:some_thing]).to eq [:foo] end it 'returns parent value when no value is set' do parent[:some_thing] = :foo expect(subject[:some_thing]).to eq [:foo] end it 'combines parent and actual values' do parent[:some_thing] = :foo subject[:some_thing] = :foo_bar expect(subject[:some_thing]).to eq %i[foo foo_bar] end it 'parent values are not changed' do parent[:some_thing] = :foo subject[:some_thing] = :foo_bar expect(parent[:some_thing]).to eq [:foo] end end describe '#[]=' do it 'sets a value' do subject[:some_thing] = :foo expect(subject[:some_thing]).to eq [:foo] end it 'pushes further values' do subject[:some_thing] = :foo subject[:some_thing] = :bar expect(subject[:some_thing]).to eq %i[foo bar] end it 'can handle array values' do subject[:some_thing] = :foo subject[:some_thing] = %i[bar more] expect(subject[:some_thing]).to eq [:foo, %i[bar more]] parent[:some_thing_else] = %i[foo bar] subject[:some_thing_else] = %i[some bar foo] expect(subject[:some_thing_else]).to eq [%i[foo bar], %i[some bar foo]] end end describe '#to_hash' do it 'returns a Hash representation' do parent[:some_thing] = :foo subject[:some_thing] = %i[bar more] subject[:some_thing_more] = :foo_bar expect(subject.to_hash).to eq(some_thing: [:foo, %i[bar more]], some_thing_more: [:foo_bar]) end end describe '#clone' do let(:obj_cloned) { subject.clone } it 'copies all values' do parent = described_class.new child = described_class.new parent grandchild = described_class.new child parent[:some_thing] = :foo child[:some_thing] = %i[bar more] grandchild[:some_thing] = :grand_foo_bar grandchild[:some_thing_more] = :foo_bar expect(grandchild.clone.to_hash).to eq(some_thing: [:foo, %i[bar more], :grand_foo_bar], some_thing_more: [:foo_bar]) end context 'complex (i.e. not primitive) data types (ex. middleware, please see bug #930)' do let(:middleware) { double } before { subject[:middleware] = middleware } it 'copies values; does not duplicate them' do expect(obj_cloned[:middleware]).to eq [middleware] end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/util/reverse_stackable_values_spec.rb
spec/grape/util/reverse_stackable_values_spec.rb
# frozen_string_literal: true describe Grape::Util::ReverseStackableValues do subject { described_class.new(parent) } let(:parent) { described_class.new } describe '#keys' do it 'returns all keys' do subject[:some_thing] = :foo_bar subject[:some_thing_else] = :foo_bar expect(subject.keys).to eq %i[some_thing some_thing_else].sort end it 'returns merged keys with parent' do parent[:some_thing] = :foo parent[:some_thing_else] = :foo subject[:some_thing] = :foo_bar subject[:some_thing_more] = :foo_bar expect(subject.keys).to eq %i[some_thing some_thing_else some_thing_more].sort end end describe '#delete' do it 'deletes a key' do subject[:some_thing] = :new_foo_bar subject.delete :some_thing expect(subject[:some_thing]).to eq [] end it 'does not delete parent values' do parent[:some_thing] = :foo subject[:some_thing] = :new_foo_bar subject.delete :some_thing expect(subject[:some_thing]).to eq [:foo] end end describe '#[]' do it 'returns an array of values' do subject[:some_thing] = :foo expect(subject[:some_thing]).to eq [:foo] end it 'returns parent value when no value is set' do parent[:some_thing] = :foo expect(subject[:some_thing]).to eq [:foo] end it 'combines parent and actual values (actual first)' do parent[:some_thing] = :foo subject[:some_thing] = :foo_bar expect(subject[:some_thing]).to eq %i[foo_bar foo] end it 'parent values are not changed' do parent[:some_thing] = :foo subject[:some_thing] = :foo_bar expect(parent[:some_thing]).to eq [:foo] end end describe '#[]=' do it 'sets a value' do subject[:some_thing] = :foo expect(subject[:some_thing]).to eq [:foo] end it 'pushes further values' do subject[:some_thing] = :foo subject[:some_thing] = :bar expect(subject[:some_thing]).to eq %i[foo bar] end it 'can handle array values' do subject[:some_thing] = :foo subject[:some_thing] = %i[bar more] expect(subject[:some_thing]).to eq [:foo, %i[bar more]] parent[:some_thing_else] = %i[foo bar] subject[:some_thing_else] = %i[some bar foo] expect(subject[:some_thing_else]).to eq [%i[some bar foo], %i[foo bar]] end end describe '#to_hash' do it 'returns a Hash representation' do parent[:some_thing] = :foo subject[:some_thing] = %i[bar more] subject[:some_thing_more] = :foo_bar expect(subject.to_hash).to eq( some_thing: [%i[bar more], :foo], some_thing_more: [:foo_bar] ) end end describe '#clone' do let(:obj_cloned) { subject.clone } it 'copies all values' do parent = described_class.new child = described_class.new parent grandchild = described_class.new child parent[:some_thing] = :foo child[:some_thing] = %i[bar more] grandchild[:some_thing] = :grand_foo_bar grandchild[:some_thing_more] = :foo_bar expect(grandchild.clone.to_hash).to eq( some_thing: [:grand_foo_bar, %i[bar more], :foo], some_thing_more: [:foo_bar] ) end context 'complex (i.e. not primitive) data types (ex. middleware, please see bug #930)' do let(:middleware) { double } before { subject[:middleware] = middleware } it 'copies values; does not duplicate them' do expect(obj_cloned[:middleware]).to eq [middleware] end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/util/inheritable_values_spec.rb
spec/grape/util/inheritable_values_spec.rb
# frozen_string_literal: true describe Grape::Util::InheritableValues do subject { described_class.new(parent) } let(:parent) { described_class.new } describe '#delete' do it 'deletes a key' do subject[:some_thing] = :new_foo_bar subject.delete :some_thing expect(subject[:some_thing]).to be_nil end it 'does not delete parent values' do parent[:some_thing] = :foo subject[:some_thing] = :new_foo_bar subject.delete :some_thing expect(subject[:some_thing]).to eq :foo end end describe '#[]' do it 'returns a value' do subject[:some_thing] = :foo expect(subject[:some_thing]).to eq :foo end it 'returns parent value when no value is set' do parent[:some_thing] = :foo expect(subject[:some_thing]).to eq :foo end it 'overwrites parent value with the current one' do parent[:some_thing] = :foo subject[:some_thing] = :foo_bar expect(subject[:some_thing]).to eq :foo_bar end it 'parent values are not changed' do parent[:some_thing] = :foo subject[:some_thing] = :foo_bar expect(parent[:some_thing]).to eq :foo end end describe '#[]=' do it 'sets a value' do subject[:some_thing] = :foo expect(subject[:some_thing]).to eq :foo end end describe '#to_hash' do it 'returns a Hash representation' do parent[:some_thing] = :foo subject[:some_thing_more] = :foo_bar expect(subject.to_hash).to eq(some_thing: :foo, some_thing_more: :foo_bar) end end describe '#clone' do let(:obj_cloned) { subject.clone } context 'complex (i.e. not primitive) data types (ex. entity classes, please see bug #891)' do let(:description) { { entity: double } } before { subject[:description] = description } it 'copies values; does not duplicate them' do expect(obj_cloned[:description]).to eq description end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/util/registry_spec.rb
spec/grape/util/registry_spec.rb
# frozen_string_literal: true describe Grape::Util::Registry do # Create a test class that includes the Registry module subject { test_registry_class.new } let(:test_registry_class) do Class.new do include Grape::Util::Registry # Public methods to expose private functionality for testing def registry_empty? registry.empty? end def registry_get(key) registry[key] end end end describe '#register' do let(:test_class) do Class.new do def self.name 'TestModule::TestClass' end end end let(:simple_class) do Class.new do def self.name 'SimpleClass' end end end let(:camel_case_class) do Class.new do def self.name 'CamelCaseClass' end end end let(:anonymous_class) { Class.new } let(:nil_name_class) do Class.new do def self.name nil end end end let(:empty_name_class) do Class.new do def self.name '' end end end context 'with valid class names' do it 'registers a class with demodulized and underscored name' do subject.register(test_class) expect(subject.registry_get('test_class')).to eq(test_class) end it 'registers a simple class name correctly' do subject.register(simple_class) expect(subject.registry_get('simple_class')).to eq(simple_class) end it 'handles camel case class names' do subject.register(camel_case_class) expect(subject.registry_get('camel_case_class')).to eq(camel_case_class) end it 'uses indifferent access for registry keys' do subject.register(test_class) expect(subject.registry_get(:test_class)).to eq(test_class) expect(subject.registry_get('test_class')).to eq(test_class) end end context 'with invalid class names' do it 'does not register anonymous classes' do subject.register(anonymous_class) expect(subject.registry_empty?).to be true end it 'does not register classes with nil names' do subject.register(nil_name_class) expect(subject.registry_empty?).to be true end it 'does not register classes with empty names' do subject.register(empty_name_class) expect(subject.registry_empty?).to be true end end context 'with duplicate registrations' do it 'warns when registering a duplicate short name' do expect do subject.register(test_class) subject.register(test_class) end.to output(/test_class is already registered with class.*It will be overridden/).to_stderr end it 'warns with correct short name for different class types' do expect do subject.register(simple_class) subject.register(simple_class) end.to output(/simple_class is already registered with class.*It will be overridden/).to_stderr end it 'warns with correct short name for camel case classes' do expect do subject.register(camel_case_class) subject.register(camel_case_class) end.to output(/camel_case_class is already registered with class.*It will be overridden/).to_stderr end it 'warns for each duplicate registration' do expect do subject.register(test_class) subject.register(test_class) subject.register(test_class) # Third registration should warn again end.to output(/test_class is already registered with class.*It will be overridden/).to_stderr end it 'warns with exact message format' do expected_message = "test_class is already registered with class #{test_class}. It will be overridden globally with the following: #{test_class.name}" expect do subject.register(test_class) subject.register(test_class) end.to output(/#{Regexp.escape(expected_message)}/).to_stderr end it 'overwrites existing registration when duplicate short name is registered' do subject.register(test_class) subject.register(test_class) expect(subject.registry_get('test_class')).to eq(test_class) end end end describe 'edge cases' do it 'handles classes with special characters in names' do special_class = Class.new do def self.name 'Special::Class::With::Many::Modules' end end subject.register(special_class) expect(subject.registry_get('modules')).to eq(special_class) end it 'handles classes with numbers in names' do numbered_class = Class.new do def self.name 'Class123WithNumbers' end end subject.register(numbered_class) expect(subject.registry_get('class123_with_numbers')).to eq(numbered_class) end it 'handles classes with acronyms' do acronym_class = Class.new do def self.name 'API::HTTPClient' end end subject.register(acronym_class) expect(subject.registry_get('http_client')).to eq(acronym_class) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/params_builder/hash_spec.rb
spec/grape/params_builder/hash_spec.rb
# frozen_string_literal: true describe Grape::ParamsBuilder::Hash do subject { app } let(:app) do Class.new(Grape::API) end describe 'in an endpoint' do describe '#params' do before do subject.params do build_with :hash end subject.get do params.class end end it 'is of type Hash' do get '/' expect(last_response.status).to eq(200) expect(last_response.body).to eq('Hash') end end end describe 'in an api' do before do subject.build_with :hash end describe '#params' do before do subject.get do params.class end end it 'is Hash' do get '/' expect(last_response.status).to eq(200) expect(last_response.body).to eq('Hash') end end it 'symbolizes params keys' do subject.params do optional :a, type: Hash do optional :b, type: Hash do optional :c, type: String end optional :d, type: Array end end subject.get '/foo' do [params[:a][:b][:c], params[:a][:d]] end get '/foo', 'a' => { b: { c: 'bar' }, 'd' => ['foo'] } expect(last_response.status).to eq(200) expect(last_response.body).to eq('["bar", ["foo"]]') end it 'symbolizes the params' do subject.params do build_with :hash requires :a, type: String end subject.get '/foo' do [params[:a], params['a']] end get '/foo', a: 'bar' expect(last_response.status).to eq(200) expect(last_response.body).to eq('["bar", nil]') end it 'does not overwrite route_param with a regular param if they have same name' do subject.namespace :route_param do route_param :foo do get { params.to_json } end end get '/route_param/bar', foo: 'baz' expect(last_response.status).to eq(200) expect(last_response.body).to eq('{"foo":"bar"}') end it 'does not overwrite route_param with a defined regular param if they have same name' do subject.namespace :route_param do params do requires :foo, type: String end route_param :foo do get do params[:foo] end end end get '/route_param/bar', foo: 'baz' expect(last_response.status).to eq(200) expect(last_response.body).to eq('bar') end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/params_builder/hash_with_indifferent_access_spec.rb
spec/grape/params_builder/hash_with_indifferent_access_spec.rb
# frozen_string_literal: true describe Grape::ParamsBuilder::HashWithIndifferentAccess do subject { app } let(:app) do Class.new(Grape::API) end describe 'in an endpoint' do describe '#params' do before do subject.params do build_with :hash_with_indifferent_access end subject.get do params.class end end it 'is of type Hash' do get '/' expect(last_response.status).to eq(200) expect(last_response.body).to eq('ActiveSupport::HashWithIndifferentAccess') end end end describe 'in an api' do before do subject.build_with :hash_with_indifferent_access end describe '#params' do before do subject.get do params.class end end it 'is a Hash' do get '/' expect(last_response.status).to eq(200) expect(last_response.body).to eq('ActiveSupport::HashWithIndifferentAccess') end it 'parses sub hash params' do subject.params do build_with :hash_with_indifferent_access optional :a, type: Hash do optional :b, type: Hash do optional :c, type: String end optional :d, type: Array end end subject.get '/foo' do [params[:a]['b'][:c], params['a'][:d]] end get '/foo', a: { b: { c: 'bar' }, d: ['foo'] } expect(last_response.status).to eq(200) expect(last_response.body).to eq('["bar", ["foo"]]') end it 'params are indifferent to symbol or string keys' do subject.params do build_with :hash_with_indifferent_access optional :a, type: Hash do optional :b, type: Hash do optional :c, type: String end optional :d, type: Array end end subject.get '/foo' do [params[:a]['b'][:c], params['a'][:d]] end get '/foo', 'a' => { b: { c: 'bar' }, 'd' => ['foo'] } expect(last_response.status).to eq(200) expect(last_response.body).to eq('["bar", ["foo"]]') end it 'responds to string keys' do subject.params do build_with :hash_with_indifferent_access requires :a, type: String end subject.get '/foo' do [params[:a], params['a']] end get '/foo', a: 'bar' expect(last_response.status).to eq(200) expect(last_response.body).to eq('["bar", "bar"]') end end it 'does not overwrite route_param with a regular param if they have same name' do subject.namespace :route_param do route_param :foo do get { params.to_json } end end get '/route_param/bar', foo: 'baz' expect(last_response.status).to eq(200) expect(last_response.body).to eq('{"foo":"bar"}') end it 'does not overwrite route_param with a defined regular param if they have same name' do subject.namespace :route_param do params do requires :foo, type: String end route_param :foo do get do [params[:foo], params['foo']] end end end get '/route_param/bar', foo: 'baz' expect(last_response.status).to eq(200) expect(last_response.body).to eq('["bar", "bar"]') end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/integration/rack_spec.rb
spec/grape/integration/rack_spec.rb
# frozen_string_literal: true describe Rack do describe 'from a Tempfile' do subject { last_response.body } let(:app) do Class.new(Grape::API) do format :json params do requires :file, type: File end post do params[:file].then do |file| { filename: file[:filename], type: file[:type], content: file[:tempfile].read } end end end end let(:response_body) do { filename: File.basename(tempfile.path), type: 'text/plain', content: 'rubbish' }.to_json end let(:tempfile) do Tempfile.new.tap do |t| t.write('rubbish') t.rewind end end before do post '/', file: Rack::Test::UploadedFile.new(tempfile.path, 'text/plain') end it 'correctly populates params from a Tempfile' do expect(subject).to eq(response_body) ensure tempfile.close! end end context 'when the app is mounted' do let(:ping_mount) do Class.new(Grape::API) do get 'ping' end end let(:app) do app_to_mount = ping_mount Class.new(Grape::API) do namespace 'namespace' do mount app_to_mount end end end it 'finds the app on the namespace' do get '/namespace/ping' expect(last_response).to be_successful end end # https://github.com/ruby-grape/grape/issues/2576 describe 'when an api is mounted' do let(:api) do Class.new(Grape::API) do format :json version 'v1', using: :path resource :system do get :ping do { message: 'pong' } end end end end let(:parent_api) do api_to_mount = api Class.new(Grape::API) do format :json namespace '/api' do mount api_to_mount end end end it 'is not polluted with the parent namespace' do env = Rack::MockRequest.env_for('/v1/api/system/ping', method: 'GET') response = Rack::MockResponse[*parent_api.call(env)] expect(response.status).to eq(200) parsed_body = JSON.parse(response.body) expect(parsed_body['message']).to eq('pong') end it 'can call the api' do env = Rack::MockRequest.env_for('/v1/system/ping', method: 'GET') response = Rack::MockResponse[*api.call(env)] expect(response.status).to eq(200) parsed_body = JSON.parse(response.body) expect(parsed_body['message']).to eq('pong') end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/integration/global_namespace_function_spec.rb
spec/grape/integration/global_namespace_function_spec.rb
# frozen_string_literal: true # see https://github.com/ruby-grape/grape/issues/1348 def namespace raise end describe Grape::API do subject do Class.new(Grape::API) do format :json get do { ok: true } end end end def app subject end context 'with a global namespace function' do it 'works' do get '/' expect(last_response.status).to eq 200 end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/integration/rack_sendfile_spec.rb
spec/grape/integration/rack_sendfile_spec.rb
# frozen_string_literal: true describe Rack::Sendfile do subject do content_object = file_object app = Class.new(Grape::API) do use Rack::Sendfile, 'X-Accel-Redirect' format :json get do if content_object.is_a?(String) sendfile content_object else stream content_object end end end options = { method: Rack::GET, 'HTTP_X_ACCEL_MAPPING' => '/accel/mapping/=/replaced/' } env = Rack::MockRequest.env_for('/', options) app.call(env) end context 'when calling sendfile' do let(:file_object) do '/accel/mapping/some/path' end it 'contains Sendfile headers' do headers = subject[1] expect(headers).to include('X-Accel-Redirect') end end context 'when streaming non file content' do let(:file_object) do double(:file_object, each: nil) end it 'not contains Sendfile headers' do headers = subject[1] expect(headers).not_to include('X-Accel-Redirect') end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/presenters/presenter_spec.rb
spec/grape/presenters/presenter_spec.rb
# frozen_string_literal: true describe Grape::Presenters::Presenter do subject { dummy_class.new } let(:dummy_class) do Class.new do include Grape::DSL::InsideRoute attr_reader :env, :request, :new_settings def initialize @env = {} @header = {} @new_settings = { namespace_inheritable: {}, namespace_stackable: {} } end end end describe 'represent' do let(:object_mock) do Object.new end it 'represent object' do expect(described_class.represent(object_mock)).to eq object_mock end end describe 'present' do let(:hash_mock) do { key: :value } end describe 'instance' do before do subject.present hash_mock, with: described_class end it 'presents dummy hash' do expect(subject.body).to eq hash_mock end end describe 'multiple presenter' do let(:hash_mock1) do { key1: :value1 } end let(:hash_mock2) do { key2: :value2 } end describe 'instance' do before do subject.present hash_mock1, with: described_class subject.present hash_mock2, with: described_class end it 'presents both dummy presenter' do expect(subject.body[:key1]).to eq hash_mock1[:key1] expect(subject.body[:key2]).to eq hash_mock2[:key2] end end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/exceptions/missing_group_type_spec.rb
spec/grape/exceptions/missing_group_type_spec.rb
# frozen_string_literal: true RSpec.describe Grape::Exceptions::MissingGroupType do describe '#message' do subject { described_class.new.message } it { is_expected.to include 'group type is required' } end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/exceptions/invalid_formatter_spec.rb
spec/grape/exceptions/invalid_formatter_spec.rb
# frozen_string_literal: true describe Grape::Exceptions::InvalidFormatter do describe '#message' do let(:error) do described_class.new(String, 'xml') end it 'contains the problem in the message' do expect(error.message).to include( 'cannot convert String to xml' ) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/exceptions/invalid_accept_header_spec.rb
spec/grape/exceptions/invalid_accept_header_spec.rb
# frozen_string_literal: true describe Grape::Exceptions::InvalidAcceptHeader do shared_examples_for 'a valid request' do it 'does return with status 200' do expect(last_response.status).to eq 200 end it 'does return the expected result' do expect(last_response.body).to eq('beer received') end end shared_examples_for 'a cascaded request' do it 'does not find a matching route' do expect(last_response.status).to eq 404 end end shared_examples_for 'a not-cascaded request' do it 'does not include the X-Cascade=pass header' do expect(last_response.headers).not_to have_key('X-Cascade') end it 'does not accept the request' do expect(last_response.status).to eq 406 end end shared_examples_for 'a rescued request' do it 'does not include the X-Cascade=pass header' do expect(last_response.headers['X-Cascade']).to be_nil end it 'does show rescue handler processing' do expect(last_response.status).to eq 400 expect(last_response.body).to eq('message was processed') end end context 'API with cascade=false and rescue_from :all handler' do subject { Class.new(Grape::API) } before do subject.version 'v99', using: :header, vendor: 'vendorname', format: :json, cascade: false subject.rescue_from :all do |e| error! 'message was processed', 400, e[:headers] end subject.get '/beer' do 'beer received' end end def app subject end context 'that received a request with correct vendor and version' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.vendorname-v99' } it_behaves_like 'a valid request' end context 'that receives' do context 'an invalid vendor in the request' do before do get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.invalidvendor-v99', 'CONTENT_TYPE' => 'application/json' end it_behaves_like 'a rescued request' end end end context 'API with cascade=false and without a rescue handler' do subject { Class.new(Grape::API) } before do subject.version 'v99', using: :header, vendor: 'vendorname', format: :json, cascade: false subject.get '/beer' do 'beer received' end end def app subject end context 'that received a request with correct vendor and version' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.vendorname-v99' } it_behaves_like 'a valid request' end context 'that receives' do context 'an invalid version in the request' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.vendorname-v77' } it_behaves_like 'a not-cascaded request' end context 'an invalid vendor in the request' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.invalidvendor-v99' } it_behaves_like 'a not-cascaded request' end end end context 'API with cascade=false and with rescue_from :all handler and http_codes' do subject { Class.new(Grape::API) } before do subject.version 'v99', using: :header, vendor: 'vendorname', format: :json, cascade: false subject.rescue_from :all do |e| error! 'message was processed', 400, e[:headers] end subject.desc 'Get beer' do failure [[400, 'Bad Request'], [401, 'Unauthorized'], [403, 'Forbidden'], [404, 'Resource not found'], [406, 'API vendor or version not found'], [500, 'Internal processing error']] end subject.get '/beer' do 'beer received' end end def app subject end context 'that received a request with correct vendor and version' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.vendorname-v99' } it_behaves_like 'a valid request' end context 'that receives' do context 'an invalid vendor in the request' do before do get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.invalidvendor-v99', 'CONTENT_TYPE' => 'application/json' end it_behaves_like 'a rescued request' end end end context 'API with cascade=false, http_codes but without a rescue handler' do subject { Class.new(Grape::API) } before do subject.version 'v99', using: :header, vendor: 'vendorname', format: :json, cascade: false subject.desc 'Get beer' do failure [[400, 'Bad Request'], [401, 'Unauthorized'], [403, 'Forbidden'], [404, 'Resource not found'], [406, 'API vendor or version not found'], [500, 'Internal processing error']] end subject.get '/beer' do 'beer received' end end def app subject end context 'that received a request with correct vendor and version' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.vendorname-v99' } it_behaves_like 'a valid request' end context 'that receives' do context 'an invalid version in the request' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.vendorname-v77' } it_behaves_like 'a not-cascaded request' end context 'an invalid vendor in the request' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.invalidvendor-v99' } it_behaves_like 'a not-cascaded request' end end end context 'API with cascade=true and rescue_from :all handler' do subject { Class.new(Grape::API) } before do subject.version 'v99', using: :header, vendor: 'vendorname', format: :json, cascade: true subject.rescue_from :all do |e| error! 'message was processed', 400, e[:headers] end subject.get '/beer' do 'beer received' end end def app subject end context 'that received a request with correct vendor and version' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.vendorname-v99' } it_behaves_like 'a valid request' end context 'that receives' do context 'an invalid version in the request' do before do get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.vendorname-v77', 'CONTENT_TYPE' => 'application/json' end it_behaves_like 'a cascaded request' end context 'an invalid vendor in the request' do before do get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.invalidvendor-v99', 'CONTENT_TYPE' => 'application/json' end it_behaves_like 'a cascaded request' end end end context 'API with cascade=true and without a rescue handler' do subject { Class.new(Grape::API) } before do subject.version 'v99', using: :header, vendor: 'vendorname', format: :json, cascade: true subject.get '/beer' do 'beer received' end end def app subject end context 'that received a request with correct vendor and version' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.vendorname-v99' } it_behaves_like 'a valid request' end context 'that receives' do context 'an invalid version in the request' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.vendorname-v77' } it_behaves_like 'a cascaded request' end context 'an invalid vendor in the request' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.invalidvendor-v99' } it_behaves_like 'a cascaded request' end end end context 'API with cascade=true and with rescue_from :all handler and http_codes' do subject { Class.new(Grape::API) } before do subject.version 'v99', using: :header, vendor: 'vendorname', format: :json, cascade: true subject.rescue_from :all do |e| error! 'message was processed', 400, e[:headers] end subject.desc 'Get beer' do failure [[400, 'Bad Request'], [401, 'Unauthorized'], [403, 'Forbidden'], [404, 'Resource not found'], [406, 'API vendor or version not found'], [500, 'Internal processing error']] end subject.get '/beer' do 'beer received' end end def app subject end context 'that received a request with correct vendor and version' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.vendorname-v99' } it_behaves_like 'a valid request' end context 'that receives' do context 'an invalid version in the request' do before do get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.vendorname-v77', 'CONTENT_TYPE' => 'application/json' end it_behaves_like 'a cascaded request' end context 'an invalid vendor in the request' do before do get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.invalidvendor-v99', 'CONTENT_TYPE' => 'application/json' end it_behaves_like 'a cascaded request' end end end context 'API with cascade=true, http_codes but without a rescue handler' do subject { Class.new(Grape::API) } before do subject.version 'v99', using: :header, vendor: 'vendorname', format: :json, cascade: true subject.desc 'Get beer' do failure [[400, 'Bad Request'], [401, 'Unauthorized'], [403, 'Forbidden'], [404, 'Resource not found'], [406, 'API vendor or version not found'], [500, 'Internal processing error']] end subject.get '/beer' do 'beer received' end end def app subject end context 'that received a request with correct vendor and version' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.vendorname-v99' } it_behaves_like 'a valid request' end context 'that receives' do context 'an invalid version in the request' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.vendorname-v77' } it_behaves_like 'a cascaded request' end context 'an invalid vendor in the request' do before { get '/beer', {}, 'HTTP_ACCEPT' => 'application/vnd.invalidvendor-v99' } it_behaves_like 'a cascaded request' end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/exceptions/unsupported_group_type_spec.rb
spec/grape/exceptions/unsupported_group_type_spec.rb
# frozen_string_literal: true RSpec.describe Grape::Exceptions::UnsupportedGroupType do subject { described_class.new } describe '#message' do subject { described_class.new.message } it { is_expected.to include 'group type must be Array, Hash, JSON or Array[JSON]' } end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/exceptions/missing_mime_type_spec.rb
spec/grape/exceptions/missing_mime_type_spec.rb
# frozen_string_literal: true describe Grape::Exceptions::MissingMimeType do describe '#message' do let(:error) do described_class.new('new_json') end it 'contains the problem in the message' do expect(error.message).to include 'missing mime type for new_json' end it 'contains the resolution in the message' do expect(error.message).to include "or add your own with content_type :new_json, 'application/new_json' " end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/exceptions/invalid_versioner_option_spec.rb
spec/grape/exceptions/invalid_versioner_option_spec.rb
# frozen_string_literal: true describe Grape::Exceptions::InvalidVersionerOption do describe '#message' do let(:error) do described_class.new('headers') end it 'contains the problem in the message' do expect(error.message).to include( 'unknown :using for versioner: headers' ) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/exceptions/unknown_validator_spec.rb
spec/grape/exceptions/unknown_validator_spec.rb
# frozen_string_literal: true describe Grape::Exceptions::UnknownValidator do describe '#message' do let(:error) do described_class.new('gt_10') end it 'contains the problem in the message' do expect(error.message).to include( 'unknown validator: gt_10' ) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/exceptions/body_parse_errors_spec.rb
spec/grape/exceptions/body_parse_errors_spec.rb
# frozen_string_literal: true describe Grape::Exceptions::ValidationErrors do context 'api with rescue_from :all handler' do subject { Class.new(Grape::API) } before do subject.rescue_from :all do |_e| error! 'message was processed', 400 end subject.params do requires :beer end subject.post '/beer' do 'beer received' end end def app subject end context 'with content_type json' do it 'can recover from failed body parsing' do post '/beer', 'test', 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq 400 expect(last_response.body).to eq('message was processed') end end context 'with content_type xml' do it 'can recover from failed body parsing' do post '/beer', 'test', 'CONTENT_TYPE' => 'application/xml' expect(last_response.status).to eq 400 expect(last_response.body).to eq('message was processed') end end context 'with content_type text' do it 'can recover from failed body parsing' do post '/beer', 'test', 'CONTENT_TYPE' => 'text/plain' expect(last_response.status).to eq 400 expect(last_response.body).to eq('message was processed') end end context 'with no specific content_type' do it 'can recover from failed body parsing' do post '/beer', 'test', {} expect(last_response.status).to eq 400 expect(last_response.body).to eq('message was processed') end end end context 'api with rescue_from :grape_exceptions handler' do subject { Class.new(Grape::API) } before do subject.rescue_from :all do |_e| error! 'message was processed', 400 end subject.rescue_from :grape_exceptions subject.params do requires :beer end subject.post '/beer' do 'beer received' end end def app subject end context 'with content_type json' do it 'returns body parsing error message' do post '/beer', 'test', 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq 400 expect(last_response.body).to include 'message body does not match declared format' end end context 'with content_type xml' do it 'returns body parsing error message' do post '/beer', 'test', 'CONTENT_TYPE' => 'application/xml' expect(last_response.status).to eq 400 expect(last_response.body).to include 'message body does not match declared format' end end end context 'api with rescue_from :grape_exceptions handler with block' do subject { Class.new(Grape::API) } before do subject.rescue_from :grape_exceptions do |e| error! "Custom Error Contents, Original Message: #{e.message}", 400 end subject.params do requires :beer end subject.post '/beer' do 'beer received' end end def app subject end context 'with content_type json' do it 'returns body parsing error message' do post '/beer', 'test', 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq 400 expect(last_response.body).to include 'message body does not match declared format' expect(last_response.body).to include 'Custom Error Contents, Original Message' end end context 'with content_type xml' do it 'returns body parsing error message' do post '/beer', 'test', 'CONTENT_TYPE' => 'application/xml' expect(last_response.status).to eq 400 expect(last_response.body).to include 'message body does not match declared format' expect(last_response.body).to include 'Custom Error Contents, Original Message' end end end context 'api without a rescue handler' do subject { Class.new(Grape::API) } before do subject.params do requires :beer end subject.post '/beer' do 'beer received' end end def app subject end context 'and with content_type json' do it 'can recover from failed body parsing' do post '/beer', 'test', 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq 400 expect(last_response.body).to include('message body does not match declared format') expect(last_response.body).to include('application/json') end end context 'with content_type xml' do it 'can recover from failed body parsing' do post '/beer', 'test', 'CONTENT_TYPE' => 'application/xml' expect(last_response.status).to eq 400 expect(last_response.body).to include('message body does not match declared format') expect(last_response.body).to include('application/xml') end end context 'with content_type text' do it 'can recover from failed body parsing' do post '/beer', 'test', 'CONTENT_TYPE' => 'text/plain' expect(last_response.status).to eq 400 expect(last_response.body).to eq('beer is missing') end end context 'and with no specific content_type' do it 'can recover from failed body parsing' do post '/beer', 'test', {} expect(last_response.status).to eq 400 # plain response with text/html expect(last_response.body).to eq('beer is missing') end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/exceptions/base_spec.rb
spec/grape/exceptions/base_spec.rb
# frozen_string_literal: true describe Grape::Exceptions::Base do describe '#to_s' do subject { described_class.new(message: message).to_s } let(:message) { 'a_message' } it { is_expected.to eq(message) } end describe '#message' do subject { described_class.new(message: message).message } let(:message) { 'a_message' } it { is_expected.to eq(message) } end describe '#compose_message' do subject { described_class.new.__send__(:compose_message, key, **attributes) } let(:key) { :invalid_formatter } let(:attributes) { { klass: String, to_format: 'xml' } } after do I18n.enforce_available_locales = true I18n.available_locales = %i[en] I18n.locale = :en I18n.default_locale = :en I18n.reload! end context 'when I18n enforces available locales' do before { I18n.enforce_available_locales = true } context 'when the fallback locale is available' do before do I18n.available_locales = %i[de en] I18n.default_locale = :de end it 'returns the translated message' do expect(subject).to eq('cannot convert String to xml') end end context 'when the fallback locale is not available' do before do I18n.available_locales = %i[de jp] I18n.locale = :de I18n.default_locale = :de end it 'returns the translation string' do expect(subject).to eq("grape.errors.messages.#{key}") end end end context 'when I18n does not enforce available locales' do before { I18n.enforce_available_locales = false } context 'when the fallback locale is available' do before { I18n.available_locales = %i[de en] } it 'returns the translated message' do expect(subject).to eq('cannot convert String to xml') end end context 'when the fallback locale is not available' do before { I18n.available_locales = %i[de jp] } it 'returns the translated message' do expect(subject).to eq('cannot convert String to xml') end end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/exceptions/validation_errors_spec.rb
spec/grape/exceptions/validation_errors_spec.rb
# frozen_string_literal: true describe Grape::Exceptions::ValidationErrors do let(:validation_message) { 'FooBar is invalid' } let(:validation_error) { instance_double Grape::Exceptions::Validation, params: [validation_message], message: '' } context 'initialize' do subject do described_class.new(errors: [validation_error], headers: headers) end let(:headers) do { 'A-Header-Key' => 'A-Header-Value' } end it 'assigns headers through base class' do expect(subject.headers).to eq(headers) end end context 'message' do context 'is not repeated' do subject(:message) { error.message.split(',').map(&:strip) } let(:error) do described_class.new(errors: [validation_error, validation_error]) end it { expect(message).to include validation_message } it { expect(message.size).to eq 1 } end end describe '#full_messages' do context 'with errors' do subject { described_class.new(errors: [validation_error_1, validation_error_2]).full_messages } let(:validation_error_1) { Grape::Exceptions::Validation.new(params: ['id'], message: :presence) } let(:validation_error_2) { Grape::Exceptions::Validation.new(params: ['name'], message: :presence) } it 'returns an array with each errors full message' do expect(subject).to contain_exactly('id is missing', 'name is missing') end end context 'when attributes is an array of symbols' do subject { described_class.new(errors: [validation_error]).full_messages } let(:validation_error) { Grape::Exceptions::Validation.new(params: [:admin_field], message: 'Can not set admin-only field') } it 'returns an array with an error full message' do expect(subject.first).to eq('admin_field Can not set admin-only field') end end end context 'api' do subject { Class.new(Grape::API) } def app subject end it 'can return structured json with separate fields' do subject.format :json subject.rescue_from described_class do |e| error!(e, 400) end subject.params do optional :beer optional :wine optional :juice exactly_one_of :beer, :wine, :juice end subject.get '/exactly_one_of' do 'exactly_one_of works!' end get '/exactly_one_of', beer: 'string', wine: 'anotherstring' expect(last_response).to be_bad_request expect(JSON.parse(last_response.body)).to eq( [ 'params' => %w[beer wine], 'messages' => ['are mutually exclusive'] ] ) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/exceptions/invalid_response_spec.rb
spec/grape/exceptions/invalid_response_spec.rb
# frozen_string_literal: true describe Grape::Exceptions::InvalidResponse do describe '#message' do let(:error) { described_class.new } it 'contains the problem in the message' do expect(error.message).to include('Invalid response') end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/exceptions/validation_spec.rb
spec/grape/exceptions/validation_spec.rb
# frozen_string_literal: true describe Grape::Exceptions::Validation do it 'fails when params are missing' do expect { described_class.new(message: 'presence') }.to raise_error(ArgumentError, /missing keyword:.+?params/) end context 'when message is a symbol' do it 'stores message_key' do expect(described_class.new(params: ['id'], message: :presence).message_key).to eq(:presence) end end context 'when message is a String' do it 'does not store the message_key' do expect(described_class.new(params: ['id'], message: 'presence').message_key).to be_nil end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/middleware/exception_spec.rb
spec/grape/middleware/exception_spec.rb
# frozen_string_literal: true describe Grape::Middleware::Error do let(:exception_app) do Class.new do class << self def call(_env) raise 'rain!' end end end end let(:other_exception_app) do Class.new do class << self def call(_env) raise NotImplementedError, 'snow!' end end end end let(:custom_error_app) do custom_error = Class.new(Grape::Exceptions::Base) Class.new do define_singleton_method(:call) do |_env| raise custom_error.new(status: 400, message: 'failed validation') end end end let(:error_hash_app) do Class.new do class << self def error!(message, status) throw :error, message: { error: message, detail: 'missing widget' }, status: status end def call(_env) error!('rain!', 401) end end end end let(:access_denied_app) do Class.new do class << self def error!(message, status) throw :error, message: message, status: status end def call(_env) error!('Access Denied', 401) end end end end let(:app) do opts = options app = running_app Rack::Builder.app do use Rack::Lint use Spec::Support::EndpointFaker if opts.any? use Grape::Middleware::Error, **opts else use Grape::Middleware::Error end run app end end context 'with defaults' do let(:running_app) { exception_app } let(:options) { {} } it 'does not trap errors by default' do expect { get '/' }.to raise_error(RuntimeError, 'rain!') end end context 'with rescue_all' do context 'StandardError exception' do let(:running_app) { exception_app } let(:options) { { rescue_all: true } } it 'sets the message appropriately' do get '/' expect(last_response.body).to eq('rain!') end it 'defaults to a 500 status' do get '/' expect(last_response.status).to eq(500) end end context 'Non-StandardError exception' do let(:running_app) { other_exception_app } let(:options) { { rescue_all: true } } it 'does not trap errors other than StandardError' do expect { get '/' }.to raise_error(NotImplementedError, 'snow!') end end end context 'Non-StandardError exception with a provided rescue handler' do context 'default error response' do let(:running_app) { other_exception_app } let(:options) { { rescue_handlers: { NotImplementedError => nil } } } it 'rescues the exception using the default handler' do get '/' expect(last_response.body).to eq('snow!') end end context 'custom error response' do let(:running_app) { other_exception_app } let(:options) { { rescue_handlers: { NotImplementedError => -> { Rack::Response.new('rescued', 200, {}) } } } } it 'rescues the exception using the provided handler' do get '/' expect(last_response.body).to eq('rescued') end end end context do let(:running_app) { exception_app } let(:options) { { rescue_all: true, default_status: 500 } } it 'is possible to specify a different default status code' do get '/' expect(last_response.status).to eq(500) end end context do let(:running_app) { exception_app } let(:options) { { rescue_all: true, format: :json } } it 'is possible to return errors in json format' do get '/' expect(last_response.body).to eq('{"error":"rain!"}') end end context do let(:running_app) { error_hash_app } let(:options) { { rescue_all: true, format: :json } } it 'is possible to return hash errors in json format' do get '/' expect(['{"error":"rain!","detail":"missing widget"}', '{"detail":"missing widget","error":"rain!"}']).to include(last_response.body) end end context do let(:running_app) { exception_app } let(:options) { { rescue_all: true, format: :xml } } it 'is possible to return errors in xml format' do get '/' expect(last_response.body).to eq("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<error>\n <message>rain!</message>\n</error>\n") end end context do let(:running_app) { error_hash_app } let(:options) { { rescue_all: true, format: :xml } } it 'is possible to return hash errors in xml format' do get '/' expect(["<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<error>\n <detail>missing widget</detail>\n <error>rain!</error>\n</error>\n", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<error>\n <error>rain!</error>\n <detail>missing widget</detail>\n</error>\n"]).to include(last_response.body) end end context do let(:running_app) { exception_app } let(:options) do { rescue_all: true, format: :custom, error_formatters: { custom: lambda do |message, _backtrace, _options, _env, _original_exception| { custom_formatter: message }.inspect end } } end it 'is possible to specify a custom formatter' do get '/' response = Rack::Utils.escape_html({ custom_formatter: 'rain!' }.inspect) expect(last_response.body).to eq(response) end end context do let(:running_app) { access_denied_app } let(:options) { {} } it 'does not trap regular error! codes' do get '/' expect(last_response.status).to eq(401) end end context do let(:running_app) { custom_error_app } let(:options) { { rescue_all: false } } it 'responds to custom Grape exceptions appropriately' do get '/' expect(last_response.status).to eq(400) expect(last_response.body).to eq('failed validation') end end context 'with rescue_options :backtrace and :exception set to true' do let(:running_app) { exception_app } let(:options) do { rescue_all: true, format: :json, rescue_options: { backtrace: true, original_exception: true } } end it 'is possible to return the backtrace and the original exception in json format' do get '/' expect(last_response.body).to include('error', 'rain!', 'backtrace', 'original_exception', 'RuntimeError') end end context do let(:running_app) { exception_app } let(:options) do { rescue_all: true, format: :xml, rescue_options: { backtrace: true, original_exception: true } } end it 'is possible to return the backtrace and the original exception in xml format' do get '/' expect(last_response.body).to include('error', 'rain!', 'backtrace', 'original-exception', 'RuntimeError') end end context do let(:running_app) { exception_app } let(:options) do { rescue_all: true, format: :txt, rescue_options: { backtrace: true, original_exception: true } } end it 'is possible to return the backtrace and the original exception in txt format' do get '/' expect(last_response.body).to include('error', 'rain!', 'backtrace', 'original exception', 'RuntimeError') end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/middleware/formatter_spec.rb
spec/grape/middleware/formatter_spec.rb
# frozen_string_literal: true describe Grape::Middleware::Formatter do subject { described_class.new(app) } before { allow(subject).to receive(:dup).and_return(subject) } let(:body) { { 'foo' => 'bar' } } let(:app) { ->(_env) { [200, {}, [body]] } } context 'serialization' do let(:body) { { 'abc' => 'def' } } let(:env) do { Rack::PATH_INFO => '/somewhere', 'HTTP_ACCEPT' => 'application/json' } end it 'looks at the bodies for possibly serializable data' do r = Rack::MockResponse[*subject.call(env)] expect(r.body).to eq(Grape::Json.dump(body)) end context 'default format' do let(:body) { ['foo'] } let(:env) do { Rack::PATH_INFO => '/somewhere', 'HTTP_ACCEPT' => '*/*' } end before do subject.options[:default_format] = :json end it 'returns JSON' do body.instance_eval do def to_json(*_args) '"bar"' end end r = Rack::MockResponse[*subject.call(env)] expect(r.body).to eq('"bar"') end end context 'xml' do let(:body) { +'string' } let(:env) do { Rack::PATH_INFO => '/somewhere.xml', 'HTTP_ACCEPT' => 'application/json' } end it 'calls #to_xml if the content type is xml' do body.instance_eval do def to_xml '<bar/>' end end r = Rack::MockResponse[*subject.call(env)] expect(r.body).to eq('<bar/>') end end end context 'error handling' do let(:formatter) { double(:formatter) } let(:env) do { Rack::PATH_INFO => '/somewhere.xml', 'HTTP_ACCEPT' => 'application/json' } end before do allow(Grape::Formatter).to receive(:formatter_for) { formatter } end it 'rescues formatter-specific exceptions' do allow(formatter).to receive(:call) { raise Grape::Exceptions::InvalidFormatter.new(String, 'xml') } expect do catch(:error) { subject.call(env) } end.not_to raise_error end it 'does not rescue other exceptions' do allow(formatter).to receive(:call) { raise StandardError } expect do catch(:error) { subject.call(Rack::PATH_INFO => '/somewhere.xml', 'HTTP_ACCEPT' => 'application/json') } end.to raise_error(StandardError) end end context 'detection' do context 'when path contains invalid byte sequence' do it 'does not raise an exception' do expect { subject.call(Rack::PATH_INFO => "/info.\x80") }.not_to raise_error end end it 'uses the xml extension if one is provided' do subject.call(Rack::PATH_INFO => '/info.xml') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:xml) end it 'uses the json extension if one is provided' do subject.call(Rack::PATH_INFO => '/info.json') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:json) end it 'uses the format parameter if one is provided' do subject.call(Rack::PATH_INFO => '/info', Rack::QUERY_STRING => 'format=json') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:json) end it 'uses the default format if none is provided' do subject.call(Rack::PATH_INFO => '/info') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:txt) end it 'uses the requested format if provided in headers' do subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/json') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:json) end it 'uses the file extension format if provided before headers' do subject.call(Rack::PATH_INFO => '/info.txt', 'HTTP_ACCEPT' => 'application/json') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:txt) end end context 'accept header detection' do context 'when header contains invalid byte sequence' do it 'does not raise an exception' do expect { subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => "Hello \x80") }.not_to raise_error end end it 'detects from the Accept header' do subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/xml') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:xml) end it 'uses quality rankings to determine formats' do subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/json; q=0.3,application/xml; q=1.0') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:xml) subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/json; q=1.0,application/xml; q=0.3') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:json) end it 'handles quality rankings mixed with nothing' do subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/json,application/xml; q=1.0') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:xml) subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/xml; q=1.0,application/json') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:json) end it 'handles quality rankings that have a default 1.0 value' do subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/json,application/xml;q=0.5') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:json) subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/xml;q=0.5,application/json') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:json) end it 'parses headers with other attributes' do subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/json; abc=2.3; q=1.0,application/xml; q=0.7') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:json) end it 'ensures that a quality of 0 is less preferred than any other content type' do subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/json;q=0.0,application/xml') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:xml) subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/xml,application/json;q=0.0') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:xml) end context 'with custom vendored content types' do context 'when registered' do subject { described_class.new(app, content_types: { custom: 'application/vnd.test+json' }) } it 'uses the custom type' do subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/vnd.test+json') expect(subject.env[Grape::Env::API_FORMAT]).to eq(:custom) end end context 'when unregistered' do it 'returns the default content type text/plain' do r = Rack::MockResponse[*subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/vnd.test+json')] expect(r.headers[Rack::CONTENT_TYPE]).to eq('text/plain') end end end it 'parses headers with symbols as hash keys' do subject.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/xml', system_time: '091293') expect(subject.env[:system_time]).to eq('091293') end end context 'content-type' do it 'is set for json' do _, headers, = subject.call(Rack::PATH_INFO => '/info.json') expect(headers[Rack::CONTENT_TYPE]).to eq('application/json') end it 'is set for xml' do _, headers, = subject.call(Rack::PATH_INFO => '/info.xml') expect(headers[Rack::CONTENT_TYPE]).to eq('application/xml') end it 'is set for txt' do _, headers, = subject.call(Rack::PATH_INFO => '/info.txt') expect(headers[Rack::CONTENT_TYPE]).to eq('text/plain') end it 'is set for custom' do s = described_class.new(app, content_types: { custom: 'application/x-custom' }) _, headers, = s.call(Rack::PATH_INFO => '/info.custom') expect(headers[Rack::CONTENT_TYPE]).to eq('application/x-custom') end it 'is set for vendored with registered type' do s = described_class.new(app, content_types: { custom: 'application/vnd.test+json' }) _, headers, = s.call(Rack::PATH_INFO => '/info', 'HTTP_ACCEPT' => 'application/vnd.test+json') expect(headers[Rack::CONTENT_TYPE]).to eq('application/vnd.test+json') end end context 'format' do it 'uses custom formatter' do s = described_class.new(app, content_types: { custom: "don't care" }, formatters: { custom: ->(_obj, _env) { 'CUSTOM FORMAT' } }) r = Rack::MockResponse[*s.call(Rack::PATH_INFO => '/info.custom')] expect(r.body).to eq('CUSTOM FORMAT') end context 'default' do let(:body) { ['blah'] } it 'uses default json formatter' do r = Rack::MockResponse[*subject.call(Rack::PATH_INFO => '/info.json')] expect(r.body).to eq(Grape::Json.dump(body)) end end it 'uses custom json formatter' do subject.options[:formatters] = { json: ->(_obj, _env) { 'CUSTOM JSON FORMAT' } } r = Rack::MockResponse[*subject.call(Rack::PATH_INFO => '/info.json')] expect(r.body).to eq('CUSTOM JSON FORMAT') end end context 'no content responses' do let(:no_content_response) { ->(status) { [status, {}, []] } } statuses_without_body = if Gem::Version.new(Rack.release) >= Gem::Version.new('2.1.0') Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.keys else Rack::Utils::STATUS_WITH_NO_ENTITY_BODY end statuses_without_body.each do |status| it "does not modify a #{status} response" do expected_response = no_content_response[status] allow(app).to receive(:call).and_return(expected_response) expect(subject.call({})).to eq(expected_response) end end end context 'input' do content_types = ['application/json', 'application/json; charset=utf-8'].freeze %w[POST PATCH PUT DELETE].each do |method| context 'when body is not nil or empty' do context 'when Content-Type is supported' do let(:io) { StringIO.new('{"is_boolean":true,"string":"thing"}') } let(:content_type) { 'application/json' } it "parses the body from #{method} and copies values into rack.request.form_hash" do subject.call( Rack::PATH_INFO => '/info', Rack::REQUEST_METHOD => method, 'CONTENT_TYPE' => content_type, Rack::RACK_INPUT => io, 'CONTENT_LENGTH' => io.length.to_s ) expect(subject.env[Rack::RACK_REQUEST_FORM_HASH]['is_boolean']).to be true expect(subject.env[Rack::RACK_REQUEST_FORM_HASH]['string']).to eq('thing') end end context 'when Content-Type is not supported' do let(:io) { StringIO.new('{"is_boolean":true,"string":"thing"}') } let(:content_type) { 'application/atom+xml' } it 'returns a 415 HTTP error status' do error = catch(:error) do subject.call( Rack::PATH_INFO => '/info', Rack::REQUEST_METHOD => method, 'CONTENT_TYPE' => content_type, Rack::RACK_INPUT => io, 'CONTENT_LENGTH' => io.length.to_s ) end expect(error[:status]).to eq(415) expect(error[:message]).to eq("The provided content-type 'application/atom+xml' is not supported.") end end end context 'when body is nil' do let(:io) { double } before do allow(io).to receive_message_chain(rewind: nil, read: nil) end it 'does not read and parse the body' do expect(subject).not_to receive(:read_rack_input) subject.call( Rack::PATH_INFO => '/info', Rack::REQUEST_METHOD => method, 'CONTENT_TYPE' => 'application/json', Rack::RACK_INPUT => io, 'CONTENT_LENGTH' => '0' ) end end context 'when body is empty' do let(:io) { double } before do allow(io).to receive_messages(rewind: nil, read: '') end it 'does not read and parse the body' do expect(subject).not_to receive(:read_rack_input) subject.call( Rack::PATH_INFO => '/info', Rack::REQUEST_METHOD => method, 'CONTENT_TYPE' => 'application/json', Rack::RACK_INPUT => io, 'CONTENT_LENGTH' => 0 ) end end content_types.each do |content_type| context content_type do it "parses the body from #{method} and copies values into rack.request.form_hash" do io = StringIO.new('{"is_boolean":true,"string":"thing"}') subject.call( Rack::PATH_INFO => '/info', Rack::REQUEST_METHOD => method, 'CONTENT_TYPE' => content_type, Rack::RACK_INPUT => io, 'CONTENT_LENGTH' => io.length.to_s ) expect(subject.env[Rack::RACK_REQUEST_FORM_HASH]['is_boolean']).to be true expect(subject.env[Rack::RACK_REQUEST_FORM_HASH]['string']).to eq('thing') end end end it "parses the chunked body from #{method} and copies values into rack.request.from_hash" do io = StringIO.new('{"is_boolean":true,"string":"thing"}') subject.call( Rack::PATH_INFO => '/infol', Rack::REQUEST_METHOD => method, 'CONTENT_TYPE' => 'application/json', Rack::RACK_INPUT => io, 'HTTP_TRANSFER_ENCODING' => 'chunked' ) expect(subject.env[Rack::RACK_REQUEST_FORM_HASH]['is_boolean']).to be true expect(subject.env[Rack::RACK_REQUEST_FORM_HASH]['string']).to eq('thing') end it 'rewinds IO' do io = StringIO.new('{"is_boolean":true,"string":"thing"}') io.read subject.call( Rack::PATH_INFO => '/infol', Rack::REQUEST_METHOD => method, 'CONTENT_TYPE' => 'application/json', Rack::RACK_INPUT => io, 'HTTP_TRANSFER_ENCODING' => 'chunked' ) expect(subject.env[Rack::RACK_REQUEST_FORM_HASH]['is_boolean']).to be true expect(subject.env[Rack::RACK_REQUEST_FORM_HASH]['string']).to eq('thing') end it "parses the body from an xml #{method} and copies values into rack.request.from_hash" do io = StringIO.new('<thing><name>Test</name></thing>') subject.call( Rack::PATH_INFO => '/info.xml', Rack::REQUEST_METHOD => method, 'CONTENT_TYPE' => 'application/xml', Rack::RACK_INPUT => io, 'CONTENT_LENGTH' => io.length.to_s ) if Object.const_defined? :MultiXml expect(subject.env[Rack::RACK_REQUEST_FORM_HASH]['thing']['name']).to eq('Test') else expect(subject.env[Rack::RACK_REQUEST_FORM_HASH]['thing']['name']['__content__']).to eq('Test') end end [Rack::Request::FORM_DATA_MEDIA_TYPES, Rack::Request::PARSEABLE_DATA_MEDIA_TYPES].flatten.each do |content_type| it "ignores #{content_type}" do io = StringIO.new('name=Other+Test+Thing') subject.call( Rack::PATH_INFO => '/info', Rack::REQUEST_METHOD => method, 'CONTENT_TYPE' => content_type, Rack::RACK_INPUT => io, 'CONTENT_LENGTH' => io.length.to_s ) expect(subject.env[Rack::RACK_REQUEST_FORM_HASH]).to be_nil end end end end context 'send file' do let(:file) { double(File) } let(:file_body) { Grape::ServeStream::StreamResponse.new(file) } let(:app) { ->(_env) { [200, {}, file_body] } } let(:body) { 'data' } let(:env) do { Rack::PATH_INFO => '/somewhere', 'HTTP_ACCEPT' => 'application/json' } end let(:headers) do if Gem::Version.new(Rack.release) < Gem::Version.new('3.1') { Rack::CONTENT_TYPE => 'application/json', Rack::CONTENT_LENGTH => body.bytesize.to_s } else { Rack::CONTENT_TYPE => 'application/json' } end end it 'returns a file response' do expect(file).to receive(:each).and_yield(body) r = Rack::MockResponse[*subject.call(env)] expect(r).to be_successful expect(r.headers).to eq(headers) expect(r.body).to eq('data') end end context 'inheritable formatters' do subject { described_class.new(app, formatters: { invalid: invalid_formatter }, content_types: { invalid: 'application/x-invalid' }) } let(:invalid_formatter) do Class.new do def self.call(_, _) { message: 'invalid' }.to_json end end end let(:app) { ->(_env) { [200, {}, ['']] } } let(:env) do Rack::MockRequest.env_for('/hello.invalid', 'HTTP_ACCEPT' => 'application/x-invalid') end it 'returns response by invalid formatter' do r = Rack::MockResponse[*subject.call(env)] expect(JSON.parse(r.body)).to eq('message' => 'invalid') end end context 'custom parser raises exception and rescue options are enabled for backtrace and original_exception' do it 'adds the backtrace and original_exception to the error output' do subject = described_class.new( app, rescue_options: { backtrace: true, original_exception: true }, parsers: { json: ->(_object, _env) { raise StandardError, 'fail' } } ) io = StringIO.new('{invalid}') error = catch(:error) do subject.call( Rack::PATH_INFO => '/info', Rack::REQUEST_METHOD => Rack::POST, 'CONTENT_TYPE' => 'application/json', Rack::RACK_INPUT => io, 'CONTENT_LENGTH' => io.length.to_s ) end expect(error[:message]).to eq 'fail' expect(error[:backtrace].size).to be >= 1 expect(error[:original_exception].class).to eq StandardError end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/middleware/versioner_spec.rb
spec/grape/middleware/versioner_spec.rb
# frozen_string_literal: true describe Grape::Middleware::Versioner do subject { described_class.using(strategy) } context 'when :path' do let(:strategy) { :path } it { is_expected.to eq(Grape::Middleware::Versioner::Path) } end context 'when :header' do let(:strategy) { :header } it { is_expected.to eq(Grape::Middleware::Versioner::Header) } end context 'when :param' do let(:strategy) { :param } it { is_expected.to eq(Grape::Middleware::Versioner::Param) } end context 'when :accept_version_header' do let(:strategy) { :accept_version_header } it { is_expected.to eq(Grape::Middleware::Versioner::AcceptVersionHeader) } end context 'when unknown' do let(:strategy) { :unknown } it 'raises an error' do expect { subject }.to raise_error Grape::Exceptions::InvalidVersionerOption, Grape::Exceptions::InvalidVersionerOption.new(strategy).message end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/middleware/base_spec.rb
spec/grape/middleware/base_spec.rb
# frozen_string_literal: true describe Grape::Middleware::Base do subject { described_class.new(blank_app) } let(:blank_app) { ->(_) { [200, {}, 'Hi there.'] } } before do # Keep it one object for testing. allow(subject).to receive(:dup).and_return(subject) end it 'has the app as an accessor' do expect(subject.app).to eq(blank_app) end it 'calls through to the app' do expect(subject.call({})).to eq([200, {}, 'Hi there.']) end context 'callbacks' do after { subject.call!({}) } it 'calls #before' do expect(subject).to receive(:before) end it 'calls #after' do expect(subject).to receive(:after) end end context 'callbacks on error' do let(:blank_app) { ->(_) { raise StandardError } } it 'calls #after' do expect(subject).to receive(:after) expect { subject.call({}) }.to raise_error(StandardError) end end context 'after callback' do before do allow(subject).to receive(:after).and_return([200, {}, 'Hello from after callback']) end it 'overwrites application response' do expect(subject.call!({}).last).to eq('Hello from after callback') end end context 'after callback with errors' do it 'does not overwrite the application response' do expect(subject.call({})).to eq([200, {}, 'Hi there.']) end context 'with patched warnings' do before do @warnings = warnings = [] allow(subject).to receive(:warn) { |m| warnings << m } allow(subject).to receive(:after).and_raise(StandardError) end it 'does show a warning' do expect { subject.call({}) }.to raise_error(StandardError) expect(@warnings).not_to be_empty end end end it 'is able to access the response' do subject.call({}) expect(subject.response).to be_a(Rack::Response) end describe '#response' do subject do described_class.new(response) end before { subject.call({}) } context 'when Array' do let(:rack_response) { Rack::Response.new('test', 204, abc: 1) } let(:response) { ->(_) { [204, { abc: 1 }, 'test'] } } it 'status' do expect(subject.response.status).to eq(204) end it 'body' do expect(subject.response.body).to eq(['test']) end it 'header' do expect(subject.response.headers).to have_key(:abc) end it 'returns the memoized Rack::Response instance' do allow(Rack::Response).to receive(:new).and_return(rack_response) expect(subject.response).to eq(rack_response) end end context 'when Rack::Response' do let(:rack_response) { Rack::Response.new('test', 204, abc: 1) } let(:response) { ->(_) { rack_response } } it 'status' do expect(subject.response.status).to eq(204) end it 'body' do expect(subject.response.body).to eq(['test']) end it 'header' do expect(subject.response.headers).to have_key(:abc) end it 'returns the memoized Rack::Response instance' do expect(subject.response).to eq(rack_response) end end end describe '#context' do subject { described_class.new(blank_app) } it 'allows access to response context' do subject.call(Grape::Env::API_ENDPOINT => { header: 'some header' }) expect(subject.context).to eq(header: 'some header') end end context 'options' do it 'persists options passed at initialization' do expect(described_class.new(blank_app, abc: true).options[:abc]).to be true end context 'defaults' do let(:example_ware) do Class.new(Grape::Middleware::Base) do const_set(:DEFAULT_OPTIONS, { monkey: true }.freeze) end end it 'persists the default options' do expect(example_ware.new(blank_app).options[:monkey]).to be true end it 'overrides default options when provided' do expect(example_ware.new(blank_app, monkey: false).options[:monkey]).to be false end end end context 'header' do let(:example_ware) do Class.new(Grape::Middleware::Base) do def before header 'X-Test-Before', 'Hi' end def after header 'X-Test-After', 'Bye' nil end end end let(:app) do context = self Rack::Builder.app do use context.example_ware run ->(_) { [200, {}, ['Yeah']] } end end it 'is able to set a header' do get '/' expect(last_response.headers['X-Test-Before']).to eq('Hi') expect(last_response.headers['X-Test-After']).to eq('Bye') end end context 'header overwrite' do let(:example_ware) do Class.new(Grape::Middleware::Base) do def before header 'X-Test-Overwriting', 'Hi' end def after header 'X-Test-Overwriting', 'Bye' nil end end end let(:api) do Class.new(Grape::API) do get('/') do header 'X-Test-Overwriting', 'Yeah' 'Hello' end end end let(:app) do context = self Rack::Builder.app do use context.example_ware run context.api.new end end it 'overwrites header by after headers' do get '/' expect(last_response.headers['X-Test-Overwriting']).to eq('Bye') end end describe 'query_params' do let(:dummy_middleware) do Class.new(Grape::Middleware::Base) do def before query_params end end end let(:app) do context = self Rack::Builder.app do use context.dummy_middleware run ->(_) { [200, {}, ['Yeah']] } end end context 'when query params are conflicting' do it 'raises an ConflictingTypes error' do expect { get '/?x[y]=1&x[y]z=2' }.to raise_error(Grape::Exceptions::ConflictingTypes) end end context 'when query params is over the specified limit' do let(:query_params) { "foo#{'[a]' * Rack::Utils.param_depth_limit}=bar" } it 'raises an ConflictingTypes error' do expect { get "/?foo#{'[a]' * Rack::Utils.param_depth_limit}=bar" }.to raise_error(Grape::Exceptions::TooDeepParameters) end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/middleware/stack_spec.rb
spec/grape/middleware/stack_spec.rb
# frozen_string_literal: true describe Grape::Middleware::Stack do subject { described_class.new } let(:foo_middleware) { Class.new } let(:bar_middleware) { Class.new } let(:block_middleware) do Class.new do attr_reader :block def initialize(&block) @block = block end end end let(:proc) { -> {} } let(:others) { [[:use, bar_middleware], [:insert_before, bar_middleware, block_middleware, proc]] } before do subject.use foo_middleware end describe '#use' do it 'pushes a middleware class onto the stack' do expect { subject.use bar_middleware } .to change(subject, :size).by(1) expect(subject.last).to eq(bar_middleware) end it 'pushes a middleware class with arguments onto the stack' do expect { subject.use bar_middleware, false, my_arg: 42 } .to change(subject, :size).by(1) expect(subject.last).to eq(bar_middleware) expect(subject.last.args).to eq([false, { my_arg: 42 }]) end it 'pushes a middleware class with block arguments onto the stack' do expect { subject.use block_middleware, &proc } .to change(subject, :size).by(1) expect(subject.last).to eq(block_middleware) expect(subject.last.args).to eq([]) expect(subject.last.block).to eq(proc) end end describe '#insert' do it 'inserts a middleware class at the integer index' do expect { subject.insert 0, bar_middleware } .to change(subject, :size).by(1) expect(subject[0]).to eq(bar_middleware) expect(subject[1]).to eq(foo_middleware) end end describe '#insert_before' do it 'inserts a middleware before another middleware class' do expect { subject.insert_before foo_middleware, bar_middleware } .to change(subject, :size).by(1) expect(subject[0]).to eq(bar_middleware) expect(subject[1]).to eq(foo_middleware) end it 'inserts a middleware before an anonymous class given by its superclass' do subject.use Class.new(block_middleware) expect { subject.insert_before block_middleware, bar_middleware } .to change(subject, :size).by(1) expect(subject[1]).to eq(bar_middleware) expect(subject[2]).to eq(block_middleware) end it 'raises an error on an invalid index' do stub_const('StackSpec::BlockMiddleware', block_middleware) expect { subject.insert_before block_middleware, bar_middleware } .to raise_error(RuntimeError, 'No such middleware to insert before: StackSpec::BlockMiddleware') end end describe '#insert_after' do it 'inserts a middleware after another middleware class' do expect { subject.insert_after foo_middleware, bar_middleware } .to change(subject, :size).by(1) expect(subject[1]).to eq(bar_middleware) expect(subject[0]).to eq(foo_middleware) end it 'inserts a middleware after an anonymous class given by its superclass' do subject.use Class.new(block_middleware) expect { subject.insert_after block_middleware, bar_middleware } .to change(subject, :size).by(1) expect(subject[1]).to eq(block_middleware) expect(subject[2]).to eq(bar_middleware) end it 'raises an error on an invalid index' do stub_const('StackSpec::BlockMiddleware', block_middleware) expect { subject.insert_after block_middleware, bar_middleware } .to raise_error(RuntimeError, 'No such middleware to insert after: StackSpec::BlockMiddleware') end end describe '#merge_with' do it 'applies a collection of operations and middlewares' do expect { subject.merge_with(others) } .to change(subject, :size).by(2) expect(subject[0]).to eq(foo_middleware) expect(subject[1]).to eq(block_middleware) expect(subject[2]).to eq(bar_middleware) end context 'middleware spec with proc declaration exists' do let(:middleware_spec_with_proc) { [:use, foo_middleware, proc] } it 'properly forwards spec arguments' do expect(subject).to receive(:use).with(foo_middleware) subject.merge_with([middleware_spec_with_proc]) end end end describe '#build' do it 'returns a rack builder instance' do expect(subject.build).to be_instance_of(Rack::Builder) end context 'when @others are present' do let(:others) { [[:insert_after, Grape::Middleware::Formatter, bar_middleware]] } it 'applies the middleware specs stored in @others' do subject.concat others subject.use Grape::Middleware::Formatter subject.build expect(subject[0]).to eq foo_middleware expect(subject[1]).to eq Grape::Middleware::Formatter expect(subject[2]).to eq bar_middleware end end end describe '#concat' do it 'adds non :use specs to @others' do expect { subject.concat others }.to change(subject, :others).from([]).to([[others.last]]) end it 'calls +merge_with+ with the :use specs' do expect(subject).to receive(:merge_with).with [[:use, bar_middleware]] subject.concat others end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/middleware/error_spec.rb
spec/grape/middleware/error_spec.rb
# frozen_string_literal: true describe Grape::Middleware::Error do let(:error_entity) do Class.new(Grape::Entity) do expose :code expose :static def static 'static text' end end end let(:err_app) do Class.new do class << self attr_accessor :error, :format def call(_env) throw :error, error end end end end let(:options) { { default_message: 'Aww, hamburgers.' } } let(:app) do opts = options context = self Rack::Builder.app do use Spec::Support::EndpointFaker use Grape::Middleware::Error, **opts # rubocop:disable RSpec/DescribedClass run context.err_app end end it 'sets the status code appropriately' do err_app.error = { status: 410 } get '/' expect(last_response.status).to eq(410) end it 'sets the status code based on the rack util status code symbol' do err_app.error = { status: :gone } get '/' expect(last_response.status).to eq(410) end it 'sets the error message appropriately' do err_app.error = { message: 'Awesome stuff.' } get '/' expect(last_response.body).to eq('Awesome stuff.') end it 'defaults to a 500 status' do err_app.error = {} get '/' expect(last_response).to be_server_error end it 'has a default message' do err_app.error = {} get '/' expect(last_response.body).to eq('Aww, hamburgers.') end context 'with http code' do let(:options) { { default_message: 'Aww, hamburgers.' } } it 'adds the status code if wanted' do err_app.error = { message: { code: 200 } } get '/' expect(last_response.body).to eq({ code: 200 }.to_json) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/middleware/globals_spec.rb
spec/grape/middleware/globals_spec.rb
# frozen_string_literal: true describe Grape::Middleware::Globals do subject { described_class.new(blank_app) } before { allow(subject).to receive(:dup).and_return(subject) } let(:blank_app) { ->(_env) { [200, {}, 'Hi there.'] } } it 'calls through to the app' do expect(subject.call({})).to eq([200, {}, 'Hi there.']) end context 'environment' do it 'sets the grape.request environment' do subject.call({}) expect(subject.env[Grape::Env::GRAPE_REQUEST]).to be_a(Grape::Request) end it 'sets the grape.request.headers environment' do subject.call({}) expect(subject.env[Grape::Env::GRAPE_REQUEST_HEADERS]).to be_a(Hash) end it 'sets the grape.request.params environment' do subject.call(Rack::QUERY_STRING => 'test=1', Rack::RACK_INPUT => StringIO.new) expect(subject.env[Grape::Env::GRAPE_REQUEST_PARAMS]).to be_a(Hash) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/middleware/auth/dsl_spec.rb
spec/grape/middleware/auth/dsl_spec.rb
# frozen_string_literal: true describe Grape::Middleware::Auth::DSL do subject { Class.new(Grape::API) } let(:block) { -> {} } let(:settings) do { opaque: 'secret', proc: block, realm: 'API Authorization', type: :http_digest } end describe '.auth' do it 'sets auth parameters' do expect(subject.base_instance).to receive(:use).with(Grape::Middleware::Auth::Base, settings) subject.auth :http_digest, realm: settings[:realm], opaque: settings[:opaque], &settings[:proc] expect(subject.auth).to eq(settings) end it 'can be called multiple times' do expect(subject.base_instance).to receive(:use).with(Grape::Middleware::Auth::Base, settings) expect(subject.base_instance).to receive(:use).with(Grape::Middleware::Auth::Base, settings.merge(realm: 'super_secret')) subject.auth :http_digest, realm: settings[:realm], opaque: settings[:opaque], &settings[:proc] first_settings = subject.auth subject.auth :http_digest, realm: 'super_secret', opaque: settings[:opaque], &settings[:proc] expect(subject.auth).to eq(settings.merge(realm: 'super_secret')) expect(subject.auth.object_id).not_to eq(first_settings.object_id) end end describe '.http_basic' do it 'sets auth parameters' do subject.http_basic realm: 'my_realm', &settings[:proc] expect(subject.auth).to eq(realm: 'my_realm', type: :http_basic, proc: block) end end describe '.http_digest' do context 'when realm is a hash' do it 'sets auth parameters' do subject.http_digest realm: { realm: 'my_realm', opaque: 'my_opaque' }, &settings[:proc] expect(subject.auth).to eq(realm: { realm: 'my_realm', opaque: 'my_opaque' }, type: :http_digest, proc: block) end end context 'when realm is not hash' do it 'sets auth parameters' do subject.http_digest realm: 'my_realm', opaque: 'my_opaque', &settings[:proc] expect(subject.auth).to eq(realm: 'my_realm', type: :http_digest, proc: block, opaque: 'my_opaque') end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/middleware/auth/strategies_spec.rb
spec/grape/middleware/auth/strategies_spec.rb
# frozen_string_literal: true describe Grape::Middleware::Auth::Strategies do describe 'Basic Auth' do let(:app) do proc = ->(u, p) { u && p && u == p } Rack::Builder.app do use Grape::Middleware::Error use(Grape::Middleware::Auth::Base, type: :http_basic, proc: proc) run ->(_env) { [200, {}, ['Hello there.']] } end end it 'throws a 401 if no auth is given' do get '/whatever' expect(last_response).to be_unauthorized end it 'authenticates if given valid creds' do get '/whatever', {}, 'HTTP_AUTHORIZATION' => encode_basic_auth('admin', 'admin') expect(last_response).to be_successful expect(last_response.body).to eq('Hello there.') end it 'throws a 401 is wrong auth is given' do get '/whatever', {}, 'HTTP_AUTHORIZATION' => encode_basic_auth('admin', 'wrong') expect(last_response).to be_unauthorized end end describe 'Unknown Auth' do context 'when type is not register' do let(:app) do Class.new(Grape::API) do use Grape::Middleware::Auth::Base, type: :unknown get('/whatever') { 'Hello there.' } end end it 'throws a 401' do expect { get '/whatever' }.to raise_error(Grape::Exceptions::UnknownAuthStrategy, 'unknown auth strategy: unknown') end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/middleware/auth/base_spec.rb
spec/grape/middleware/auth/base_spec.rb
# frozen_string_literal: true describe Grape::Middleware::Auth::Base do subject do Class.new(Grape::API) do http_basic realm: 'my_realm' do |user, password| user && password && user == password end get '/authorized' do 'DONE' end end end let(:app) { subject } it 'authenticates if given valid creds' do get '/authorized', {}, 'HTTP_AUTHORIZATION' => encode_basic_auth('admin', 'admin') expect(last_response).to be_successful expect(last_response.body).to eq('DONE') end it 'throws a 401 is wrong auth is given' do get '/authorized', {}, 'HTTP_AUTHORIZATION' => encode_basic_auth('admin', 'wrong') expect(last_response).to be_unauthorized end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/middleware/versioner/path_spec.rb
spec/grape/middleware/versioner/path_spec.rb
# frozen_string_literal: true describe Grape::Middleware::Versioner::Path do subject { described_class.new(app, **options) } let(:app) { ->(env) { [200, env, env[Grape::Env::API_VERSION]] } } let(:options) { {} } it 'sets the API version based on the first path' do expect(subject.call(Rack::PATH_INFO => '/v1/awesome').last).to eq('v1') end it 'does not cut the version out of the path' do expect(subject.call(Rack::PATH_INFO => '/v1/awesome')[1][Rack::PATH_INFO]).to eq('/v1/awesome') end it 'provides a nil version if no path is given' do expect(subject.call(Rack::PATH_INFO => '/').last).to be_nil end context 'with a pattern' do let(:options) { { pattern: /v./i } } it 'sets the version if it matches' do expect(subject.call(Rack::PATH_INFO => '/v1/awesome').last).to eq('v1') end it 'ignores the version if it fails to match' do expect(subject.call(Rack::PATH_INFO => '/awesome/radical').last).to be_nil end end [%w[v1 v2], %i[v1 v2], [:v1, 'v2'], ['v1', :v2]].each do |versions| context "with specified versions as #{versions}" do let(:options) { { versions: versions } } it 'throws an error if a non-allowed version is specified' do expect(catch(:error) { subject.call(Rack::PATH_INFO => '/v3/awesome') }[:status]).to eq(404) end it 'allows versions that have been specified' do expect(subject.call(Rack::PATH_INFO => '/v1/asoasd').last).to eq('v1') end end end context 'with prefix, but requested version is not matched' do let(:options) { { prefix: '/v1', pattern: /v./i } } it 'recognizes potential version' do expect(subject.call(Rack::PATH_INFO => '/v3/foo').last).to eq('v3') end end context 'with mount path' do let(:options) { { mount_path: '/mounted', versions: [:v1] } } it 'recognizes potential version' do expect(subject.call(Rack::PATH_INFO => '/mounted/v1/foo').last).to eq('v1') end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/middleware/versioner/header_spec.rb
spec/grape/middleware/versioner/header_spec.rb
# frozen_string_literal: true describe Grape::Middleware::Versioner::Header do subject { described_class.new(app, **@options) } let(:app) { ->(env) { [200, env, env] } } before do @options = { version_options: { using: :header, vendor: 'vendor' } } end context 'api.type and api.subtype' do it 'sets type and subtype to first choice of content type if no preference given' do status, _, env = subject.call('HTTP_ACCEPT' => '*/*') expect(env[Grape::Env::API_TYPE]).to eql 'application' expect(env[Grape::Env::API_SUBTYPE]).to eql 'vnd.vendor+xml' expect(status).to eq(200) end it 'sets preferred type' do status, _, env = subject.call('HTTP_ACCEPT' => 'application/*') expect(env[Grape::Env::API_TYPE]).to eql 'application' expect(env[Grape::Env::API_SUBTYPE]).to eql 'vnd.vendor+xml' expect(status).to eq(200) end it 'sets preferred type and subtype' do status, _, env = subject.call('HTTP_ACCEPT' => 'text/plain') expect(env[Grape::Env::API_TYPE]).to eql 'text' expect(env[Grape::Env::API_SUBTYPE]).to eql 'plain' expect(status).to eq(200) end end context 'api.format' do it 'is set' do status, _, env = subject.call('HTTP_ACCEPT' => 'application/vnd.vendor+json') expect(env[Grape::Env::API_FORMAT]).to eql 'json' expect(status).to eq(200) end it 'is nil if not provided' do status, _, env = subject.call('HTTP_ACCEPT' => 'application/vnd.vendor') expect(env[Grape::Env::API_FORMAT]).to be_nil expect(status).to eq(200) end ['v1', :v1].each do |version| context "when version is set to #{version}" do before do @options[:versions] = [version] end it 'is set' do status, _, env = subject.call('HTTP_ACCEPT' => 'application/vnd.vendor-v1+json') expect(env[Grape::Env::API_FORMAT]).to eql 'json' expect(status).to eq(200) end it 'is nil if not provided' do status, _, env = subject.call('HTTP_ACCEPT' => 'application/vnd.vendor-v1') expect(env[Grape::Env::API_FORMAT]).to be_nil expect(status).to eq(200) end end end end context 'api.vendor' do it 'is set' do status, _, env = subject.call('HTTP_ACCEPT' => 'application/vnd.vendor') expect(env[Grape::Env::API_VENDOR]).to eql 'vendor' expect(status).to eq(200) end it 'is set if format provided' do status, _, env = subject.call('HTTP_ACCEPT' => 'application/vnd.vendor+json') expect(env[Grape::Env::API_VENDOR]).to eql 'vendor' expect(status).to eq(200) end it 'fails with 406 Not Acceptable if vendor is invalid' do expect { subject.call('HTTP_ACCEPT' => 'application/vnd.othervendor+json').last } .to raise_exception do |exception| expect(exception).to be_a(Grape::Exceptions::InvalidAcceptHeader) expect(exception.headers).to eql('X-Cascade' => 'pass') expect(exception.status).to be 406 expect(exception.message).to include 'API vendor not found' end end context 'when version is set' do before do @options[:versions] = ['v1'] end it 'is set' do status, _, env = subject.call('HTTP_ACCEPT' => 'application/vnd.vendor-v1') expect(env[Grape::Env::API_VENDOR]).to eql 'vendor' expect(status).to eq(200) end it 'is set if format provided' do status, _, env = subject.call('HTTP_ACCEPT' => 'application/vnd.vendor-v1+json') expect(env[Grape::Env::API_VENDOR]).to eql 'vendor' expect(status).to eq(200) end it 'fails with 406 Not Acceptable if vendor is invalid' do expect { subject.call('HTTP_ACCEPT' => 'application/vnd.othervendor-v1+json').last } .to raise_exception do |exception| expect(exception).to be_a(Grape::Exceptions::InvalidAcceptHeader) expect(exception.headers).to eql('X-Cascade' => 'pass') expect(exception.status).to be 406 expect(exception.message).to include('API vendor not found') end end end end context 'api.version' do before do @options[:versions] = ['v1'] end it 'is set' do status, _, env = subject.call('HTTP_ACCEPT' => 'application/vnd.vendor-v1') expect(env[Grape::Env::API_VERSION]).to eql 'v1' expect(status).to eq(200) end it 'is set if format provided' do status, _, env = subject.call('HTTP_ACCEPT' => 'application/vnd.vendor-v1+json') expect(env[Grape::Env::API_VERSION]).to eql 'v1' expect(status).to eq(200) end it 'fails with 406 Not Acceptable if version is invalid' do expect { subject.call('HTTP_ACCEPT' => 'application/vnd.vendor-v2+json').last }.to raise_exception do |exception| expect(exception).to be_a(Grape::Exceptions::InvalidVersionHeader) expect(exception.headers).to eql('X-Cascade' => 'pass') expect(exception.status).to be 406 expect(exception.message).to include('API version not found') end end end it 'succeeds if :strict is not set' do expect(subject.call('HTTP_ACCEPT' => '').first).to eq(200) expect(subject.call({}).first).to eq(200) end it 'succeeds if :strict is set to false' do @options[:version_options][:strict] = false expect(subject.call('HTTP_ACCEPT' => '').first).to eq(200) expect(subject.call({}).first).to eq(200) end it 'succeeds if :strict is set to false and given an invalid header' do @options[:version_options][:strict] = false expect(subject.call('HTTP_ACCEPT' => 'yaml').first).to eq(200) expect(subject.call({}).first).to eq(200) end context 'when :strict is set' do before do @options[:versions] = ['v1'] @options[:version_options][:strict] = true end it 'fails with 406 Not Acceptable if header is not set' do expect { subject.call({}).last }.to raise_exception do |exception| expect(exception).to be_a(Grape::Exceptions::InvalidAcceptHeader) expect(exception.headers).to eql('X-Cascade' => 'pass') expect(exception.status).to be 406 expect(exception.message).to include('Accept header must be set.') end end it 'fails with 406 Not Acceptable if header is empty' do expect { subject.call('HTTP_ACCEPT' => '').last }.to raise_exception do |exception| expect(exception).to be_a(Grape::Exceptions::InvalidAcceptHeader) expect(exception.headers).to eql('X-Cascade' => 'pass') expect(exception.status).to be 406 expect(exception.message).to include('Accept header must be set.') end end it 'succeeds if proper header is set' do expect(subject.call('HTTP_ACCEPT' => 'application/vnd.vendor-v1+json').first).to eq(200) end end context 'when :strict and cascade: false' do before do @options[:versions] = ['v1'] @options[:version_options][:strict] = true @options[:version_options][:cascade] = false end it 'fails with 406 Not Acceptable if header is not set' do expect { subject.call({}).last }.to raise_exception do |exception| expect(exception).to be_a(Grape::Exceptions::InvalidAcceptHeader) expect(exception.headers).to eql({}) expect(exception.status).to be 406 expect(exception.message).to include('Accept header must be set.') end end it 'fails with 406 Not Acceptable if header is application/xml' do expect { subject.call('HTTP_ACCEPT' => 'application/xml').last } .to raise_exception do |exception| expect(exception).to be_a(Grape::Exceptions::InvalidAcceptHeader) expect(exception.headers).to eql({}) expect(exception.status).to be 406 expect(exception.message).to include('API vendor or version not found.') end end it 'fails with 406 Not Acceptable if header is empty' do expect { subject.call('HTTP_ACCEPT' => '').last }.to raise_exception do |exception| expect(exception).to be_a(Grape::Exceptions::InvalidAcceptHeader) expect(exception.headers).to eql({}) expect(exception.status).to be 406 expect(exception.message).to include('Accept header must be set.') end end it 'fails with 406 Not Acceptable if header contains a single invalid accept' do expect { subject.call('HTTP_ACCEPT' => 'application/json;application/vnd.vendor-v1+json').first } .to raise_exception do |exception| expect(exception).to be_a(Grape::Exceptions::InvalidAcceptHeader) expect(exception.headers).to eql({}) expect(exception.status).to be 406 expect(exception.message).to include('API vendor or version not found.') end end it 'succeeds if proper header is set' do expect(subject.call('HTTP_ACCEPT' => 'application/vnd.vendor-v1+json').first).to eq(200) end end context 'when multiple versions are specified' do before do @options[:versions] = %w[v1 v2] end it 'succeeds with v1' do expect(subject.call('HTTP_ACCEPT' => 'application/vnd.vendor-v1+json').first).to eq(200) end it 'succeeds with v2' do expect(subject.call('HTTP_ACCEPT' => 'application/vnd.vendor-v2+json').first).to eq(200) end it 'fails with another version' do expect { subject.call('HTTP_ACCEPT' => 'application/vnd.vendor-v3+json') }.to raise_exception do |exception| expect(exception).to be_a(Grape::Exceptions::InvalidVersionHeader) expect(exception.headers).to eql('X-Cascade' => 'pass') expect(exception.status).to be 406 expect(exception.message).to include('API version not found') end end end context 'when there are multiple versions with complex vendor specified with rescue_from :all' do subject do Class.new(Grape::API) do rescue_from :all end end let(:v1_app) do Class.new(Grape::API) do version 'v1', using: :header, vendor: 'test.a-cool_resource', cascade: false, strict: true content_type :v1_test, 'application/vnd.test.a-cool_resource-v1+json' formatter :v1_test, ->(object, _) { object } format :v1_test resources :users do get :hello do 'one' end end end end let(:v2_app) do Class.new(Grape::API) do version 'v2', using: :header, vendor: 'test.a-cool_resource', strict: true content_type :v2_test, 'application/vnd.test.a-cool_resource-v2+json' formatter :v2_test, ->(object, _) { object } format :v2_test resources :users do get :hello do 'two' end end end end def app subject.mount v2_app subject.mount v1_app subject end context 'with header versioned endpoints and a rescue_all block defined' do it 'responds correctly to a v1 request' do versioned_get '/users/hello', 'v1', using: :header, vendor: 'test.a-cool_resource' expect(last_response.body).to eq('one') expect(last_response.body).not_to include('API vendor or version not found') end it 'responds correctly to a v2 request' do versioned_get '/users/hello', 'v2', using: :header, vendor: 'test.a-cool_resource' expect(last_response.body).to eq('two') expect(last_response.body).not_to include('API vendor or version not found') end end end context 'with missing vendor option' do subject do Class.new(Grape::API) do version 'v1', using: :header end end def app subject end it 'fails' do expect { versioned_get '/', 'v1', using: :header }.to raise_error Grape::Exceptions::MissingVendorOption end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/middleware/versioner/param_spec.rb
spec/grape/middleware/versioner/param_spec.rb
# frozen_string_literal: true describe Grape::Middleware::Versioner::Param do subject { described_class.new(app, **options) } let(:app) { ->(env) { [200, env, env[Grape::Env::API_VERSION]] } } let(:options) { {} } it 'sets the API version based on the default param (apiver)' do env = Rack::MockRequest.env_for('/awesome', params: { 'apiver' => 'v1' }) expect(subject.call(env)[1][Grape::Env::API_VERSION]).to eq('v1') end it 'cuts (only) the version out of the params' do env = Rack::MockRequest.env_for('/awesome', params: { 'apiver' => 'v1', 'other_param' => '5' }) env[Rack::RACK_REQUEST_QUERY_HASH] = Rack::Utils.parse_nested_query(env[Rack::QUERY_STRING]) expect(subject.call(env)[1][Rack::RACK_REQUEST_QUERY_HASH]['apiver']).to be_nil expect(subject.call(env)[1][Rack::RACK_REQUEST_QUERY_HASH]['other_param']).to eq('5') end it 'provides a nil version if no version is given' do env = Rack::MockRequest.env_for('/') expect(subject.call(env).last).to be_nil end context 'with specified parameter name' do let(:options) { { version_options: { parameter: 'v' } } } it 'sets the API version based on the custom parameter name' do env = Rack::MockRequest.env_for('/awesome', params: { 'v' => 'v1' }) expect(subject.call(env)[1][Grape::Env::API_VERSION]).to eq('v1') end it 'does not set the API version based on the default param' do env = Rack::MockRequest.env_for('/awesome', params: { 'apiver' => 'v1' }) expect(subject.call(env)[1][Grape::Env::API_VERSION]).to be_nil end end context 'with specified versions' do let(:options) { { versions: %w[v1 v2] } } it 'throws an error if a non-allowed version is specified' do env = Rack::MockRequest.env_for('/awesome', params: { 'apiver' => 'v3' }) expect(catch(:error) { subject.call(env) }[:status]).to eq(404) end it 'allows versions that have been specified' do env = Rack::MockRequest.env_for('/awesome', params: { 'apiver' => 'v1' }) expect(subject.call(env)[1][Grape::Env::API_VERSION]).to eq('v1') end end context 'when no version is set' do let(:options) do { versions: ['v1'], version_options: { using: :header } } end it 'returns a 200 (matches the first version found)' do env = Rack::MockRequest.env_for('/awesome', params: {}) expect(subject.call(env).first).to eq(200) end end context 'when there are multiple versions without a custom param' do subject { Class.new(Grape::API) } let(:v1_app) do Class.new(Grape::API) do version 'v1', using: :param content_type :v1_test, 'application/vnd.test.a-cool_resource-v1+json' formatter :v1_test, ->(object, _) { object } format :v1_test resources :users do get :hello do 'one' end end end end let(:v2_app) do Class.new(Grape::API) do version 'v2', using: :param content_type :v2_test, 'application/vnd.test.a-cool_resource-v2+json' formatter :v2_test, ->(object, _) { object } format :v2_test resources :users do get :hello do 'two' end end end end def app subject.mount v2_app subject.mount v1_app subject end it 'responds correctly to a v1 request' do versioned_get '/users/hello', 'v1', using: :param, parameter: :apiver expect(last_response.body).to eq('one') expect(last_response.body).not_to include('API vendor or version not found') end it 'responds correctly to a v2 request' do versioned_get '/users/hello', 'v2', using: :param, parameter: :apiver expect(last_response.body).to eq('two') expect(last_response.body).not_to include('API vendor or version not found') end end context 'when there are multiple versions with a custom param' do subject { Class.new(Grape::API) } let(:v1_app) do Class.new(Grape::API) do version 'v1', using: :param, parameter: 'v' content_type :v1_test, 'application/vnd.test.a-cool_resource-v1+json' formatter :v1_test, ->(object, _) { object } format :v1_test resources :users do get :hello do 'one' end end end end let(:v2_app) do Class.new(Grape::API) do version 'v2', using: :param, parameter: 'v' content_type :v2_test, 'application/vnd.test.a-cool_resource-v2+json' formatter :v2_test, ->(object, _) { object } format :v2_test resources :users do get :hello do 'two' end end end end def app subject.mount v2_app subject.mount v1_app subject end it 'responds correctly to a v1 request' do versioned_get '/users/hello', 'v1', using: :param, parameter: 'v' expect(last_response.body).to eq('one') expect(last_response.body).not_to include('API vendor or version not found') end it 'responds correctly to a v2 request' do versioned_get '/users/hello', 'v2', using: :param, parameter: 'v' expect(last_response.body).to eq('two') expect(last_response.body).not_to include('API vendor or version not found') end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/middleware/versioner/accept_version_header_spec.rb
spec/grape/middleware/versioner/accept_version_header_spec.rb
# frozen_string_literal: true describe Grape::Middleware::Versioner::AcceptVersionHeader do subject { described_class.new(app, **@options) } let(:app) { ->(env) { [200, env, env] } } before do @options = { version_options: { using: :accept_version_header } } end describe '#bad encoding' do before do @options[:versions] = %w[v1] end it 'does not raise an error' do expect do subject.call('HTTP_ACCEPT_VERSION' => "\x80") end.to throw_symbol(:error, status: 406, headers: { 'X-Cascade' => 'pass' }, message: 'The requested version is not supported.') end end context 'api.version' do before do @options[:versions] = ['v1'] end it 'is set' do status, _, env = subject.call('HTTP_ACCEPT_VERSION' => 'v1') expect(env[Grape::Env::API_VERSION]).to eql 'v1' expect(status).to eq(200) end it 'is set if format provided' do status, _, env = subject.call('HTTP_ACCEPT_VERSION' => 'v1') expect(env[Grape::Env::API_VERSION]).to eql 'v1' expect(status).to eq(200) end it 'fails with 406 Not Acceptable if version is not supported' do expect do subject.call('HTTP_ACCEPT_VERSION' => 'v2').last end.to throw_symbol( :error, status: 406, headers: { 'X-Cascade' => 'pass' }, message: 'The requested version is not supported.' ) end end it 'succeeds if :strict is not set' do expect(subject.call('HTTP_ACCEPT_VERSION' => '').first).to eq(200) expect(subject.call({}).first).to eq(200) end it 'succeeds if :strict is set to false' do @options[:version_options][:strict] = false expect(subject.call('HTTP_ACCEPT_VERSION' => '').first).to eq(200) expect(subject.call({}).first).to eq(200) end context 'when :strict is set' do before do @options[:versions] = ['v1'] @options[:version_options][:strict] = true end it 'fails with 406 Not Acceptable if header is not set' do expect do subject.call({}).last end.to throw_symbol( :error, status: 406, headers: { 'X-Cascade' => 'pass' }, message: 'Accept-Version header must be set.' ) end it 'fails with 406 Not Acceptable if header is empty' do expect do subject.call('HTTP_ACCEPT_VERSION' => '').last end.to throw_symbol( :error, status: 406, headers: { 'X-Cascade' => 'pass' }, message: 'Accept-Version header must be set.' ) end it 'succeeds if proper header is set' do expect(subject.call('HTTP_ACCEPT_VERSION' => 'v1').first).to eq(200) end end context 'when :strict and cascade: false' do before do @options[:versions] = ['v1'] @options[:version_options][:strict] = true @options[:version_options][:cascade] = false end it 'fails with 406 Not Acceptable if header is not set' do expect do subject.call({}).last end.to throw_symbol( :error, status: 406, headers: {}, message: 'Accept-Version header must be set.' ) end it 'fails with 406 Not Acceptable if header is empty' do expect do subject.call('HTTP_ACCEPT_VERSION' => '').last end.to throw_symbol( :error, status: 406, headers: {}, message: 'Accept-Version header must be set.' ) end it 'succeeds if proper header is set' do expect(subject.call('HTTP_ACCEPT_VERSION' => 'v1').first).to eq(200) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/dsl/routing_spec.rb
spec/grape/dsl/routing_spec.rb
# frozen_string_literal: true describe Grape::DSL::Routing do subject { dummy_class } let(:dummy_class) do Class.new do extend Grape::DSL::Routing extend Grape::DSL::Settings extend Grape::DSL::Validations class << self attr_reader :instance, :base attr_accessor :configuration end end end let(:proc) { -> {} } let(:options) { { a: :b } } let(:path) { '/dummy' } describe '.version' do it 'sets a version for route' do version = 'v1' expect(subject.version(version)).to eq(version) expect(subject.inheritable_setting.namespace_inheritable[:version]).to eq([version]) expect(subject.inheritable_setting.namespace_inheritable[:version_options]).to eq(using: :path) end end describe '.prefix' do it 'sets a prefix for route' do prefix = '/api' subject.prefix prefix expect(subject.inheritable_setting.namespace_inheritable[:root_prefix]).to eq(prefix) end end describe '.scope' do let(:root_app) do Class.new(Grape::API) do scope :my_scope do get :my_endpoint do return_no_content end end end end it 'create a scope without affecting the URL' do env = Rack::MockRequest.env_for('/my_endpoint', method: Rack::GET) response = Rack::MockResponse[*root_app.call(env)] expect(response).to be_no_content end end describe '.do_not_route_head!' do it 'sets do not route head option' do subject.do_not_route_head! expect(subject.inheritable_setting.namespace_inheritable[:do_not_route_head]).to be(true) end end describe '.do_not_route_options!' do it 'sets do not route options option' do subject.do_not_route_options! expect(subject.inheritable_setting.namespace_inheritable[:do_not_route_options]).to be(true) end end describe '.mount' do it 'mounts on a nested path' do subject = Class.new(Grape::API) app1 = Class.new(Grape::API) do get '/' do return_no_content end end app2 = Class.new(Grape::API) do get '/' do return_no_content end end subject.mount app1 => '/app1' app1.mount app2 => '/app2' env = Rack::MockRequest.env_for('/app1', method: Rack::GET) response = Rack::MockResponse[*subject.call(env)] expect(response).to be_no_content env = Rack::MockRequest.env_for('/app1/app2', method: Rack::GET) response = Rack::MockResponse[*subject.call(env)] expect(response).to be_no_content end it 'mounts multiple routes at once' do base_app = Class.new(Grape::API) app1 = Class.new(Grape::API) do get '/' do return_no_content end end app2 = Class.new(Grape::API) do get '/' do return_no_content end end base_app.mount(app1 => '/app1', app2 => '/app2') env = Rack::MockRequest.env_for('/app1', method: Rack::GET) response = Rack::MockResponse[*base_app.call(env)] expect(response).to be_no_content env = Rack::MockRequest.env_for('/app2', method: Rack::GET) response = Rack::MockResponse[*base_app.call(env)] expect(response).to be_no_content end end describe '.route' do before do allow(subject).to receive(:endpoints).and_return([]) allow(subject.inheritable_setting).to receive(:route_end) allow(subject).to receive(:reset_validations!) end it 'marks end of the route' do expect(subject.inheritable_setting).to receive(:route_end) subject.route(:any) end it 'resets validations' do expect(subject).to receive(:reset_validations!) subject.route(:any) end it 'defines a new endpoint' do expect { subject.route(:any) } .to change { subject.endpoints.count }.from(0).to(1) end it 'does not duplicate identical endpoints' do subject.route(:any) expect { subject.route(:any) } .not_to change(subject.endpoints, :count) end it 'generates correct endpoint options' do subject.inheritable_setting.route[:description] = { fiz: 'baz' } subject.inheritable_setting.namespace_stackable[:params] = { nuz: 'naz' } expect(Grape::Endpoint).to receive(:new) do |_inheritable_setting, endpoint_options| expect(endpoint_options[:method]).to eq :get expect(endpoint_options[:path]).to eq '/foo' expect(endpoint_options[:for]).to eq subject expect(endpoint_options[:route_options]).to eq(foo: 'bar', fiz: 'baz', params: { nuz: 'naz' }) end.and_yield subject.route(:get, '/foo', { foo: 'bar' }, &proc {}) end end describe '.get' do it 'delegates to .route' do expect(subject).to receive(:route).with(Rack::GET, path, options) subject.get path, **options, &proc end end describe '.post' do it 'delegates to .route' do expect(subject).to receive(:route).with(Rack::POST, path, options) subject.post path, **options, &proc end end describe '.put' do it 'delegates to .route' do expect(subject).to receive(:route).with(Rack::PUT, path, options) subject.put path, **options, &proc end end describe '.head' do it 'delegates to .route' do expect(subject).to receive(:route).with(Rack::HEAD, path, options) subject.head path, **options, &proc end end describe '.delete' do it 'delegates to .route' do expect(subject).to receive(:route).with(Rack::DELETE, path, options) subject.delete path, **options, &proc end end describe '.options' do it 'delegates to .route' do expect(subject).to receive(:route).with(Rack::OPTIONS, path, options) subject.options path, **options, &proc end end describe '.patch' do it 'delegates to .route' do expect(subject).to receive(:route).with(Rack::PATCH, path, options) subject.patch path, **options, &proc end end describe '.namespace' do it 'creates a new namespace with given name and options' do subject.namespace(:foo, foo: 'bar') {} expect(subject.namespace(:foo, foo: 'bar')).to eq(Grape::Namespace.new(:foo, foo: 'bar')) end it 'calls #joined_space_path on Namespace' do inside_namespace = nil subject.namespace(:foo, foo: 'bar') do inside_namespace = namespace end expect(inside_namespace).to eq('/foo') end end describe '.group' do it 'is alias to #namespace' do expect(subject.method(:group)).to eq subject.method(:namespace) end end describe '.resource' do it 'is alias to #namespace' do expect(subject.method(:resource)).to eq subject.method(:namespace) end end describe '.resources' do it 'is alias to #namespace' do expect(subject.method(:resources)).to eq subject.method(:namespace) end end describe '.segment' do it 'is alias to #namespace' do expect(subject.method(:segment)).to eq subject.method(:namespace) end end describe '.routes' do let(:main_app) { Class.new(Grape::API) } let(:first_app) { Class.new(Grape::API) } let(:second_app) { Class.new(Grape::API) } before do main_app.mount(first_app => '/first_app', second_app => '/second_app') end it 'returns flatten endpoints routes' do expect(main_app.endpoints).not_to be_empty expect(main_app.routes).to eq(main_app.endpoints.map(&:routes).flatten) end context 'when #routes was already called once' do it 'memoizes' do object_id = main_app.routes.object_id expect(main_app.routes.object_id).to eq(object_id) end end end describe '.route_param' do let!(:options) { { requirements: regex } } let(:regex) { /(.*)/ } it 'calls #namespace with given params' do expect(subject).to receive(:namespace).with(':foo', requirements: nil).and_yield subject.route_param('foo', &proc {}) end it 'nests requirements option under param name' do expect(subject).to receive(:namespace) do |_param, options| expect(options[:requirements][:foo]).to eq regex end subject.route_param('foo', **options, &proc {}) end it 'does not modify options parameter' do allow(subject).to receive(:namespace) expect { subject.route_param('foo', **options, &proc {}) } .not_to(change { options }) end end describe '.versions' do it 'returns last defined version' do subject.version 'v1' subject.version 'v2' expect(subject.version).to eq('v2') end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/dsl/desc_spec.rb
spec/grape/dsl/desc_spec.rb
# frozen_string_literal: true describe Grape::DSL::Desc do subject { dummy_class } let(:dummy_class) do Class.new do extend Grape::DSL::Desc extend Grape::DSL::Settings end end describe '.desc' do it 'sets a description' do desc_text = 'The description' options = { message: 'none' } subject.desc desc_text, options expect(subject.namespace_setting(:description)).to eq(options.merge(description: desc_text)) expect(subject.route_setting(:description)).to eq(options.merge(description: desc_text)) end it 'can be set with a block' do expected_options = { summary: 'summary', description: 'The description', detail: 'more details', params: { first: :param }, entity: Object, default: { code: 400, message: 'Invalid' }, http_codes: [[401, 'Unauthorized', 'Entities::Error']], named: 'My named route', body_name: 'My body name', headers: [ XAuthToken: { description: 'Valdates your identity', required: true }, XOptionalHeader: { description: 'Not really needed', required: false } ], hidden: false, deprecated: false, is_array: true, nickname: 'nickname', produces: %w[array of mime_types], consumes: %w[array of mime_types], tags: %w[tag1 tag2], security: %w[array of security schemes] } subject.desc 'The description' do summary 'summary' detail 'more details' params(first: :param) success Object default code: 400, message: 'Invalid' failure [[401, 'Unauthorized', 'Entities::Error']] named 'My named route' body_name 'My body name' headers [ XAuthToken: { description: 'Valdates your identity', required: true }, XOptionalHeader: { description: 'Not really needed', required: false } ] hidden false deprecated false is_array true nickname 'nickname' produces %w[array of mime_types] consumes %w[array of mime_types] tags %w[tag1 tag2] security %w[array of security schemes] end expect(subject.namespace_setting(:description)).to eq(expected_options) expect(subject.route_setting(:description)).to eq(expected_options) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/dsl/callbacks_spec.rb
spec/grape/dsl/callbacks_spec.rb
# frozen_string_literal: true describe Grape::DSL::Callbacks do subject { dummy_class } let(:dummy_class) do Class.new do extend Grape::DSL::Settings extend Grape::DSL::Callbacks end end let(:proc) { -> {} } describe '.before' do it 'adds a block to "before"' do subject.before(&proc) expect(subject.inheritable_setting.namespace_stackable[:befores]).to eq([proc]) end end describe '.before_validation' do it 'adds a block to "before_validation"' do subject.before_validation(&proc) expect(subject.inheritable_setting.namespace_stackable[:before_validations]).to eq([proc]) end end describe '.after_validation' do it 'adds a block to "after_validation"' do subject.after_validation(&proc) expect(subject.inheritable_setting.namespace_stackable[:after_validations]).to eq([proc]) end end describe '.after' do it 'adds a block to "after"' do subject.after(&proc) expect(subject.inheritable_setting.namespace_stackable[:afters]).to eq([proc]) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/dsl/parameters_spec.rb
spec/grape/dsl/parameters_spec.rb
# frozen_string_literal: true describe Grape::DSL::Parameters do subject { dummy_class.new } let(:dummy_class) do Class.new do include Grape::DSL::Parameters attr_accessor :api, :element, :parent def initialize @validate_attributes = [] end def validate_attributes(*args) @validate_attributes.push(*args) end def validate_attributes_reader @validate_attributes end def push_declared_params(args, _opts) @push_declared_params = args end def push_declared_params_reader @push_declared_params end def validates(*args) @validates = *args end def validates_reader @validates end def new_scope(args, _opts, _, &block) nested_scope = self.class.new nested_scope.new_group_scope(args, &block) nested_scope end def new_group_scope(args) prev_group = @group @group = args.clone.first yield @group = prev_group end def extract_message_option(attrs) return nil unless attrs.is_a?(Array) opts = attrs.last.is_a?(Hash) ? attrs.pop : {} opts.key?(:message) && !opts[:message].nil? ? opts.delete(:message) : nil end end end describe '#use' do before do allow_message_expectations_on_nil allow(subject.api).to receive(:namespace_stackable).with(:named_params) end let(:options) { { option: 'value' } } let(:named_params) { { params_group: proc {} } } it 'calls processes associated with named params' do subject.api = Class.new { include Grape::DSL::Settings }.new subject.api.inheritable_setting.namespace_stackable[:named_params] = named_params expect(subject).to receive(:instance_exec).with(options).and_yield subject.use :params_group, **options end it 'raises error when non-existent named param is called' do subject.api = Class.new { include Grape::DSL::Settings }.new expect { subject.use :params_group }.to raise_error('Params :params_group not found!') end end describe '#use_scope' do it 'is alias to #use' do expect(subject.method(:use_scope)).to eq subject.method(:use) end end describe '#includes' do it 'is alias to #use' do expect(subject.method(:includes)).to eq subject.method(:use) end end describe '#requires' do it 'adds a required parameter' do subject.requires :id, type: Integer, desc: 'Identity.' expect(subject.validate_attributes_reader).to eq([[:id], { type: Integer, desc: 'Identity.', presence: { value: true, message: nil } }]) expect(subject.push_declared_params_reader).to eq([:id]) end end describe '#optional' do it 'adds an optional parameter' do subject.optional :id, type: Integer, desc: 'Identity.' expect(subject.validate_attributes_reader).to eq([[:id], { type: Integer, desc: 'Identity.' }]) expect(subject.push_declared_params_reader).to eq([:id]) end end describe '#with' do it 'creates a scope with group attributes' do subject.with(type: Integer) { subject.optional :id, desc: 'Identity.' } expect(subject.validate_attributes_reader).to eq([[:id], { type: Integer, desc: 'Identity.' }]) expect(subject.push_declared_params_reader).to eq([:id]) end it 'merges the group attributes' do subject.with(documentation: { in: 'body' }) { subject.optional :vault, documentation: { default: 33 } } expect(subject.validate_attributes_reader).to eq([[:vault], { documentation: { in: 'body', default: 33 } }]) expect(subject.push_declared_params_reader).to eq([:vault]) end it 'overrides the group attribute when values not mergable' do subject.with(type: Integer, documentation: { in: 'body', default: 33 }) do subject.optional :vault subject.optional :allowed_vaults, type: [Integer], documentation: { default: [31, 32, 33], is_array: true } end expect(subject.validate_attributes_reader).to eq( [ [:vault], { type: Integer, documentation: { in: 'body', default: 33 } }, [:allowed_vaults], { type: [Integer], documentation: { in: 'body', default: [31, 32, 33], is_array: true } } ] ) end it 'allows a primitive type attribite to overwrite a complex type group attribute' do subject.with(documentation: { x: { nullable: true } }) do subject.optional :vault, type: Integer, documentation: { x: nil } end expect(subject.validate_attributes_reader).to eq( [ [:vault], { type: Integer, documentation: { x: nil } } ] ) end it 'does not nest primitives inside existing complex types erroneously' do subject.with(type: Hash, documentation: { default: { vault: '33' } }) do subject.optional :info subject.optional :role, type: String, documentation: { default: 'resident' } end expect(subject.validate_attributes_reader).to eq( [ [:info], { type: Hash, documentation: { default: { vault: '33' } } }, [:role], { type: String, documentation: { default: 'resident' } } ] ) end it 'merges deeply nested attributes' do subject.with(documentation: { details: { in: 'body', hidden: false } }) do subject.optional :vault, documentation: { details: { desc: 'The vault number' } } end expect(subject.validate_attributes_reader).to eq( [ [:vault], { documentation: { details: { in: 'body', hidden: false, desc: 'The vault number' } } } ] ) end it "supports nested 'with' calls" do subject.with(type: Integer, documentation: { in: 'body' }) do subject.optional :pipboy_id subject.with(documentation: { default: 33 }) do subject.optional :vault subject.with(type: String) do subject.with(documentation: { default: 'resident' }) do subject.optional :role end end subject.optional :age, documentation: { default: 42 } end end expect(subject.validate_attributes_reader).to eq( [ [:pipboy_id], { type: Integer, documentation: { in: 'body' } }, [:vault], { type: Integer, documentation: { in: 'body', default: 33 } }, [:role], { type: String, documentation: { in: 'body', default: 'resident' } }, [:age], { type: Integer, documentation: { in: 'body', default: 42 } } ] ) end it "supports Hash parameter inside the 'with' calls" do subject.with(documentation: { in: 'body' }) do subject.optional :info, type: Hash, documentation: { x: { nullable: true }, desc: 'The info' } do subject.optional :vault, type: Integer, documentation: { default: 33, desc: 'The vault number' } end end expect(subject.validate_attributes_reader).to eq( [ [:info], { type: Hash, documentation: { in: 'body', desc: 'The info', x: { nullable: true } } }, [:vault], { type: Integer, documentation: { in: 'body', default: 33, desc: 'The vault number' } } ] ) end end describe '#mutually_exclusive' do it 'adds an mutally exclusive parameter validation' do subject.mutually_exclusive :media, :audio expect(subject.validates_reader).to eq([%i[media audio], { mutually_exclusive: { value: true, message: nil } }]) end end describe '#exactly_one_of' do it 'adds an exactly of one parameter validation' do subject.exactly_one_of :media, :audio expect(subject.validates_reader).to eq([%i[media audio], { exactly_one_of: { value: true, message: nil } }]) end end describe '#at_least_one_of' do it 'adds an at least one of parameter validation' do subject.at_least_one_of :media, :audio expect(subject.validates_reader).to eq([%i[media audio], { at_least_one_of: { value: true, message: nil } }]) end end describe '#all_or_none_of' do it 'adds an all or none of parameter validation' do subject.all_or_none_of :media, :audio expect(subject.validates_reader).to eq([%i[media audio], { all_or_none_of: { value: true, message: nil } }]) end end describe '#group' do it 'is alias to #requires' do expect(subject.method(:group)).to eq subject.method(:requires) end end describe '#params' do it 'inherits params from parent' do parent_params = { foo: 'bar' } subject.parent = Object.new allow(subject.parent).to receive_messages(params: parent_params, params_meeting_dependency: nil) expect(subject.params({})).to eq parent_params end describe 'when params argument is an array of hashes' do it 'returns values of each hash for @element key' do subject.element = :foo expect(subject.params([{ foo: 'bar' }, { foo: 'baz' }])).to eq(%w[bar baz]) end end describe 'when params argument is a hash' do it 'returns value for @element key' do subject.element = :foo expect(subject.params(foo: 'bar')).to eq('bar') end end describe 'when params argument is not a array or a hash' do it 'returns empty hash' do subject.element = Object.new expect(subject.params(Object.new)).to eq({}) end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/dsl/request_response_spec.rb
spec/grape/dsl/request_response_spec.rb
# frozen_string_literal: true describe Grape::DSL::RequestResponse do subject { dummy_class } let(:dummy_class) do Class.new do extend Grape::DSL::RequestResponse extend Grape::DSL::Settings end end let(:c_type) { 'application/json' } let(:format) { 'txt' } describe '.default_format' do it 'sets the default format' do subject.default_format :format expect(subject.inheritable_setting.namespace_inheritable[:default_format]).to eq(:format) end it 'returns the format without paramter' do subject.default_format :format expect(subject.default_format).to eq :format end end describe '.format' do it 'sets a new format' do subject.format format expect(subject.inheritable_setting.namespace_inheritable[:format]).to eq(format.to_sym) expect(subject.inheritable_setting.namespace_inheritable[:default_error_formatter]).to eq(Grape::ErrorFormatter::Txt) end end describe '.formatter' do it 'sets the formatter for a content type' do subject.formatter c_type, :formatter expect(subject.inheritable_setting.namespace_stackable[:formatters]).to eq([c_type.to_sym => :formatter]) end end describe '.parser' do it 'sets a parser for a content type' do subject.parser c_type, :parser expect(subject.inheritable_setting.namespace_stackable[:parsers]).to eq([c_type.to_sym => :parser]) end end describe '.default_error_formatter' do it 'sets a new error formatter' do subject.default_error_formatter :json expect(subject.inheritable_setting.namespace_inheritable[:default_error_formatter]).to eq(Grape::ErrorFormatter::Json) end end describe '.error_formatter' do it 'sets a error_formatter' do format = 'txt' subject.error_formatter format, :error_formatter expect(subject.inheritable_setting.namespace_stackable[:error_formatters]).to eq([{ format.to_sym => :error_formatter }]) end it 'understands syntactic sugar' do subject.error_formatter format, with: :error_formatter expect(subject.inheritable_setting.namespace_stackable[:error_formatters]).to eq([{ format.to_sym => :error_formatter }]) end end describe '.content_type' do it 'sets a content type for a format' do subject.content_type format, c_type expect(subject.inheritable_setting.namespace_stackable[:content_types]).to eq([format.to_sym => c_type]) end end describe '.content_types' do it 'returns all content types' do expect(subject.content_types).to eq(xml: 'application/xml', serializable_hash: 'application/json', json: 'application/json', txt: 'text/plain', binary: 'application/octet-stream') end end describe '.default_error_status' do it 'sets a default error status' do subject.default_error_status 500 expect(subject.inheritable_setting.namespace_inheritable[:default_error_status]).to eq(500) end end describe '.rescue_from' do describe ':all' do it 'sets rescue all to true' do subject.rescue_from :all expect(subject.inheritable_setting.namespace_inheritable.to_hash).to eq( { rescue_all: true, all_rescue_handler: nil } ) end it 'sets given proc as rescue handler' do rescue_handler_proc = proc {} subject.rescue_from :all, rescue_handler_proc expect(subject.inheritable_setting.namespace_inheritable.to_hash).to eq( { rescue_all: true, all_rescue_handler: rescue_handler_proc } ) end it 'sets given block as rescue handler' do rescue_handler_proc = proc {} subject.rescue_from :all, &rescue_handler_proc expect(subject.inheritable_setting.namespace_inheritable.to_hash).to eq( { rescue_all: true, all_rescue_handler: rescue_handler_proc } ) end it 'sets a rescue handler declared through :with option' do with_block = -> { 'hello' } subject.rescue_from :all, with: with_block expect(subject.inheritable_setting.namespace_inheritable.to_hash).to eq( { rescue_all: true, all_rescue_handler: with_block } ) end it 'abort if :with option value is not Symbol, String or Proc' do expect { subject.rescue_from :all, with: 1234 }.to raise_error(ArgumentError, "with: #{integer_class_name}, expected Symbol, String or Proc") end it 'abort if both :with option and block are passed' do expect do subject.rescue_from :all, with: -> { 'hello' } do error!('bye') end end.to raise_error(ArgumentError, 'both :with option and block cannot be passed') end end describe ':grape_exceptions' do it 'sets rescue all to true' do subject.rescue_from :grape_exceptions expect(subject.inheritable_setting.namespace_inheritable.to_hash).to eq( { rescue_all: true, rescue_grape_exceptions: true, grape_exceptions_rescue_handler: nil } ) end it 'sets given proc as rescue handler' do rescue_handler_proc = proc {} subject.rescue_from :grape_exceptions, rescue_handler_proc expect(subject.inheritable_setting.namespace_inheritable.to_hash).to eq( { rescue_all: true, rescue_grape_exceptions: true, grape_exceptions_rescue_handler: rescue_handler_proc } ) end it 'sets given block as rescue handler' do rescue_handler_proc = proc {} subject.rescue_from :grape_exceptions, &rescue_handler_proc expect(subject.inheritable_setting.namespace_inheritable.to_hash).to eq( { rescue_all: true, rescue_grape_exceptions: true, grape_exceptions_rescue_handler: rescue_handler_proc } ) end it 'sets a rescue handler declared through :with option' do with_block = -> { 'hello' } subject.rescue_from :grape_exceptions, with: with_block expect(subject.inheritable_setting.namespace_inheritable.to_hash).to eq( { rescue_all: true, rescue_grape_exceptions: true, grape_exceptions_rescue_handler: with_block } ) end end describe 'list of exceptions is passed' do it 'sets hash of exceptions as rescue handlers' do subject.rescue_from StandardError expect(subject.inheritable_setting.namespace_reverse_stackable[:rescue_handlers]).to eq([StandardError => nil]) expect(subject.inheritable_setting.namespace_stackable[:rescue_options]).to eq([{}]) end it 'rescues only base handlers if rescue_subclasses: false option is passed' do subject.rescue_from StandardError, rescue_subclasses: false expect(subject.inheritable_setting.namespace_reverse_stackable[:base_only_rescue_handlers]).to eq([StandardError => nil]) expect(subject.inheritable_setting.namespace_stackable[:rescue_options]).to eq([rescue_subclasses: false]) end it 'sets given proc as rescue handler for each key in hash' do rescue_handler_proc = proc {} subject.rescue_from StandardError, rescue_handler_proc expect(subject.inheritable_setting.namespace_reverse_stackable[:rescue_handlers]).to eq([StandardError => rescue_handler_proc]) expect(subject.inheritable_setting.namespace_stackable[:rescue_options]).to eq([{}]) end it 'sets given block as rescue handler for each key in hash' do rescue_handler_proc = proc {} subject.rescue_from StandardError, &rescue_handler_proc expect(subject.inheritable_setting.namespace_reverse_stackable[:rescue_handlers]).to eq([StandardError => rescue_handler_proc]) expect(subject.inheritable_setting.namespace_stackable[:rescue_options]).to eq([{}]) end it 'sets a rescue handler declared through :with option for each key in hash' do with_block = -> { 'hello' } subject.rescue_from StandardError, with: with_block expect(subject.inheritable_setting.namespace_reverse_stackable[:rescue_handlers]).to eq([StandardError => with_block]) expect(subject.inheritable_setting.namespace_stackable[:rescue_options]).to eq([{}]) end end end describe '.represent' do it 'sets a presenter for a class' do presenter = Class.new subject.represent :ThisClass, with: presenter expect(subject.inheritable_setting.namespace_stackable[:representations]).to eq([ThisClass: presenter]) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/dsl/middleware_spec.rb
spec/grape/dsl/middleware_spec.rb
# frozen_string_literal: true describe Grape::DSL::Middleware do subject { dummy_class } let(:dummy_class) do Class.new do extend Grape::DSL::Middleware extend Grape::DSL::Settings end end let(:proc) { -> {} } let(:foo_middleware) { Class.new } let(:bar_middleware) { Class.new } describe '.use' do it 'adds a middleware with the right operation' do subject.use foo_middleware, :arg1, &proc expect(subject.inheritable_setting.namespace_stackable[:middleware]).to eq([[:use, foo_middleware, :arg1, proc]]) end end describe '.insert' do it 'adds a middleware with the right operation' do subject.insert 0, :arg1, &proc expect(subject.inheritable_setting.namespace_stackable[:middleware]).to eq([[:insert, 0, :arg1, proc]]) end end describe '.insert_before' do it 'adds a middleware with the right operation' do subject.insert_before foo_middleware, :arg1, &proc expect(subject.inheritable_setting.namespace_stackable[:middleware]).to eq([[:insert_before, foo_middleware, :arg1, proc]]) end end describe '.insert_after' do it 'adds a middleware with the right operation' do subject.insert_after foo_middleware, :arg1, &proc expect(subject.inheritable_setting.namespace_stackable[:middleware]).to eq([[:insert_after, foo_middleware, :arg1, proc]]) end end describe '.middleware' do it 'returns the middleware stack' do subject.use foo_middleware, :arg1, &proc subject.insert_before bar_middleware, :arg1, :arg2 expect(subject.middleware).to eq [[:use, foo_middleware, :arg1, proc], [:insert_before, bar_middleware, :arg1, :arg2]] end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/dsl/validations_spec.rb
spec/grape/dsl/validations_spec.rb
# frozen_string_literal: true describe Grape::DSL::Validations do subject { dummy_class } let(:dummy_class) do Class.new do extend Grape::DSL::Settings extend Grape::DSL::Validations end end describe '.params' do subject { dummy_class.params { :my_block } } it 'creates a proper Grape::Validations::ParamsScope' do expect(Grape::Validations::ParamsScope).to receive(:new).with(api: dummy_class, type: Hash) do |_func, &block| expect(block.call).to eq(:my_block) end.and_return(:param_scope) expect(subject).to eq(:param_scope) end end describe '.contract' do context 'when contract is nil and blockless' do it 'raises an ArgumentError' do expect { dummy_class.contract }.to raise_error(ArgumentError, 'Either contract or block must be provided') end end context 'when contract is nil and but a block is provided' do it 'returns a proper rape::Validations::ContractScope' do expect(Grape::Validations::ContractScope).to receive(:new).with(dummy_class, nil) do |_func, &block| expect(block.call).to eq(:my_block) end.and_return(:my_contract_scope) expect(dummy_class.contract { :my_block }).to eq(:my_contract_scope) end end context 'when contract is present and blockless' do subject { dummy_class.contract(:my_contract) } before do allow(Grape::Validations::ContractScope).to receive(:new).with(dummy_class, :my_contract).and_return(:my_contract_scope) end it { is_expected.to eq(:my_contract_scope) } end context 'when contract and block are provided' do context 'when contract does not respond to schema' do let(:my_contract) { Class.new } it 'returns a proper rape::Validations::ContractScope' do expect(Grape::Validations::ContractScope).to receive(:new).with(dummy_class, my_contract) do |_func, &block| expect(block.call).to eq(:my_block) end.and_return(:my_contract_scope) expect(dummy_class.contract(my_contract.new) { :my_block }).to eq(:my_contract_scope) end end context 'when contract responds to schema' do let(:my_contract) do Class.new do def schema; end end end it 'raises an ArgumentError' do expect { dummy_class.contract(my_contract.new) { :my_block } }.to raise_error(ArgumentError, 'Cannot inherit from contract, only schema') end end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/dsl/settings_spec.rb
spec/grape/dsl/settings_spec.rb
# frozen_string_literal: true describe Grape::DSL::Settings do subject { dummy_class.new } let(:dummy_class) do Class.new do include Grape::DSL::Settings def with_namespace(&block) within_namespace(&block) end def reset_validations!; end end end describe '#global_setting' do it 'sets a value globally' do subject.global_setting :some_thing, :foo_bar expect(subject.global_setting(:some_thing)).to eq :foo_bar subject.with_namespace do subject.global_setting :some_thing, :foo_bar_baz expect(subject.global_setting(:some_thing)).to eq :foo_bar_baz end expect(subject.global_setting(:some_thing)).to eq(:foo_bar_baz) end end describe '#route_setting' do it 'sets a value until the end of a namespace' do subject.with_namespace do subject.route_setting :some_thing, :foo_bar expect(subject.route_setting(:some_thing)).to eq :foo_bar end expect(subject.route_setting(:some_thing)).to be_nil end end describe '#namespace_setting' do it 'sets a value until the end of a namespace' do subject.with_namespace do subject.namespace_setting :some_thing, :foo_bar expect(subject.namespace_setting(:some_thing)).to eq :foo_bar end expect(subject.namespace_setting(:some_thing)).to be_nil end it 'resets values after leaving nested namespaces' do subject.with_namespace do subject.namespace_setting :some_thing, :foo_bar expect(subject.namespace_setting(:some_thing)).to eq :foo_bar subject.with_namespace do expect(subject.namespace_setting(:some_thing)).to be_nil end expect(subject.namespace_setting(:some_thing)).to eq :foo_bar end expect(subject.namespace_setting(:some_thing)).to be_nil end end describe '#namespace_inheritable' do it 'inherits values from surrounding namespace' do subject.with_namespace do subject.inheritable_setting.namespace_inheritable[:some_thing] = :foo_bar expect(subject.inheritable_setting.namespace_inheritable[:some_thing]).to eq :foo_bar subject.with_namespace do expect(subject.inheritable_setting.namespace_inheritable[:some_thing]).to eq :foo_bar subject.inheritable_setting.namespace_inheritable[:some_thing] = :foo_bar_2 expect(subject.inheritable_setting.namespace_inheritable[:some_thing]).to eq :foo_bar_2 end expect(subject.inheritable_setting.namespace_inheritable[:some_thing]).to eq :foo_bar end end end describe '#namespace_stackable' do it 'stacks values from surrounding namespace' do subject.with_namespace do subject.inheritable_setting.namespace_stackable[:some_thing] = :foo_bar expect(subject.inheritable_setting.namespace_stackable[:some_thing]).to eq [:foo_bar] subject.with_namespace do subject.inheritable_setting.namespace_stackable[:some_thing] = :foo_bar_2 expect(subject.inheritable_setting.namespace_stackable[:some_thing]).to eq %i[foo_bar foo_bar_2] end expect(subject.inheritable_setting.namespace_stackable[:some_thing]).to eq [:foo_bar] end end end describe 'complex scenario' do it 'plays well' do obj1 = dummy_class.new obj2 = dummy_class.new obj3 = dummy_class.new obj1_copy = nil obj2_copy = nil obj3_copy = nil obj1.with_namespace do obj1.inheritable_setting.namespace_stackable[:some_thing] = :obj1 expect(obj1.inheritable_setting.namespace_stackable[:some_thing]).to eq [:obj1] obj1_copy = obj1.inheritable_setting.point_in_time_copy end expect(obj1.inheritable_setting.namespace_stackable[:some_thing]).to eq [] expect(obj1_copy.namespace_stackable[:some_thing]).to eq [:obj1] obj2.with_namespace do obj2.inheritable_setting.namespace_stackable[:some_thing] = :obj2 expect(obj2.inheritable_setting.namespace_stackable[:some_thing]).to eq [:obj2] obj2_copy = obj2.inheritable_setting.point_in_time_copy end expect(obj2.inheritable_setting.namespace_stackable[:some_thing]).to eq [] expect(obj2_copy.namespace_stackable[:some_thing]).to eq [:obj2] obj3.with_namespace do obj3.inheritable_setting.namespace_stackable[:some_thing] = :obj3 expect(obj3.inheritable_setting.namespace_stackable[:some_thing]).to eq [:obj3] obj3_copy = obj3.inheritable_setting.point_in_time_copy end expect(obj3.inheritable_setting.namespace_stackable[:some_thing]).to eq [] expect(obj3_copy.namespace_stackable[:some_thing]).to eq [:obj3] # obj1.top_level_setting.inherit_from obj2_copy.point_in_time_copy # obj2.top_level_setting.inherit_from obj3_copy.point_in_time_copy # expect(obj1_copy.namespace_stackable[:some_thing]).to eq %i[obj3 obj2 obj1] end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/dsl/headers_spec.rb
spec/grape/dsl/headers_spec.rb
# frozen_string_literal: true describe Grape::DSL::Headers do subject { dummy_class.new } let(:dummy_class) do Class.new do include Grape::DSL::Headers end end let(:header_data) do { 'first key' => 'First Value', 'second key' => 'Second Value' } end context 'when headers are set' do describe '#header' do before do header_data.each { |k, v| subject.header(k, v) } end describe 'get' do it 'returns a specifc value' do expect(subject.header['first key']).to eq 'First Value' expect(subject.header['second key']).to eq 'Second Value' end it 'returns all set headers' do expect(subject.header).to eq header_data expect(subject.headers).to eq header_data end end describe 'set' do it 'returns value' do expect(subject.header('third key', 'Third Value')) expect(subject.header['third key']).to eq 'Third Value' end end describe 'delete' do it 'deletes a header key-value pair' do expect(subject.header('first key')).to eq header_data['first key'] expect(subject.header).not_to have_key('first key') end end end end context 'when no headers are set' do describe '#header' do it 'returns nil' do expect(subject.header['first key']).to be_nil expect(subject.header('first key')).to be_nil end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/dsl/logger_spec.rb
spec/grape/dsl/logger_spec.rb
# frozen_string_literal: true describe Grape::DSL::Logger do let(:dummy_logger) do Class.new do extend Grape::DSL::Logger extend Grape::DSL::Settings end end describe '.logger' do context 'when setting a logger' do subject { dummy_logger.logger :my_logger } it { is_expected.to eq(:my_logger) } end context 'when retrieving logger' do context 'when never been set' do subject { dummy_logger.logger } before { allow(Logger).to receive(:new).with($stdout).and_return(:stdout_logger) } it { is_expected.to eq(:stdout_logger) } end context 'when already set' do subject { dummy_logger.logger } before { dummy_logger.logger :my_logger } it { is_expected.to eq(:my_logger) } end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/dsl/inside_route_spec.rb
spec/grape/dsl/inside_route_spec.rb
# frozen_string_literal: true describe Grape::DSL::InsideRoute do subject { dummy_class.new } let(:dummy_class) do Class.new do include Grape::DSL::InsideRoute include Grape::DSL::Settings attr_reader :env, :request, :new_settings def initialize @env = {} @header = {} @new_settings = { namespace_inheritable: inheritable_setting.namespace_inheritable, namespace_stackable: inheritable_setting.namespace_stackable } end def header(key = nil, val = nil) if key val ? header[key] = val : header.delete(key) else @header ||= Grape::Util::Header.new end end end end describe '#version' do it 'defaults to nil' do expect(subject.version).to be_nil end it 'returns env[api.version]' do subject.env[Grape::Env::API_VERSION] = 'dummy' expect(subject.version).to eq 'dummy' end end describe '#error!' do it 'throws :error' do expect { subject.error! 'Not Found', 404 }.to throw_symbol(:error) end describe 'thrown' do before do catch(:error) { subject.error! 'Not Found', 404 } end it 'sets status' do expect(subject.status).to eq 404 end end describe 'default_error_status' do before do subject.inheritable_setting.namespace_inheritable[:default_error_status] = 500 catch(:error) { subject.error! 'Unknown' } end it 'sets status to default_error_status' do expect(subject.status).to eq 500 end end # self.status(status || settings[:default_error_status]) # throw :error, message: message, status: self.status, headers: headers end describe '#redirect' do describe 'default' do before do subject.redirect '/' end it 'sets status to 302' do expect(subject.status).to eq 302 end it 'sets location header' do expect(subject.header['Location']).to eq '/' end end describe 'permanent' do before do subject.redirect '/', permanent: true end it 'sets status to 301' do expect(subject.status).to eq 301 end it 'sets location header' do expect(subject.header['Location']).to eq '/' end end end describe '#status' do %w[GET PUT OPTIONS].each do |method| it 'defaults to 200 on GET' do request = Grape::Request.new(Rack::MockRequest.env_for('/', method: method)) expect(subject).to receive(:request).and_return(request).twice expect(subject.status).to eq 200 end end it 'defaults to 201 on POST' do request = Grape::Request.new(Rack::MockRequest.env_for('/', method: Rack::POST)) expect(subject).to receive(:request).and_return(request) expect(subject.status).to eq 201 end it 'defaults to 204 on DELETE' do request = Grape::Request.new(Rack::MockRequest.env_for('/', method: Rack::DELETE)) expect(subject).to receive(:request).and_return(request).twice expect(subject.status).to eq 204 end it 'defaults to 200 on DELETE with a body present' do request = Grape::Request.new(Rack::MockRequest.env_for('/', method: Rack::DELETE)) subject.body 'content here' expect(subject).to receive(:request).and_return(request).twice expect(subject.status).to eq 200 end it 'returns status set' do subject.status 501 expect(subject.status).to eq 501 end it 'accepts symbol for status' do subject.status :see_other expect(subject.status).to eq 303 end it 'raises error if unknow symbol is passed' do expect { subject.status :foo_bar } .to raise_error(ArgumentError, 'Status code :foo_bar is invalid.') end it 'accepts unknown Integer status codes' do expect { subject.status 210 }.not_to raise_error end it 'raises error if status is not a integer or symbol' do expect { subject.status Object.new } .to raise_error(ArgumentError, 'Status code must be Integer or Symbol.') end end describe '#return_no_content' do it 'sets the status code and body' do subject.return_no_content expect(subject.status).to eq 204 expect(subject.body).to eq '' end end describe '#content_type' do describe 'set' do before do subject.content_type 'text/plain' end it 'returns value' do expect(subject.content_type).to eq 'text/plain' end end it 'returns default' do expect(subject.content_type).to be_nil end end describe '#body' do describe 'set' do before do subject.body 'body' end it 'returns value' do expect(subject.body).to eq 'body' end end describe 'false' do before do subject.body false end it 'sets status to 204' do expect(subject.body).to eq '' expect(subject.status).to eq 204 end end it 'returns default' do expect(subject.body).to be_nil end end describe '#sendfile' do describe 'set' do context 'as file path' do let(:file_path) { '/some/file/path' } let(:file_response) do file_body = Grape::ServeStream::FileBody.new(file_path) Grape::ServeStream::StreamResponse.new(file_body) end before do subject.header Rack::CACHE_CONTROL, 'cache' subject.header Rack::CONTENT_LENGTH, 123 subject.header 'Transfer-Encoding', 'base64' subject.sendfile file_path end it 'returns value wrapped in StreamResponse' do expect(subject.sendfile).to eq file_response end it 'set the correct headers' do expect(subject.header).to match( Rack::CACHE_CONTROL => 'cache', Rack::CONTENT_LENGTH => 123, 'Transfer-Encoding' => 'base64' ) end end context 'as object' do let(:file_object) { double('StreamerObject', each: nil) } it 'raises an error that only a file path is supported' do expect { subject.sendfile file_object }.to raise_error(ArgumentError, /Argument must be a file path/) end end end it 'returns default' do expect(subject.sendfile).to be_nil end end describe '#stream' do describe 'set' do context 'as a file path' do let(:file_path) { '/some/file/path' } let(:file_response) do file_body = Grape::ServeStream::FileBody.new(file_path) Grape::ServeStream::StreamResponse.new(file_body) end before do subject.header Rack::CACHE_CONTROL, 'cache' subject.header Rack::CONTENT_LENGTH, 123 subject.header 'Transfer-Encoding', 'base64' subject.stream file_path end it 'returns file body wrapped in StreamResponse' do expect(subject.stream).to eq file_response end it 'sets only the cache-control header' do expect(subject.header).to match(Rack::CACHE_CONTROL => 'no-cache') end end context 'as a stream object' do let(:stream_object) { double('StreamerObject', each: nil) } let(:stream_response) do Grape::ServeStream::StreamResponse.new(stream_object) end before do subject.header Rack::CACHE_CONTROL, 'cache' subject.header Rack::CONTENT_LENGTH, 123 subject.header 'Transfer-Encoding', 'base64' subject.stream stream_object end it 'returns value wrapped in StreamResponse' do expect(subject.stream).to eq stream_response end it 'set only the cache-control header' do expect(subject.header).to match(Rack::CACHE_CONTROL => 'no-cache') end end context 'as a non-stream object' do let(:non_stream_object) { double('NonStreamerObject') } it 'raises an error that the object must implement :each' do expect { subject.stream non_stream_object }.to raise_error(ArgumentError, /:each/) end end end it 'returns default' do expect(subject.stream).to be_nil expect(subject.header).to be_empty end end describe '#route' do before do subject.env[Grape::Env::GRAPE_ROUTING_ARGS] = {} subject.env[Grape::Env::GRAPE_ROUTING_ARGS][:route_info] = 'dummy' end it 'returns route_info' do expect(subject.route).to eq 'dummy' end end describe '#present' do # see entity_spec.rb for entity representation spec coverage describe 'dummy' do before do subject.present 'dummy' end it 'presents dummy object' do expect(subject.body).to eq 'dummy' end end describe 'with' do describe 'entity' do let(:entity_mock) do entity_mock = Object.new allow(entity_mock).to receive(:represent).and_return('dummy') entity_mock end describe 'instance' do before do subject.present 'dummy', with: entity_mock end it 'presents dummy object' do expect(subject.body).to eq 'dummy' end end end end describe 'multiple entities' do let(:entity_mock_one) do entity_mock_one = Object.new allow(entity_mock_one).to receive(:represent).and_return(dummy1: 'dummy1') entity_mock_one end let(:entity_mock_two) do entity_mock_two = Object.new allow(entity_mock_two).to receive(:represent).and_return(dummy2: 'dummy2') entity_mock_two end describe 'instance' do before do subject.present 'dummy1', with: entity_mock_one subject.present 'dummy2', with: entity_mock_two end it 'presents both dummy objects' do expect(subject.body[:dummy1]).to eq 'dummy1' expect(subject.body[:dummy2]).to eq 'dummy2' end end end describe 'non mergeable entity' do let(:entity_mock_one) do entity_mock_one = Object.new allow(entity_mock_one).to receive(:represent).and_return(dummy1: 'dummy1') entity_mock_one end let(:entity_mock_two) do entity_mock_two = Object.new allow(entity_mock_two).to receive(:represent).and_return('not a hash') entity_mock_two end describe 'instance' do it 'fails' do subject.present 'dummy1', with: entity_mock_one expect do subject.present 'dummy2', with: entity_mock_two end.to raise_error ArgumentError, 'Representation of type String cannot be merged.' end end end end describe '#declared' do let(:dummy_class) do Class.new do include Grape::DSL::Declared attr_reader :before_filter_passed def initialize @before_filter_passed = false end end end it 'is not available by default' do expect { subject.declared({}) }.to raise_error( Grape::DSL::InsideRoute::MethodNotYetAvailable ) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/dsl/helpers_spec.rb
spec/grape/dsl/helpers_spec.rb
# frozen_string_literal: true describe Grape::DSL::Helpers do subject { dummy_class } let(:dummy_class) do Class.new do extend Grape::DSL::Helpers extend Grape::DSL::Settings def self.mods inheritable_setting.namespace_stackable[:helpers] end def self.first_mod mods.first end end end let(:proc) do lambda do |*| def test :test end end end describe '.helpers' do it 'adds a module with the given block' do subject.helpers(&proc) expect(subject.first_mod.instance_methods).to include(:test) end it 'uses provided modules' do mod = Module.new subject.helpers(mod, &proc) expect(subject.first_mod).to eq mod end it 'uses many provided modules' do mod = Module.new mod2 = Module.new mod3 = Module.new subject.helpers(mod, mod2, mod3, &proc) expect(subject.mods).to include(mod, mod2, mod3) end context 'with an external file' do let(:boolean_helper) do Module.new do extend Grape::API::Helpers params :requires_toggle_prm do requires :toggle_prm, type: Boolean end end end it 'sets Boolean as a Grape::API::Boolean' do subject.helpers boolean_helper expect(subject.first_mod::Boolean).to eq Grape::API::Boolean end end context 'in child classes' do let(:base_class) do Class.new(Grape::API) do helpers do params :requires_toggle_prm do requires :toggle_prm, type: Integer end end end end let(:api_class) do Class.new(base_class) do params do use :requires_toggle_prm end end end it 'is available' do expect { api_class }.not_to raise_exception end end context 'public scope' do it 'returns helpers only' do expect(Class.new { extend Grape::DSL::Helpers }.singleton_methods - Class.methods).to contain_exactly(:helpers) end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/mount_and_helpers_order_spec.rb
spec/grape/api/mount_and_helpers_order_spec.rb
# frozen_string_literal: true describe Grape::API do describe 'rescue_from' do context 'when the API is mounted AFTER defining the class rescue_from handler' do let(:api_rescue_from) do Class.new(Grape::API) do rescue_from :all do error!({ type: 'all' }, 404) end get do { count: 1 / 0 } end end end let(:main_rescue_from_after) do context = self Class.new(Grape::API) do rescue_from ZeroDivisionError do error!({ type: 'zero' }, 500) end mount context.api_rescue_from end end def app main_rescue_from_after end it 'is rescued by the rescue_from ZeroDivisionError handler from Main class' do get '/' expect(last_response.status).to eq(500) expect(last_response.body).to eq({ type: 'zero' }.to_json) end end context 'when the API is mounted BEFORE defining the class rescue_from handler' do let(:api_rescue_from) do Class.new(Grape::API) do rescue_from :all do error!({ type: 'all' }, 404) end get do { count: 1 / 0 } end end end let(:main_rescue_from_before) do context = self Class.new(Grape::API) do mount context.api_rescue_from rescue_from ZeroDivisionError do error!({ type: 'zero' }, 500) end end end def app main_rescue_from_before end it 'is rescued by the rescue_from ZeroDivisionError handler from Main class' do get '/' expect(last_response.status).to eq(500) expect(last_response.body).to eq({ type: 'zero' }.to_json) end end end describe 'before' do context 'when the API is mounted AFTER defining the before helper' do let(:api_before_handler) do Class.new(Grape::API) do get do { count: @count }.to_json end end end let(:main_before_handler_after) do context = self Class.new(Grape::API) do before do @count = 1 end mount context.api_before_handler end end def app main_before_handler_after end it 'is able to access the variables defined in the before helper' do get '/' expect(last_response.status).to eq(200) expect(last_response.body).to eq({ count: 1 }.to_json) end end context 'when the API is mounted BEFORE defining the before helper' do let(:api_before_handler) do Class.new(Grape::API) do get do { count: @count }.to_json end end end let(:main_before_handler_before) do context = self Class.new(Grape::API) do mount context.api_before_handler before do @count = 1 end end end def app main_before_handler_before end it 'is able to access the variables defined in the before helper' do get '/' expect(last_response.status).to eq(200) expect(last_response.body).to eq({ count: 1 }.to_json) end end end describe 'after' do context 'when the API is mounted AFTER defining the after handler' do let(:api_after_handler) do Class.new(Grape::API) do get do { count: 1 }.to_json end end end let(:main_after_handler_after) do context = self Class.new(Grape::API) do after do error!({ type: 'after' }, 500) end mount context.api_after_handler end end def app main_after_handler_after end it 'is able to access the variables defined in the after helper' do get '/' expect(last_response.status).to eq(500) expect(last_response.body).to eq({ type: 'after' }.to_json) end end context 'when the API is mounted BEFORE defining the after helper' do let(:api_after_handler) do Class.new(Grape::API) do get do { count: 1 }.to_json end end end let(:main_after_handler_before) do context = self Class.new(Grape::API) do mount context.api_after_handler after do error!({ type: 'after' }, 500) end end end def app main_after_handler_before end it 'is able to access the variables defined in the after helper' do get '/' expect(last_response.status).to eq(500) expect(last_response.body).to eq({ type: 'after' }.to_json) end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/shared_helpers_exactly_one_of_spec.rb
spec/grape/api/shared_helpers_exactly_one_of_spec.rb
# frozen_string_literal: true describe Grape::API::Helpers do let(:app) do Class.new(Grape::API) do helpers Module.new do extend Grape::API::Helpers params :drink do optional :beer optional :wine exactly_one_of :beer, :wine end end format :json params do requires :orderType, type: String, values: %w[food drink] given orderType: ->(val) { val == 'food' } do optional :pasta optional :pizza exactly_one_of :pasta, :pizza end given orderType: ->(val) { val == 'drink' } do use :drink end end get do declared(params, include_missing: true) end end end it 'defines parameters' do get '/', orderType: 'food', pizza: 'mista' expect(last_response.status).to eq 200 expect(last_response.body).to eq({ orderType: 'food', pasta: nil, pizza: 'mista', beer: nil, wine: nil }.to_json) end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/inherited_helpers_spec.rb
spec/grape/api/inherited_helpers_spec.rb
# frozen_string_literal: true describe Grape::API::Helpers do let(:user) { 'Miguel Caneo' } let(:id) { '42' } let(:api_super_class) do Class.new(Grape::API) do helpers do params(:superclass_params) { requires :id, type: String } def current_user params[:user] end end end end let(:api_overridden_sub_class) do Class.new(api_super_class) do params { use :superclass_params } helpers do def current_user "#{params[:user]} with id" end end get 'resource' do "#{current_user}: #{params['id']}" end end end let(:api_sub_class) do Class.new(api_super_class) do params { use :superclass_params } get 'resource' do "#{current_user}: #{params['id']}" end end end let(:api_example) do Class.new(api_sub_class) do params { use :superclass_params } get 'resource' do "#{current_user}: #{params['id']}" end end end context 'non overriding subclass' do subject { api_sub_class } def app subject end context 'given expected params' do it 'inherits helpers from a superclass' do get '/resource', id: id, user: user expect(last_response.body).to eq("#{user}: #{id}") end end context 'with lack of expected params' do it 'returns missing error' do get '/resource' expect(last_response.body).to eq('id is missing') end end end context 'overriding subclass' do def app api_overridden_sub_class end context 'given expected params' do it 'overrides helpers from a superclass' do get '/resource', id: id, user: user expect(last_response.body).to eq("#{user} with id: #{id}") end end context 'with lack of expected params' do it 'returns missing error' do get '/resource' expect(last_response.body).to eq('id is missing') end end end context 'example subclass' do def app api_example end context 'given expected params' do it 'inherits helpers from a superclass' do get '/resource', id: id, user: user expect(last_response.body).to eq("#{user}: #{id}") end end context 'with lack of expected params' do it 'returns missing error' do get '/resource' expect(last_response.body).to eq('id is missing') end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/required_parameters_with_invalid_method_spec.rb
spec/grape/api/required_parameters_with_invalid_method_spec.rb
# frozen_string_literal: true describe Grape::Endpoint do subject { Class.new(Grape::API) } def app subject end before do subject.namespace do params do requires :id, desc: 'Identifier.' end get ':id' do end end end context 'post' do it '405' do post '/something' expect(last_response.status).to eq 405 end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/namespace_parameters_in_route_spec.rb
spec/grape/api/namespace_parameters_in_route_spec.rb
# frozen_string_literal: true describe Grape::Endpoint do subject { Class.new(Grape::API) } def app subject end before do subject.namespace :me do namespace :pending do get '/' do 'banana' end end put ':id' do params[:id] end end end context 'get' do it 'responds without ext' do get '/me/pending' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'banana' end end context 'put' do it 'responds' do put '/me/foo' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'foo' end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/mount_and_rescue_from_spec.rb
spec/grape/api/mount_and_rescue_from_spec.rb
# frozen_string_literal: true describe Grape::API do context 'when multiple classes defines the same rescue_from' do let(:an_api) do Class.new(Grape::API) do rescue_from ZeroDivisionError do error!({ type: 'an-api-zero' }, 404) end get '/an-api' do { count: 1 / 0 } end end end let(:another_api) do Class.new(Grape::API) do rescue_from ZeroDivisionError do error!({ type: 'another-api-zero' }, 322) end get '/another-api' do { count: 1 / 0 } end end end let(:other_main) do context = self Class.new(Grape::API) do mount context.an_api mount context.another_api end end def app other_main end it 'is rescued by the rescue_from ZeroDivisionError handler defined inside each of the classes' do get '/an-api' expect(last_response.status).to eq(404) expect(last_response.body).to eq({ type: 'an-api-zero' }.to_json) get '/another-api' expect(last_response.status).to eq(322) expect(last_response.body).to eq({ type: 'another-api-zero' }.to_json) end context 'when some class does not define a rescue_from but it was defined in a previous mounted endpoint' do let(:an_api_without_defined_rescue_from) do Class.new(Grape::API) do get '/another-api-without-defined-rescue-from' do { count: 1 / 0 } end end end let(:other_main_with_not_defined_rescue_from) do context = self Class.new(Grape::API) do mount context.an_api mount context.another_api mount context.an_api_without_defined_rescue_from end end def app other_main_with_not_defined_rescue_from end it 'is not rescued by any of the previous defined rescue_from ZeroDivisionError handlers' do get '/an-api' expect(last_response.status).to eq(404) expect(last_response.body).to eq({ type: 'an-api-zero' }.to_json) get '/another-api' expect(last_response.status).to eq(322) expect(last_response.body).to eq({ type: 'another-api-zero' }.to_json) expect do get '/another-api-without-defined-rescue-from' end.to raise_error(ZeroDivisionError) end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/parameters_modification_spec.rb
spec/grape/api/parameters_modification_spec.rb
# frozen_string_literal: true describe Grape::Endpoint do subject { Class.new(Grape::API) } def app subject end before do subject.namespace :test do params do optional :foo, default: +'-abcdef' end get do params[:foo].slice!(0) params[:foo] end end end context 'when route modifies param value' do it 'param default should not change' do get '/test' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'abcdef' get '/test' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'abcdef' get '/test?foo=-123456' expect(last_response.status).to eq 200 expect(last_response.body).to eq '123456' get '/test' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'abcdef' end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/patch_method_helpers_spec.rb
spec/grape/api/patch_method_helpers_spec.rb
# frozen_string_literal: true describe Grape::API::Helpers do let(:patch_public) do Class.new(Grape::API) do format :json version 'public-v1', using: :header, vendor: 'grape' get do { ok: 'public' } end end end let(:auth_methods) do Module.new do def authenticate!; end end end let(:patch_private) do context = self Class.new(Grape::API) do format :json version 'private-v1', using: :header, vendor: 'grape' helpers context.auth_methods before do authenticate! end get do { ok: 'private' } end end end let(:main) do context = self Class.new(Grape::API) do mount context.patch_public mount context.patch_private end end def app main end context 'patch' do it 'public' do patch '/', {}, 'HTTP_ACCEPT' => 'application/vnd.grape-public-v1+json' expect(last_response.status).to eq 405 end it 'private' do patch '/', {}, 'HTTP_ACCEPT' => 'application/vnd.grape-private-v1+json' expect(last_response.status).to eq 405 end it 'default' do patch '/' expect(last_response.status).to eq 405 end end context 'default' do it 'public' do get '/', {}, 'HTTP_ACCEPT' => 'application/vnd.grape-public-v1+json' expect(last_response.status).to eq 200 expect(last_response.body).to eq({ ok: 'public' }.to_json) end it 'private' do get '/', {}, 'HTTP_ACCEPT' => 'application/vnd.grape-private-v1+json' expect(last_response.status).to eq 200 expect(last_response.body).to eq({ ok: 'private' }.to_json) end it 'default' do get '/' expect(last_response.status).to eq 200 expect(last_response.body).to eq({ ok: 'public' }.to_json) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/documentation_spec.rb
spec/grape/api/documentation_spec.rb
# frozen_string_literal: true describe Grape::API do subject { Class.new(described_class) } let(:app) { subject } context 'an endpoint with documentation' do it 'documents parameters' do subject.params do requires 'price', type: Float, desc: 'Sales price' end subject.get '/' expect(subject.routes.first.params['price']).to eq(required: true, type: 'Float', desc: 'Sales price') end it 'allows documentation with a hash' do documentation = { example: 'Joe' } subject.params do requires 'first_name', documentation: documentation end subject.get '/' expect(subject.routes.first.params['first_name'][:documentation]).to eq(documentation) end end context 'an endpoint without documentation' do before do subject.do_not_document! subject.params do requires :city, type: String, desc: 'Should be ignored' optional :postal_code, type: Integer end subject.post '/' do declared(params).to_json end end it 'does not document parameters for the endpoint' do expect(subject.routes.first.params).to eq({}) end it 'still declares params internally' do data = { city: 'Berlin', postal_code: 10_115 } post '/', data expect(last_response.body).to eq(data.to_json) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/optional_parameters_in_route_spec.rb
spec/grape/api/optional_parameters_in_route_spec.rb
# frozen_string_literal: true describe Grape::Endpoint do subject { Class.new(Grape::API) } def app subject end before do subject.namespace :api do get ':id(/:ext)' do [params[:id], params[:ext]].compact.join('/') end put ':id' do params[:id] end end end context 'get' do it 'responds without ext' do get '/api/foo' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'foo' end it 'responds with ext' do get '/api/foo/bar' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'foo/bar' end end context 'put' do it 'responds' do put '/api/foo' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'foo' end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/nested_helpers_spec.rb
spec/grape/api/nested_helpers_spec.rb
# frozen_string_literal: true describe Grape::API::Helpers do let(:helper_methods) do Module.new do extend Grape::API::Helpers def current_user @current_user ||= params[:current_user] end end end let(:nested) do context = self Class.new(Grape::API) do resource :level1 do helpers context.helper_methods get do current_user end resource :level2 do get do current_user end end end end end let(:main) do context = self Class.new(Grape::API) do mount context.nested end end def app main end it 'can access helpers from a mounted resource' do get '/level1', current_user: 'hello' expect(last_response.body).to eq('hello') end it 'can access helpers from a mounted resource in a nested resource' do get '/level1/level2', current_user: 'world' expect(last_response.body).to eq('world') end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/recognize_path_spec.rb
spec/grape/api/recognize_path_spec.rb
# frozen_string_literal: true describe Grape::API do describe '.recognize_path' do subject { Class.new(described_class) } it 'fetches endpoint by given path' do subject.get('/foo/:id') {} subject.get('/bar/:id') {} subject.get('/baz/:id') {} actual = subject.recognize_path('/bar/1234').routes[0].origin expect(actual).to eq('/bar/:id') end it 'returns nil if given path does not match with registered routes' do subject.get {} expect(subject.recognize_path('/bar/1234')).to be_nil end context 'when parametrized route with type specified together with a static route' do subject do Class.new(described_class) do resource :books do route_param :id, type: Integer do get do end resource :loans do route_param :loan_id, type: Integer do get do end end resource :print do post do end end end end resource :share do post do end end end end end it 'recognizes the static route when the parameter does not match with the specified type' do actual = subject.recognize_path('/books/share').routes[0].origin expect(actual).to eq('/books/share') end it 'does not recognize any endpoint when there is not other endpoint that matches with the requested path' do actual = subject.recognize_path('/books/other') expect(actual).to be_nil end it 'recognizes the parametrized route when the parameter matches with the specified type' do actual = subject.recognize_path('/books/1').routes[0].origin expect(actual).to eq('/books/:id') end it 'recognizes the static nested route when the parameter does not match with the specified type' do actual = subject.recognize_path('/books/1/loans/print').routes[0].origin expect(actual).to eq('/books/:id/loans/print') end it 'recognizes the nested parametrized route when the parameter matches with the specified type' do actual = subject.recognize_path('/books/1/loans/33').routes[0].origin expect(actual).to eq('/books/:id/loans/:loan_id') end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/required_parameters_in_route_spec.rb
spec/grape/api/required_parameters_in_route_spec.rb
# frozen_string_literal: true describe Grape::Endpoint do subject { Class.new(Grape::API) } def app subject end before do subject.namespace :api do get ':id' do [params[:id], params[:ext]].compact.join('/') end put ':something_id' do params[:something_id] end end end context 'get' do it 'responds' do get '/api/foo' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'foo' end end context 'put' do it 'responds' do put '/api/foo' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'foo' end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/mounted_helpers_inheritance_spec.rb
spec/grape/api/mounted_helpers_inheritance_spec.rb
# frozen_string_literal: true describe Grape::API do context 'when mounting a child API that inherits helpers from parent API' do let(:child_api) do Class.new(Grape::API) do get '/test' do parent_helper end end end let(:parent_api) do context = self Class.new(Grape::API) do helpers do def parent_helper 'parent helper value' end end mount context.child_api end end def app parent_api end it 'inherits helpers from parent API to mounted child API' do get '/test' expect(last_response.status).to eq(200) expect(last_response.body).to eq('parent helper value') end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/instance_spec.rb
spec/grape/api/instance_spec.rb
# frozen_string_literal: true require 'shared/versioning_examples' describe Grape::API::Instance do subject(:an_instance) do Class.new(Grape::API::Instance) do namespace :some_namespace do get 'some_endpoint' do 'success' end end end end let(:root_api) do to_mount = an_instance Class.new(Grape::API) do mount to_mount end end def app root_api end context 'when an instance is mounted on the root' do it 'can call the instance endpoint' do get '/some_namespace/some_endpoint' expect(last_response.body).to eq 'success' end end context 'when an instance is the root' do let(:root_api) do to_mount = an_instance Class.new(Grape::API::Instance) do mount to_mount end end it 'can call the instance endpoint' do get '/some_namespace/some_endpoint' expect(last_response.body).to eq 'success' end end context 'with multiple moutes' do let(:first) do Class.new(Grape::API::Instance) do namespace(:some_namespace) do route :any, '*path' do error!('Not found! (1)', 404) end end end end let(:second) do Class.new(Grape::API::Instance) do namespace(:another_namespace) do route :any, '*path' do error!('Not found! (2)', 404) end end end end let(:root_api) do first_instance = first second_instance = second Class.new(Grape::API) do mount first_instance mount first_instance mount second_instance end end it 'does not raise a FrozenError on first instance' do expect { patch '/some_namespace/anything' }.not_to \ raise_error end it 'responds the correct body at the first instance' do patch '/some_namespace/anything' expect(last_response.body).to eq 'Not found! (1)' end it 'does not raise a FrozenError on second instance' do expect { get '/another_namespace/other' }.not_to \ raise_error end it 'responds the correct body at the second instance' do get '/another_namespace/foobar' expect(last_response.body).to eq 'Not found! (2)' end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/custom_validations_spec.rb
spec/grape/api/custom_validations_spec.rb
# frozen_string_literal: true describe Grape::Validations do describe 'using a custom length validator' do subject do Class.new(Grape::API) do params do requires :text, default_length: 140 end get do 'bacon' end end end let(:default_length_validator) do Class.new(Grape::Validations::Validators::Base) do def validate_param!(attr_name, params) @option = params[:max].to_i if params.key?(:max) return if params[attr_name].length <= @option raise Grape::Exceptions::Validation.new(params: [@scope.full_name(attr_name)], message: "must be at the most #{@option} characters long") end end end let(:app) { subject } before do stub_const('DefaultLengthValidator', default_length_validator) described_class.register(DefaultLengthValidator) end after do described_class.deregister(:default_length) end 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 describe 'using a custom body-only validator' do subject do Class.new(Grape::API) do params do requires :text, in_body: true end get do 'bacon' end end end let(:in_body_validator) do Class.new(Grape::Validations::Validators::PresenceValidator) do def validate(request) validate!(request.env[Grape::Env::API_REQUEST_BODY]) end end end let(:app) { subject } before do stub_const('InBodyValidator', in_body_validator) described_class.register(InBodyValidator) end after do described_class.deregister(:in_body) end it 'allows field in body' do get '/', text: 'abc' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'bacon' end it 'ignores field in query' do get '/', nil, text: 'abc' expect(last_response.status).to eq 400 expect(last_response.body).to eq 'text is missing' end end describe 'using a custom validator with message_key' do subject do Class.new(Grape::API) do params do requires :text, with_message_key: true end get do 'bacon' end end end let(:message_key_validator) do Class.new(Grape::Validations::Validators::PresenceValidator) do def validate_param!(attr_name, _params) raise Grape::Exceptions::Validation.new(params: [@scope.full_name(attr_name)], message: :presence) end end end let(:app) { subject } before do stub_const('WithMessageKeyValidator', message_key_validator) described_class.register(WithMessageKeyValidator) end after do described_class.deregister(:with_message_key) end it 'fails with message' do get '/', text: 'foobar' expect(last_response.status).to eq 400 expect(last_response.body).to eq 'text is missing' end end describe 'using a custom request/param validator' do subject do Class.new(Grape::API) do params do optional :admin_field, type: String, admin: true optional :non_admin_field, type: String optional :admin_false_field, type: String, admin: false end get do 'bacon' end end end let(:admin_validator) do Class.new(Grape::Validations::Validators::Base) do def validate(request) # return if the param we are checking was not in request # @attrs is a list containing the attribute we are currently validating return unless request.params.key? @attrs.first # check if admin flag is set to true return unless @option # check if user is admin or not # as an example get a token from request and check if it's admin or not raise Grape::Exceptions::Validation.new(params: @attrs, message: 'Can not set Admin only field.') unless request.headers[access_header] == 'admin' end def access_header 'x-access-token' end end end let(:app) { subject } let(:x_access_token_header) { 'x-access-token' } before do stub_const('AdminValidator', admin_validator) described_class.register(AdminValidator) end after do described_class.deregister(:admin) end it 'fail when non-admin user sets an admin field' do get '/', admin_field: 'tester', non_admin_field: 'toaster' expect(last_response.status).to eq 400 expect(last_response.body).to include 'Can not set Admin only field.' end it 'does not fail when we send non-admin fields only' do get '/', non_admin_field: 'toaster' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'bacon' end it 'does not fail when we send non-admin and admin=false fields only' do get '/', non_admin_field: 'toaster', admin_false_field: 'test' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'bacon' end it 'does not fail when we send admin fields and we are admin' do header x_access_token_header, 'admin' get '/', admin_field: 'tester', non_admin_field: 'toaster', admin_false_field: 'test' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'bacon' end it 'fails when we send admin fields and we are not admin' do header x_access_token_header, 'user' get '/', admin_field: 'tester', non_admin_field: 'toaster', admin_false_field: 'test' expect(last_response.status).to eq 400 expect(last_response.body).to include 'Can not set Admin only field.' end end describe 'using a custom validator with instance variable' do let(:validator_type) do Class.new(Grape::Validations::Validators::Base) do def validate_param!(_attr_name, _params) if instance_variable_defined?(:@instance_variable) && @instance_variable raise Grape::Exceptions::Validation.new(params: ['params'], message: 'This should never happen') end @instance_variable = true end end end let(:app) do Class.new(Grape::API) do params do optional :param_to_validate, instance_validator: true optional :another_param_to_validate, instance_validator: true end get do 'noop' end end end before do stub_const('InstanceValidatorValidator', validator_type) described_class.register(InstanceValidatorValidator) end after do described_class.deregister(:instance_validator) end it 'passes validation every time' do expect(validator_type).to receive(:new).twice.and_call_original get '/', param_to_validate: 'value', another_param_to_validate: 'value' expect(last_response.status).to eq 200 end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/routes_with_requirements_spec.rb
spec/grape/api/routes_with_requirements_spec.rb
# frozen_string_literal: true describe Grape::Endpoint do subject { Class.new(Grape::API) } def app subject end context 'get' do it 'routes to a namespace param with dots' do subject.namespace ':ns_with_dots', requirements: { ns_with_dots: %r{[^/]+} } do get '/' do params[:ns_with_dots] end end get '/test.id.with.dots' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'test.id.with.dots' end it 'routes to a path with multiple params with dots' do subject.get ':id_with_dots/:another_id_with_dots', requirements: { id_with_dots: %r{[^/]+}, another_id_with_dots: %r{[^/]+} } do "#{params[:id_with_dots]}/#{params[:another_id_with_dots]}" end get '/test.id/test2.id' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'test.id/test2.id' end it 'routes to namespace and path params with dots, with overridden requirements' do subject.namespace ':ns_with_dots', requirements: { ns_with_dots: %r{[^/]+} } do get ':another_id_with_dots', requirements: { ns_with_dots: %r{[^/]+}, another_id_with_dots: %r{[^/]+} } do "#{params[:ns_with_dots]}/#{params[:another_id_with_dots]}" end end get '/test.id/test2.id' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'test.id/test2.id' end it 'routes to namespace and path params with dots, with merged requirements' do subject.namespace ':ns_with_dots', requirements: { ns_with_dots: %r{[^/]+} } do get ':another_id_with_dots', requirements: { another_id_with_dots: %r{[^/]+} } do "#{params[:ns_with_dots]}/#{params[:another_id_with_dots]}" end end get '/test.id/test2.id' expect(last_response.status).to eq 200 expect(last_response.body).to eq 'test.id/test2.id' end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/deeply_included_options_spec.rb
spec/grape/api/deeply_included_options_spec.rb
# frozen_string_literal: true describe Grape::API do let(:app) do main_api = api Class.new(Grape::API) do mount main_api end end let(:api) do deeply_included_options = options Class.new(Grape::API) do include deeply_included_options resource :users do get do status 200 end end end end let(:options) do deep_included_options_default = default Module.new do extend ActiveSupport::Concern include deep_included_options_default end end let(:default) do Module.new do extend ActiveSupport::Concern included do format :json end end end it 'works for unspecified format' do get '/users' expect(last_response.status).to be 200 expect(last_response.content_type).to eql 'application/json' end it 'works for specified format' do get '/users.json' expect(last_response.status).to be 200 expect(last_response.content_type).to eql 'application/json' end it "doesn't work for format different than specified" do get '/users.txt' expect(last_response.status).to be 404 end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/defines_boolean_in_params_spec.rb
spec/grape/api/defines_boolean_in_params_spec.rb
# frozen_string_literal: true describe Grape::API::Instance do describe 'boolean constant' do let(:app) do Class.new(Grape::API) do params do requires :message, type: Grape::API::Boolean end post :echo do { class: params[:message].class.name, value: params[:message] } end end end let(:expected_body) do { class: 'TrueClass', value: true }.to_s end it 'sets Boolean as a type' do post '/echo?message=true' expect(last_response.status).to eq(201) expect(last_response.body).to eq expected_body end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/shared_helpers_spec.rb
spec/grape/api/shared_helpers_spec.rb
# frozen_string_literal: true describe Grape::API::Helpers do subject do shared_params = Module.new do extend Grape::API::Helpers params :pagination do optional :page, type: Integer optional :size, type: Integer end end Class.new(Grape::API) do helpers shared_params format :json params do use :pagination end get do declared(params, include_missing: true) end end end def app subject end it 'defines parameters' do get '/' expect(last_response.status).to eq 200 expect(last_response.body).to eq({ page: nil, size: nil }.to_json) end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/api/invalid_format_spec.rb
spec/grape/api/invalid_format_spec.rb
# frozen_string_literal: true describe Grape::Endpoint do subject { Class.new(Grape::API) } def app subject end before do subject.namespace do format :json content_type :json, 'application/json' params do requires :id, desc: 'Identifier.' end get ':id' do { id: params[:id], format: params[:format] } end end end context 'get' do it 'no format' do get '/foo' expect(last_response.status).to eq 200 expect(last_response.body).to eq(Grape::Json.dump(id: 'foo', format: nil)) end it 'json format' do get '/foo.json' expect(last_response.status).to eq 200 expect(last_response.body).to eq(Grape::Json.dump(id: 'foo', format: 'json')) end it 'invalid format' do get '/foo.invalid' expect(last_response.status).to eq 200 expect(last_response.body).to eq(Grape::Json.dump(id: 'foo', format: 'invalid')) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/types_spec.rb
spec/grape/validations/types_spec.rb
# frozen_string_literal: true describe Grape::Validations::Types do let(:foo_type) do Class.new do def self.parse(_); end end end let(:bar_type) do Class.new do def self.parse; end end end describe '::primitive?' do [ Integer, Float, Numeric, BigDecimal, Grape::API::Boolean, String, Symbol, Date, DateTime, Time ].each do |type| it "recognizes #{type} as a primitive" do expect(described_class).to be_primitive(type) end end it 'identifies unknown types' do expect(described_class).not_to be_primitive(Object) expect(described_class).not_to be_primitive(foo_type) end end describe '::structure?' do [ Hash, Array, Set ].each do |type| it "recognizes #{type} as a structure" do expect(described_class).to be_structure(type) end end end describe '::special?' do [ JSON, Array[JSON], File, Rack::Multipart::UploadedFile ].each do |type| it "provides special handling for #{type.inspect}" do expect(described_class).to be_special(type) end end end describe 'special types' do subject { described_class::SPECIAL[type] } context 'when JSON' do let(:type) { JSON } it { is_expected.to eq(Grape::Validations::Types::Json) } end context 'when Array[JSON]' do let(:type) { Array[JSON] } it { is_expected.to eq(Grape::Validations::Types::JsonArray) } end context 'when File' do let(:type) { File } it { is_expected.to eq(Grape::Validations::Types::File) } end context 'when Rack::Multipart::UploadedFile' do let(:type) { Rack::Multipart::UploadedFile } it { is_expected.to eq(Grape::Validations::Types::File) } end end describe '::custom?' do it 'returns false if the type does not respond to :parse' do expect(described_class).not_to be_custom(Object) end it 'returns true if the type responds to :parse with one argument' do expect(described_class).to be_custom(foo_type) end it 'returns false if the type\'s #parse method takes other than one argument' do expect(described_class).not_to be_custom(bar_type) end end describe '::build_coercer' do it 'caches the result of the build_coercer method' do a_coercer = described_class.build_coercer(Array[String]) b_coercer = described_class.build_coercer(Array[String]) expect(a_coercer.object_id).to eq(b_coercer.object_id) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/multiple_attributes_iterator_spec.rb
spec/grape/validations/multiple_attributes_iterator_spec.rb
# frozen_string_literal: true describe Grape::Validations::MultipleAttributesIterator do describe '#each' do subject(:iterator) { described_class.new(validator, scope, params) } let(:scope) { Grape::Validations::ParamsScope.new(api: Class.new(Grape::API)) } let(:validator) { double(attrs: %i[first second third]) } context 'when params is a hash' do let(:params) do { first: 'string', second: 'string' } end it 'yields the whole params hash without the list of attrs' do expect { |b| iterator.each(&b) }.to yield_with_args(params) end end context 'when params is an array' do let(:params) do [{ first: 'string1', second: 'string1' }, { first: 'string2', second: 'string2' }] end it 'yields each element of the array without the list of attrs' do expect { |b| iterator.each(&b) }.to yield_successive_args(params[0], params[1]) end end context 'when params is empty optional placeholder' do let(:params) { [Grape::DSL::Parameters::EmptyOptionalValue] } it 'does not yield it' do expect { |b| iterator.each(&b) }.to yield_successive_args end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/params_scope_spec.rb
spec/grape/validations/params_scope_spec.rb
# frozen_string_literal: true describe Grape::Validations::ParamsScope do subject do Class.new(Grape::API) end def app subject end context 'when using custom types' do let(:custom_type) do Class.new do attr_reader :value def self.parse(value) raise if value == 'invalid' new(value) end def initialize(value) @value = value end end end it 'coerces the parameter via the type\'s parse method' do context = self subject.params do requires :foo, type: context.custom_type end subject.get('/types') { params[:foo].value } get '/types', foo: 'valid' expect(last_response.status).to eq(200) expect(last_response.body).to eq('valid') get '/types', foo: 'invalid' expect(last_response.status).to eq(400) expect(last_response.body).to match(/foo is invalid/) end end context 'param renaming' do it do subject.params do requires :foo, as: :bar optional :super, as: :hiper end subject.get('/renaming') { "#{declared(params)['bar']}-#{declared(params)['hiper']}" } get '/renaming', foo: 'any', super: 'any2' expect(last_response.status).to eq(200) expect(last_response.body).to eq('any-any2') end it do subject.params do requires :foo, as: :bar, type: String, coerce_with: lambda(&:strip) end subject.get('/renaming-coerced') { "#{params['bar']}-#{params['foo']}" } get '/renaming-coerced', foo: ' there we go ' expect(last_response.status).to eq(200) expect(last_response.body).to eq('-there we go') end it do subject.params do requires :foo, as: :bar, allow_blank: false end subject.get('/renaming-not-blank') {} get '/renaming-not-blank', foo: '' expect(last_response.status).to eq(400) expect(last_response.body).to eq('foo is empty') end it do subject.params do requires :foo, as: :bar, allow_blank: false end subject.get('/renaming-not-blank-with-value') {} get '/renaming-not-blank-with-value', foo: 'any' expect(last_response.status).to eq(200) end it do subject.params do requires :foo, as: :baz, type: Hash do requires :bar, as: :qux end end subject.get('/nested-renaming') { declared(params).to_json } get '/nested-renaming', foo: { bar: 'any' } expect(last_response.status).to eq(200) expect(last_response.body).to eq('{"baz":{"qux":"any"}}') end it 'renaming can be defined before default' do subject.params do optional :foo, as: :bar, default: 'before' end subject.get('/rename-before-default') { declared(params)[:bar] } get '/rename-before-default' expect(last_response.status).to eq(200) expect(last_response.body).to eq('before') end it 'renaming can be defined after default' do subject.params do optional :foo, default: 'after', as: :bar end subject.get('/rename-after-default') { declared(params)[:bar] } get '/rename-after-default' expect(last_response.status).to eq(200) expect(last_response.body).to eq('after') end end context 'array without coerce type explicitly given' do it 'sets the type based on first element' do subject.params do requires :periods, type: Array, values: -> { %w[day month] } end subject.get('/required') { 'required works' } get '/required', periods: %w[day month] expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end it 'fails to call API without Array type' do subject.params do requires :periods, type: Array, values: -> { %w[day month] } end subject.get('/required') { 'required works' } get '/required', periods: 'day' expect(last_response.status).to eq(400) expect(last_response.body).to eq('periods is invalid') end it 'raises exception when values are of different type' do expect do subject.params { requires :numbers, type: Array, values: [1, 'definitely not a number', 3] } end.to raise_error Grape::Exceptions::IncompatibleOptionValues end it 'raises exception when range values have different endpoint types' do expect do subject.params { requires :numbers, type: Array, values: 0.0..10 } end.to raise_error Grape::Exceptions::IncompatibleOptionValues end end context 'coercing values validation with proc' do it 'allows the proc to pass validation without checking' do subject.params { requires :numbers, type: Integer, values: -> { [0, 1, 2] } } subject.post('/required') { 'coercion with proc works' } post '/required', numbers: '1' expect(last_response.status).to eq(201) expect(last_response.body).to eq('coercion with proc works') end it 'allows the proc to pass validation without checking in value' do subject.params { requires :numbers, type: Integer, values: { value: -> { [0, 1, 2] } } } subject.post('/required') { 'coercion with proc works' } post '/required', numbers: '1' expect(last_response.status).to eq(201) expect(last_response.body).to eq('coercion with proc works') end it 'allows the proc to pass validation without checking in except' do subject.params { requires :numbers, type: Integer, except_values: -> { [0, 1, 2] } } subject.post('/required') { 'coercion with proc works' } post '/required', numbers: '10' expect(last_response.status).to eq(201) expect(last_response.body).to eq('coercion with proc works') end end context 'a Set with coerce type explicitly given' do context 'and the values are allowed' do it 'does not raise an exception' do expect do subject.params { optional :numbers, type: Set[Integer], values: 0..2, default: 0..2 } end.not_to raise_error end end context 'and the values are not allowed' 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 context 'with range values' do context "when left range endpoint isn't #kind_of? the type" do it 'raises exception' do expect do subject.params { requires :latitude, type: Integer, values: -90.0..90 } end.to raise_error Grape::Exceptions::IncompatibleOptionValues end end context "when right range endpoint isn't #kind_of? the type" do it 'raises exception' do expect do subject.params { requires :latitude, type: Integer, values: -90..90.0 } end.to raise_error Grape::Exceptions::IncompatibleOptionValues end end context 'when the default is an array' do context 'and is the entire range of allowed values' do it 'does not raise an exception' do expect do subject.params { optional :numbers, type: Array[Integer], values: 0..2, default: 0..2 } end.not_to raise_error end end context 'and is a subset of allowed values' do it 'does not raise an exception' do expect do subject.params { optional :numbers, type: Array[Integer], values: [0, 1, 2], default: [1, 0] } end.not_to raise_error end end end context 'when both range endpoints are #kind_of? the type' do it 'accepts values in the range' do subject.params do requires :letter, type: String, values: 'a'..'z' end subject.get('/letter') { params[:letter] } get '/letter', letter: 'j' expect(last_response.status).to eq(200) expect(last_response.body).to eq('j') end it 'rejects values outside the range' do subject.params do requires :letter, type: String, values: 'a'..'z' end subject.get('/letter') { params[:letter] } get '/letter', letter: 'J' expect(last_response.status).to eq(400) expect(last_response.body).to eq('letter does not have a valid value') end end end context 'parameters in group' do it 'errors when no type is provided' do expect do subject.params do group :a do requires :b end end end.to raise_error Grape::Exceptions::MissingGroupType expect do subject.params do optional :a do requires :b end end end.to raise_error Grape::Exceptions::MissingGroupType end it 'allows Hash as type' do subject.params do group :a, type: Hash do requires :b end end subject.get('/group') { 'group works' } get '/group', a: { b: true } expect(last_response.status).to eq(200) expect(last_response.body).to eq('group works') subject.params do optional :a, type: Hash do requires :b end end get '/optional_type_hash' end it 'allows Array as type' do subject.params do group :a, type: Array do requires :b end end subject.get('/group') { 'group works' } get '/group', a: [{ b: true }] expect(last_response.status).to eq(200) expect(last_response.body).to eq('group works') subject.params do optional :a, type: Array do requires :b end end get '/optional_type_array' end it 'handles missing optional Array type' do subject.params do optional :a, type: Array do requires :b end end subject.get('/test') { declared(params).to_json } get '/test' expect(last_response.status).to eq(200) expect(last_response.body).to eq('{"a":[]}') end it 'errors with an unsupported type' do expect do subject.params do group :a, type: Set do requires :b end end end.to raise_error Grape::Exceptions::UnsupportedGroupType expect do subject.params do optional :a, type: Set do requires :b end end end.to raise_error Grape::Exceptions::UnsupportedGroupType end end context 'when validations are dependent on a parameter' do before do subject.params do optional :a given :a do requires :b end end subject.get('/test') { declared(params).to_json } end it 'applies the validations only if the parameter is present' do get '/test' expect(last_response.status).to eq(200) get '/test', a: true expect(last_response.status).to eq(400) expect(last_response.body).to eq('b is missing') get '/test', a: true, b: true expect(last_response.status).to eq(200) end it 'applies the validations of multiple parameters' do subject.params do optional :a, :b given :a, :b do requires :c end end subject.get('/multiple') { declared(params).to_json } get '/multiple' expect(last_response.status).to eq(200) get '/multiple', a: true expect(last_response.status).to eq(200) get '/multiple', b: true expect(last_response.status).to eq(200) get '/multiple', a: true, b: true expect(last_response.status).to eq(400) expect(last_response.body).to eq('c is missing') get '/multiple', a: true, b: true, c: true expect(last_response.status).to eq(200) end it 'applies only the appropriate validation' do subject.params do optional :a optional :b mutually_exclusive :a, :b given :a do requires :c, type: String end given :b do requires :c, type: Integer end end subject.get('/multiple') { declared(params).to_json } get '/multiple' expect(last_response.status).to eq(200) get '/multiple', a: true, c: 'test' expect(last_response.status).to eq(200) expect(JSON.parse(last_response.body).symbolize_keys).to eq a: 'true', b: nil, c: 'test' get '/multiple', b: true, c: '3' expect(last_response.status).to eq(200) expect(JSON.parse(last_response.body).symbolize_keys).to eq a: nil, b: 'true', c: 3 get '/multiple', a: true expect(last_response.status).to eq(400) expect(last_response.body).to eq('c is missing') get '/multiple', b: true expect(last_response.status).to eq(400) expect(last_response.body).to eq('c is missing') get '/multiple', a: true, b: true, c: 'test' expect(last_response.status).to eq(400) expect(last_response.body).to eq('a, b are mutually exclusive, c is invalid') end it 'raises an error if the dependent parameter was never specified' do expect do subject.params do given :c do end end end.to raise_error(Grape::Exceptions::UnknownParameter) end it 'does not raise an error if the dependent parameter is a Hash' do expect do subject.params do optional :a, type: Hash do requires :b end given :a do requires :c end end end.not_to raise_error end it 'does not raise an error if when using nested given' do expect do subject.params do optional :a, type: Hash do requires :b end given :a do requires :c given :c do requires :d end end end end.not_to raise_error end it 'allows nested dependent parameters' do subject.params do optional :a given a: ->(val) { val == 'a' } do optional :b given b: ->(val) { val == 'b' } do optional :c given c: ->(val) { val == 'c' } do requires :d end end end end subject.get('/') { declared(params).to_json } get '/' expect(last_response.status).to eq 200 get '/', a: 'a', b: 'b', c: 'c' expect(last_response.status).to eq 400 expect(last_response.body).to eq 'd is missing' get '/', a: 'a', b: 'b', c: 'c', d: 'd' expect(last_response.status).to eq 200 expect(last_response.body).to eq({ a: 'a', b: 'b', c: 'c', d: 'd' }.to_json) end it 'allows renaming of dependent parameters' do subject.params do optional :a given :a do requires :b, as: :c end end subject.get('/multiple') { declared(params).to_json } get '/multiple', a: 'a', b: 'b' body = JSON.parse(last_response.body) expect(body.keys).to include('c') expect(body.keys).not_to include('b') end it 'allows renaming of dependent on parameter' do subject.params do optional :a, as: :b given a: ->(val) { val == 'x' } do requires :c end end subject.get('/') { declared(params) } get '/', a: 'x' expect(last_response.status).to eq 400 expect(last_response.body).to eq 'c is missing' get '/', a: 'y' expect(last_response.status).to eq 200 end it 'does not raise if the dependent parameter is not the renamed one' do expect do subject.params do optional :a, as: :b given :a do requires :c end end end.not_to raise_error end it 'raises an error if the dependent parameter is the renamed one' do expect do subject.params do optional :a, as: :b given :b do requires :c end end end.to raise_error(Grape::Exceptions::UnknownParameter) end it 'does not validate nested requires when given is false' do subject.params do requires :a, type: String, allow_blank: false, values: %w[x y z] given a: ->(val) { val == 'x' } do requires :inner1, type: Hash, allow_blank: false do requires :foo, type: Integer, allow_blank: false end end given a: ->(val) { val == 'y' } do requires :inner2, type: Hash, allow_blank: false do requires :bar, type: Integer, allow_blank: false requires :baz, type: Array, allow_blank: false do requires :baz_category, type: String, allow_blank: false end end end given a: ->(val) { val == 'z' } do requires :inner3, type: Array, allow_blank: false do requires :bar, type: Integer, allow_blank: false requires :baz, type: Array, allow_blank: false do requires :baz_category, type: String, allow_blank: false end end end end subject.get('/varying') { declared(params).to_json } get '/varying', a: 'x', inner1: { foo: 1 } expect(last_response.status).to eq(200) get '/varying', a: 'y', inner2: { bar: 2, baz: [{ baz_category: 'barstools' }] } expect(last_response.status).to eq(200) get '/varying', a: 'y', inner2: { bar: 2, baz: [{ unrelated: 'yep' }] } expect(last_response.status).to eq(400) get '/varying', a: 'z', inner3: [{ bar: 3, baz: [{ baz_category: 'barstools' }] }] expect(last_response.status).to eq(200) end it 'detect unmet nested dependency' do subject.params do requires :a, type: String, allow_blank: false, values: %w[x y z] given a: ->(val) { val == 'z' } do requires :inner3, type: Array, allow_blank: false do requires :bar, type: String, allow_blank: false given bar: ->(val) { val == 'b' } do requires :baz, type: Array do optional :baz_category, type: String end end given bar: ->(val) { val == 'c' } do requires :baz, type: Array do requires :baz_category, type: String end end end end end subject.get('/nested-dependency') { declared(params).to_json } get '/nested-dependency', a: 'z', inner3: [{ bar: 'c', baz: [{ unrelated: 'nope' }] }] expect(last_response.status).to eq(400) expect(last_response.body).to eq 'inner3[0][baz][0][baz_category] is missing' end context 'detect when json array' do before do subject.params do requires :array, type: Array do requires :a, type: String given a: ->(val) { val == 'a' } do requires :json, type: Hash do requires :b, type: String end end end end subject.post '/nested_array' do 'nested array works!' end end it 'succeeds' do params = { array: [ { a: 'a', json: { b: 'b' } }, { a: 'b' } ] } post '/nested_array', params.to_json, 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq(201) end it 'fails' do params = { array: [ { a: 'a', json: { b: 'b' } }, { a: 'a' } ] } post '/nested_array', params.to_json, 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq(400) expect(last_response.body).to eq('array[1][json] is missing, array[1][json][b] is missing') end end context 'array without given' do before do subject.params do requires :array, type: Array do requires :a, type: Integer requires :b, type: Integer end end subject.post '/array_without_given' end it 'fails' do params = { array: [ { a: 1, b: 2 }, { a: 3 }, { a: 5 } ] } post '/array_without_given', params.to_json, 'CONTENT_TYPE' => 'application/json' expect(last_response.body).to eq('array[1][b] is missing, array[2][b] is missing') expect(last_response.status).to eq(400) end end context 'array with given' do before do subject.params do requires :array, type: Array do requires :a, type: Integer given a: lambda(&:odd?) do requires :b, type: Integer end end end subject.post '/array_with_given' end it 'fails' do params = { array: [ { a: 1, b: 2 }, { a: 3 }, { a: 5 } ] } post '/array_with_given', params.to_json, 'CONTENT_TYPE' => 'application/json' expect(last_response.body).to eq('array[1][b] is missing, array[2][b] is missing') expect(last_response.status).to eq(400) end end context 'nested json array with given' do before do subject.params do requires :workflow_nodes, type: Array do requires :steps, type: Array do requires :id, type: String optional :type, type: String, values: %w[send_messsge assign_user assign_team tag_conversation snooze close add_commit] given type: ->(val) { val == 'send_messsge' } do requires :message, type: Hash do requires :content, type: String end end end end end subject.post '/nested_json_array_with_given' end it 'passes' do params = { workflow_nodes: [ { id: 'eqibmvEzPo8hQOSt', title: 'Node 1', is_start: true, steps: [ { id: 'DvdSZaIm1hEd5XO5', type: 'send_messsge', message: { content: '打击好', menus: [] } }, { id: 'VY6MIwycBw0b51Ib', type: 'add_commit', comment_content: '初来乍到' } ] } ] } post '/nested_json_array_with_given', params.to_json, 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq(201) end end it 'includes the parameter within #declared(params)' do get '/test', a: true, b: true expect(JSON.parse(last_response.body)).to eq('a' => 'true', 'b' => 'true') end it 'returns a sensible error message within a nested context' do subject.params do requires :bar, type: Hash do optional :a given :a do requires :b end end end subject.get('/nested') { 'worked' } get '/nested', bar: { a: true } expect(last_response.status).to eq(400) expect(last_response.body).to eq('bar[b] is missing') end it 'includes the nested parameter within #declared(params)' do subject.params do requires :bar, type: Hash do optional :a given :a do requires :b end end end subject.get('/nested') { declared(params).to_json } get '/nested', bar: { a: true, b: 'yes' } expect(JSON.parse(last_response.body)).to eq('bar' => { 'a' => 'true', 'b' => 'yes' }) end it 'includes level 2 nested parameters outside the given within #declared(params)' do subject.params do requires :bar, type: Hash do optional :a given :a do requires :c, type: Hash do requires :b end end end end subject.get('/nested') { declared(params).to_json } get '/nested', bar: { a: true, c: { b: 'yes' } } expect(JSON.parse(last_response.body)).to eq('bar' => { 'a' => 'true', 'c' => { 'b' => 'yes' } }) end context 'when the dependent parameter is not present #declared(params)' do context 'lateral parameter' do before do [true, false].each do |evaluate_given| subject.params do optional :a given :a do optional :b end end subject.get("/evaluate_given_#{evaluate_given}") { declared(params, evaluate_given: evaluate_given).to_json } end end it 'evaluate_given_false' do get '/evaluate_given_false', b: 'b' expect(JSON.parse(last_response.body)).to eq('a' => nil, 'b' => 'b') end it 'evaluate_given_true' do get '/evaluate_given_true', b: 'b' expect(JSON.parse(last_response.body)).to eq('a' => nil) end end context 'lateral hash parameter' do before do [true, false].each do |evaluate_given| subject.params do optional :a, values: %w[x y] given a: ->(a) { a == 'x' } do optional :b, type: Hash do optional :c end optional :e end given a: ->(a) { a == 'y' } do optional :b, type: Hash do optional :d end optional :f end end subject.get("/evaluate_given_#{evaluate_given}") { declared(params, evaluate_given: evaluate_given).to_json } end end it 'evaluate_given_false' do get '/evaluate_given_false', a: 'x' expect(JSON.parse(last_response.body)).to eq('a' => 'x', 'b' => { 'd' => nil }, 'e' => nil, 'f' => nil) get '/evaluate_given_false', a: 'y' expect(JSON.parse(last_response.body)).to eq('a' => 'y', 'b' => { 'd' => nil }, 'e' => nil, 'f' => nil) end it 'evaluate_given_true' do get '/evaluate_given_true', a: 'x' expect(JSON.parse(last_response.body)).to eq('a' => 'x', 'b' => { 'c' => nil }, 'e' => nil) get '/evaluate_given_true', a: 'y' expect(JSON.parse(last_response.body)).to eq('a' => 'y', 'b' => { 'd' => nil }, 'f' => nil) end end context 'lateral parameter within lateral hash parameter' do before do [true, false].each do |evaluate_given| subject.params do optional :a, values: %w[x y] given a: ->(a) { a == 'x' } do optional :b, type: Hash do optional :c given :c do optional :g optional :e, type: Hash do optional :h end end end end given a: ->(a) { a == 'y' } do optional :b, type: Hash do optional :d given :d do optional :f optional :e, type: Hash do optional :i end end end end end subject.get("/evaluate_given_#{evaluate_given}") { declared(params, evaluate_given: evaluate_given).to_json } end end it 'evaluate_given_false' do get '/evaluate_given_false', a: 'x' expect(JSON.parse(last_response.body)).to eq('a' => 'x', 'b' => { 'd' => nil, 'f' => nil, 'e' => { 'i' => nil } }) get '/evaluate_given_false', a: 'x', b: { c: 'c' } expect(JSON.parse(last_response.body)).to eq('a' => 'x', 'b' => { 'd' => nil, 'f' => nil, 'e' => { 'i' => nil } }) get '/evaluate_given_false', a: 'y' expect(JSON.parse(last_response.body)).to eq('a' => 'y', 'b' => { 'd' => nil, 'f' => nil, 'e' => { 'i' => nil } }) get '/evaluate_given_false', a: 'y', b: { d: 'd' } expect(JSON.parse(last_response.body)).to eq('a' => 'y', 'b' => { 'd' => 'd', 'f' => nil, 'e' => { 'i' => nil } }) end it 'evaluate_given_true' do get '/evaluate_given_true', a: 'x' expect(JSON.parse(last_response.body)).to eq('a' => 'x', 'b' => { 'c' => nil }) get '/evaluate_given_true', a: 'x', b: { c: 'c' } expect(JSON.parse(last_response.body)).to eq('a' => 'x', 'b' => { 'c' => 'c', 'g' => nil, 'e' => { 'h' => nil } }) get '/evaluate_given_true', a: 'y' expect(JSON.parse(last_response.body)).to eq('a' => 'y', 'b' => { 'd' => nil }) get '/evaluate_given_true', a: 'y', b: { d: 'd' } expect(JSON.parse(last_response.body)).to eq('a' => 'y', 'b' => { 'd' => 'd', 'f' => nil, 'e' => { 'i' => nil } }) end end context 'lateral parameter within an array param' do before do [true, false].each do |evaluate_given| subject.params do optional :array, type: Array do optional :a given :a do optional :b end end end subject.post("/evaluate_given_#{evaluate_given}") do declared(params, evaluate_given: evaluate_given).to_json end end end it 'evaluate_given_false' do post '/evaluate_given_false', { array: [{ b: 'b' }, { a: 'a', b: 'b' }] }.to_json, 'CONTENT_TYPE' => 'application/json' expect(JSON.parse(last_response.body)).to eq('array' => [{ 'a' => nil, 'b' => 'b' }, { 'a' => 'a', 'b' => 'b' }]) end it 'evaluate_given_true' do post '/evaluate_given_true', { array: [{ b: 'b' }, { a: 'a', b: 'b' }] }.to_json, 'CONTENT_TYPE' => 'application/json' expect(JSON.parse(last_response.body)).to eq('array' => [{ 'a' => nil }, { 'a' => 'a', 'b' => 'b' }]) end end context 'nested given parameter' do before do [true, false].each do |evaluate_given| subject.params do optional :a optional :c given :a do given :c do optional :b end end end subject.post("/evaluate_given_#{evaluate_given}") do declared(params, evaluate_given: evaluate_given).to_json end end end it 'evaluate_given_false' do post '/evaluate_given_false', { a: 'a', b: 'b' }.to_json, 'CONTENT_TYPE' => 'application/json' expect(JSON.parse(last_response.body)).to eq('a' => 'a', 'b' => 'b', 'c' => nil) post '/evaluate_given_false', { c: 'c', b: 'b' }.to_json, 'CONTENT_TYPE' => 'application/json' expect(JSON.parse(last_response.body)).to eq('a' => nil, 'b' => 'b', 'c' => 'c') post '/evaluate_given_false', { a: 'a', c: 'c', b: 'b' }.to_json, 'CONTENT_TYPE' => 'application/json' expect(JSON.parse(last_response.body)).to eq('a' => 'a', 'b' => 'b', 'c' => 'c') end it 'evaluate_given_true' do post '/evaluate_given_true', { a: 'a', b: 'b' }.to_json, 'CONTENT_TYPE' => 'application/json' expect(JSON.parse(last_response.body)).to eq('a' => 'a', 'c' => nil) post '/evaluate_given_true', { c: 'c', b: 'b' }.to_json, 'CONTENT_TYPE' => 'application/json' expect(JSON.parse(last_response.body)).to eq('a' => nil, 'c' => 'c') post '/evaluate_given_true', { a: 'a', c: 'c', b: 'b' }.to_json, 'CONTENT_TYPE' => 'application/json' expect(JSON.parse(last_response.body)).to eq('a' => 'a', 'b' => 'b', 'c' => 'c') end end context 'nested given parameter within an array param' do before do [true, false].each do |evaluate_given| subject.params do optional :array, type: Array do optional :a optional :c given :a do given :c do
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
true
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/single_attribute_iterator_spec.rb
spec/grape/validations/single_attribute_iterator_spec.rb
# frozen_string_literal: true describe Grape::Validations::SingleAttributeIterator do describe '#each' do subject(:iterator) { described_class.new(validator, scope, params) } let(:scope) { Grape::Validations::ParamsScope.new(api: Class.new(Grape::API)) } let(:validator) { double(attrs: %i[first second]) } context 'when params is a hash' do let(:params) do { first: 'string', second: 'string' } end it 'yields params and every single attribute from the list' do expect { |b| iterator.each(&b) } .to yield_successive_args([params, :first, false], [params, :second, false]) end end context 'when params is an array' do let(:params) do [{ first: 'string1', second: 'string1' }, { first: 'string2', second: 'string2' }] end it 'yields every single attribute from the list for each of the array elements' do expect { |b| iterator.each(&b) }.to yield_successive_args( [params[0], :first, false], [params[0], :second, false], [params[1], :first, false], [params[1], :second, false] ) end context 'empty values' do let(:params) { [{}, '', 10] } it 'marks params with empty values' do expect { |b| iterator.each(&b) }.to yield_successive_args( [params[0], :first, true], [params[0], :second, true], [params[1], :first, true], [params[1], :second, true], [params[2], :first, false], [params[2], :second, false] ) end end context 'when missing optional value' do let(:params) { [Grape::DSL::Parameters::EmptyOptionalValue, 10] } it 'does not yield skipped values' do expect { |b| iterator.each(&b) }.to yield_successive_args( [params[1], :first, false], [params[1], :second, false] ) end end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/params_documentation_spec.rb
spec/grape/validations/params_documentation_spec.rb
# frozen_string_literal: true describe Grape::Validations::ParamsDocumentation do subject { klass.new(api_double) } let(:api_double) do Class.new do include Grape::DSL::Settings end.new end let(:klass) do Class.new do include Grape::Validations::ParamsDocumentation attr_accessor :api def initialize(api) @api = api end def full_name(name) "full_name_#{name}" end end end describe '#document_params' do it 'stores documented params with all details' do attrs = %i[foo bar] validations = { presence: true, default: 42, length: { min: 1, max: 10 }, desc: 'A foo', documentation: { note: 'doc' } } type = Integer values = [1, 2, 3] except_values = [4, 5, 6] subject.document_params(attrs, validations.dup, type, values, except_values) expect(api_double.inheritable_setting.namespace_stackable[:params].first.keys).to include('full_name_foo', 'full_name_bar') expect(api_double.inheritable_setting.namespace_stackable[:params].first['full_name_foo']).to include( required: true, type: 'Integer', values: [1, 2, 3], except_values: [4, 5, 6], default: 42, min_length: 1, max_length: 10, desc: 'A foo', documentation: { note: 'doc' } ) end context 'when do_not_document is set' do let(:validations) do { desc: 'desc', description: 'description', documentation: { foo: 'bar' }, another_param: 'test' } end before do api_double.inheritable_setting.namespace_inheritable[:do_not_document] = true end it 'removes desc, description, and documentation' do subject.document_params([:foo], validations) expect(validations).to eq({ another_param: 'test' }) end end context 'when validation is empty' do let(:validations) do {} end it 'does not raise an error' do expect { subject.document_params([:foo], validations) }.not_to raise_error expect(api_double.inheritable_setting.namespace_stackable[:params].first['full_name_foo']).to eq({ required: false }) end end context 'when desc is not present' do let(:validations) do { description: 'desc2' } end it 'uses description if desc is not present' do subject.document_params([:foo], validations) expect(api_double.inheritable_setting.namespace_stackable[:params].first['full_name_foo'][:desc]).to eq('desc2') end end context 'when desc nor description is present' do let(:validations) do {} end it 'uses description if desc is not present' do subject.document_params([:foo], validations) expect(api_double.inheritable_setting.namespace_stackable[:params].first['full_name_foo']).to eq({ required: false }) end end context 'when documentation is not present' do let(:validations) do {} end it 'does not include documentation' do subject.document_params([:foo], validations) expect(api_double.inheritable_setting.namespace_stackable[:params].first['full_name_foo']).not_to have_key(:documentation) end end context 'when type is nil' do let(:validations) do { presence: true } end it 'sets type as nil' do subject.document_params([:foo], validations) expect(api_double.inheritable_setting.namespace_stackable[:params].first['full_name_foo'][:type]).to be_nil end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/validators/regexp_validator_spec.rb
spec/grape/validations/validators/regexp_validator_spec.rb
# frozen_string_literal: true describe Grape::Validations::Validators::RegexpValidator do let_it_be(:app) do Class.new(Grape::API) do default_format :json resources :custom_message do params do requires :name, regexp: { value: /^[a-z]+$/, message: 'format is invalid' } end get do end params do requires :names, type: { value: Array[String], message: 'can\'t be nil' }, regexp: { value: /^[a-z]+$/, message: 'format is invalid' } end get 'regexp_with_array' do end end params do requires :name, regexp: /^[a-z]+$/ end get do end params do requires :names, type: Array[String], regexp: /^[a-z]+$/ end get 'regexp_with_array' do end params do requires :people, type: Hash do requires :names, type: Array[String], regexp: /^[a-z]+$/ end end get 'nested_regexp_with_array' do end end end describe '#bad encoding' do let(:app) do Class.new(Grape::API) do default_format :json params do requires :name, regexp: { value: /^[a-z]+$/ } end get '/bad_encoding' end end context 'when value as bad encoding' do it 'does not raise an error' do expect { get '/bad_encoding', name: "Hello \x80" }.not_to raise_error end end end context 'custom validation message' do context 'with invalid input' do it 'refuses inapppopriate' do get '/custom_message', name: 'invalid name' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"name format is invalid"}') end it 'refuses empty' do get '/custom_message', name: '' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"name format is invalid"}') end end it 'accepts nil' do get '/custom_message', name: nil expect(last_response.status).to eq(200) end it 'accepts valid input' do get '/custom_message', name: 'bob' expect(last_response.status).to eq(200) end context 'regexp with array' do it 'refuses inapppopriate items' do get '/custom_message/regexp_with_array', names: ['invalid name', 'abc'] expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"names format is invalid"}') end it 'refuses empty items' do get '/custom_message/regexp_with_array', names: ['', 'abc'] expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"names format is invalid"}') end it 'refuses nil items' do get '/custom_message/regexp_with_array', names: [nil, 'abc'] expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"names can\'t be nil"}') end it 'accepts valid items' do get '/custom_message/regexp_with_array', names: ['bob'] expect(last_response.status).to eq(200) end it 'accepts nil instead of array' do get '/custom_message/regexp_with_array', names: nil expect(last_response.status).to eq(200) end end end context 'invalid input' do it 'refuses inapppopriate' do get '/', name: 'invalid name' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"name is invalid"}') end it 'refuses empty' do get '/', name: '' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"name is invalid"}') end end it 'accepts nil' do get '/', name: nil expect(last_response.status).to eq(200) end it 'accepts valid input' do get '/', name: 'bob' expect(last_response.status).to eq(200) end context 'regexp with array' do it 'refuses inapppopriate items' do get '/regexp_with_array', names: ['invalid name', 'abc'] expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"names is invalid"}') end it 'refuses empty items' do get '/regexp_with_array', names: ['', 'abc'] expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"names is invalid"}') end it 'refuses nil items' do get '/regexp_with_array', names: [nil, 'abc'] expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"names is invalid"}') end it 'accepts valid items' do get '/regexp_with_array', names: ['bob'] expect(last_response.status).to eq(200) end it 'accepts nil instead of array' do get '/regexp_with_array', names: nil expect(last_response.status).to eq(200) end end context 'nested regexp with array' do it 'refuses inapppopriate' do get '/nested_regexp_with_array', people: 'invalid name' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"people is invalid, people[names] is missing, people[names] is invalid"}') end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/validators/contract_scope_validator_spec.rb
spec/grape/validations/validators/contract_scope_validator_spec.rb
# frozen_string_literal: true describe Grape::Validations::Validators::ContractScopeValidator do describe '.inherits' do subject { described_class } it { is_expected.to be < Grape::Validations::Validators::Base } end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/validators/coerce_validator_spec.rb
spec/grape/validations/validators/coerce_validator_spec.rb
# frozen_string_literal: true describe Grape::Validations::Validators::CoerceValidator do subject { Class.new(Grape::API) } let(:app) { subject } describe 'coerce' do let(:secure_uri_only) do Class.new do def self.parse(value) URI.parse(value) end def self.parsed?(value) value.is_a? URI::HTTPS end end end context 'i18n' do after do I18n.available_locales = %i[en] I18n.locale = :en I18n.default_locale = :en end it 'i18n error on malformed input' do I18n.available_locales = %i[en zh-CN] I18n.load_path << File.expand_path('zh-CN.yml', __dir__) I18n.reload! I18n.locale = :'zh-CN' subject.params do requires :age, type: Integer end subject.get '/single' do 'int works' end get '/single', age: '43a' expect(last_response).to be_bad_request expect(last_response.body).to eq('年龄格式不正确') end it 'gives an english fallback error when default locale message is blank' do I18n.available_locales = %i[en pt-BR] I18n.locale = :'pt-BR' subject.params do requires :age, type: Integer end subject.get '/single' do 'int works' end get '/single', age: '43a' expect(last_response).to be_bad_request expect(last_response.body).to eq('age is invalid') end end context 'with a custom validation message' do it 'errors on malformed input' do subject.params do requires :int, type: { value: Integer, message: 'type cast is invalid' } end subject.get '/single' do 'int works' end get '/single', int: '43a' expect(last_response).to be_bad_request expect(last_response.body).to eq('int type cast is invalid') get '/single', int: '43' expect(last_response).to be_successful expect(last_response.body).to eq('int works') end context 'on custom coercion rules' do before do subject.params do requires :a, types: { value: [Grape::API::Boolean, String], message: 'type cast is invalid' }, coerce_with: (lambda do |val| case val when 'yup' true when 'false' 0 else val end end) end subject.get '/' do params[:a].class.to_s end end it 'respects :coerce_with' do get '/', a: 'yup' expect(last_response).to be_successful expect(last_response.body).to eq('TrueClass') end it 'still validates type' do get '/', a: 'false' expect(last_response).to be_bad_request expect(last_response.body).to eq('a type cast is invalid') end it 'performs no additional coercion' do get '/', a: 'true' expect(last_response).to be_successful expect(last_response.body).to eq('String') end end end it 'error on malformed input' do subject.params do requires :int, type: Integer end subject.get '/single' do 'int works' end get '/single', int: '43a' expect(last_response).to be_bad_request expect(last_response.body).to eq('int is invalid') get '/single', int: '43' expect(last_response).to be_successful expect(last_response.body).to eq('int works') end it 'error on malformed input (Array)' do subject.params do requires :ids, type: Array[Integer] end subject.get '/array' do 'array int works' end get 'array', ids: %w[1 2 az] expect(last_response).to be_bad_request expect(last_response.body).to eq('ids is invalid') get 'array', ids: %w[1 2 890] expect(last_response).to be_successful expect(last_response.body).to eq('array int works') end context 'coerces' do context 'json' do let(:headers) { { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } } it 'BigDecimal' do subject.params do requires :bigdecimal, type: BigDecimal end subject.post '/bigdecimal' do "#{params[:bigdecimal].class} #{params[:bigdecimal].to_f}" end post '/bigdecimal', { bigdecimal: 45.1 }.to_json, headers expect(last_response).to be_created expect(last_response.body).to eq('BigDecimal 45.1') end it 'Grape::API::Boolean' do subject.params do requires :boolean, type: Grape::API::Boolean end subject.post '/boolean' do params[:boolean] end post '/boolean', { boolean: 'true' }.to_json, headers expect(last_response).to be_created expect(last_response.body).to eq('true') end end it 'BigDecimal' do subject.params do requires :bigdecimal, coerce: BigDecimal end subject.get '/bigdecimal' do params[:bigdecimal].class end get '/bigdecimal', bigdecimal: '45' expect(last_response).to be_successful expect(last_response.body).to eq('BigDecimal') end it 'Integer' do subject.params do requires :int, coerce: Integer end subject.get '/int' do params[:int].class end get '/int', int: '45' expect(last_response).to be_successful expect(last_response.body).to eq(integer_class_name) end it 'String' do subject.params do requires :string, coerce: String end subject.get '/string' do params[:string].class end get '/string', string: 45 expect(last_response).to be_successful expect(last_response.body).to eq('String') get '/string', string: nil expect(last_response).to be_successful expect(last_response.body).to eq('NilClass') end context 'a custom type' do it 'coerces the given value' do context = self subject.params do requires :uri, coerce: context.secure_uri_only end subject.get '/secure_uri' do params[:uri].class end get 'secure_uri', uri: 'https://www.example.com' expect(last_response).to be_successful expect(last_response.body).to eq('URI::HTTPS') get 'secure_uri', uri: 'http://www.example.com' expect(last_response).to be_bad_request expect(last_response.body).to eq('uri is invalid') end context 'returning the InvalidValue instance when invalid' do let(:custom_type) do Class.new do def self.parse(_val) Grape::Validations::Types::InvalidValue.new('must be unique') end end end it 'uses a custom message added to the invalid value' do type = custom_type subject.params do requires :name, type: type end subject.get '/whatever' do params[:name].class end get 'whatever', name: 'Bob' expect(last_response).to be_bad_request expect(last_response.body).to eq('name must be unique') end end end context 'Array' do it 'Array of Integers' do subject.params do requires :arry, coerce: Array[Integer] end subject.get '/array' do params[:arry][0].class end get '/array', arry: %w[1 2 3] expect(last_response).to be_successful expect(last_response.body).to eq(integer_class_name) end it 'Array of Bools' do subject.params do requires :arry, coerce: Array[Grape::API::Boolean] end subject.get '/array' do params[:arry][0].class end get 'array', arry: [1, 0] expect(last_response).to be_successful expect(last_response.body).to eq('TrueClass') end it 'Array of type implementing parse' do subject.params do requires :uri, type: Array[URI] end subject.get '/uri_array' do params[:uri][0].class end get 'uri_array', uri: ['http://www.google.com'] expect(last_response).to be_successful expect(last_response.body).to eq('URI::HTTP') end it 'Set of type implementing parse' do subject.params do requires :uri, type: Set[URI] end subject.get '/uri_array' do "#{params[:uri].class},#{params[:uri].first.class},#{params[:uri].size}" end get 'uri_array', uri: Array.new(2) { 'http://www.example.com' } expect(last_response).to be_successful expect(last_response.body).to eq('Set,URI::HTTP,1') end it 'Array of a custom type' do context = self subject.params do requires :uri, type: Array[context.secure_uri_only] end subject.get '/secure_uris' do params[:uri].first.class end get 'secure_uris', uri: ['https://www.example.com'] expect(last_response).to be_successful expect(last_response.body).to eq('URI::HTTPS') get 'secure_uris', uri: ['https://www.example.com', 'http://www.example.com'] expect(last_response).to be_bad_request expect(last_response.body).to eq('uri is invalid') end end context 'Set' do it 'Set of Integers' do subject.params do requires :set, coerce: Set[Integer] end subject.get '/set' do params[:set].first.class end get '/set', set: Set.new([1, 2, 3, 4]).to_a expect(last_response).to be_successful expect(last_response.body).to eq(integer_class_name) end it 'Set of Bools' do subject.params do requires :set, coerce: Set[Grape::API::Boolean] end subject.get '/set' do params[:set].first.class end get '/set', set: Set.new([1, 0]).to_a expect(last_response).to be_successful expect(last_response.body).to eq('TrueClass') end end it 'Grape::API::Boolean' do subject.params do requires :boolean, type: Grape::API::Boolean end subject.get '/boolean' do params[:boolean].class end get '/boolean', boolean: 1 expect(last_response).to be_successful expect(last_response.body).to eq('TrueClass') end context 'File' do let(:file) { Rack::Test::UploadedFile.new(__FILE__) } let(:filename) { File.basename(__FILE__).to_s } it 'Rack::Multipart::UploadedFile' do subject.params do requires :file, type: Rack::Multipart::UploadedFile end subject.post '/upload' do params[:file][:filename] end post '/upload', file: file expect(last_response).to be_created expect(last_response.body).to eq(filename) post '/upload', file: 'not a file' expect(last_response).to be_bad_request expect(last_response.body).to eq('file is invalid') end it 'File' do subject.params do requires :file, coerce: File end subject.post '/upload' do params[:file][:filename] end post '/upload', file: file expect(last_response).to be_created expect(last_response.body).to eq(filename) post '/upload', file: 'not a file' expect(last_response).to be_bad_request expect(last_response.body).to eq('file is invalid') post '/upload', file: { filename: 'fake file', tempfile: '/etc/passwd' } expect(last_response).to be_bad_request expect(last_response.body).to eq('file is invalid') end it 'collection' do subject.params do requires :files, type: Array[File] end subject.post '/upload' do params[:files].first[:filename] end post '/upload', files: [file] expect(last_response).to be_created expect(last_response.body).to eq(filename) end end it 'Nests integers' do subject.params do requires :integers, type: Hash do requires :int, coerce: Integer end end subject.get '/int' do params[:integers][:int].class end get '/int', integers: { int: '45' } expect(last_response).to be_successful expect(last_response.body).to eq(integer_class_name) end context 'nil values' do context 'primitive types' do Grape::Validations::Types::PRIMITIVES.each do |type| it 'respects the nil value' do subject.params do requires :param, type: type end subject.get '/nil_value' do params[:param].class end get '/nil_value', param: nil expect(last_response).to be_successful expect(last_response.body).to eq('NilClass') end end end context 'structures types' do Grape::Validations::Types::STRUCTURES.each do |type| it 'respects the nil value' do subject.params do requires :param, type: type end subject.get '/nil_value' do params[:param].class end get '/nil_value', param: nil expect(last_response).to be_successful expect(last_response.body).to eq('NilClass') end end end context 'special types' do Grape::Validations::Types::SPECIAL.each_key do |type| it 'respects the nil value' do subject.params do requires :param, type: type end subject.get '/nil_value' do params[:param].class end get '/nil_value', param: nil expect(last_response).to be_successful expect(last_response.body).to eq('NilClass') end end context 'variant-member-type collections' do [ Array[Integer, String], [Integer, String, Array[Integer, String]] ].each do |type| it 'respects the nil value' do subject.params do requires :param, type: type end subject.get '/nil_value' do params[:param].class end get '/nil_value', param: nil expect(last_response).to be_successful expect(last_response.body).to eq('NilClass') end end end end end context 'empty string' do context 'primitive types' do (Grape::Validations::Types::PRIMITIVES - [String]).each do |type| it "is coerced to nil for type #{type}" do subject.params do requires :param, type: type end subject.get '/empty_string' do params[:param].class end get '/empty_string', param: '' expect(last_response).to be_successful expect(last_response.body).to eq('NilClass') end end it 'is not coerced to nil for type String' do subject.params do requires :param, type: String end subject.get '/empty_string' do params[:param].class end get '/empty_string', param: '' expect(last_response).to be_successful expect(last_response.body).to eq('String') end end context 'structures types' do (Grape::Validations::Types::STRUCTURES - [Hash]).each do |type| it "is coerced to nil for type #{type}" do subject.params do requires :param, type: type end subject.get '/empty_string' do params[:param].class end get '/empty_string', param: '' expect(last_response).to be_successful expect(last_response.body).to eq('NilClass') end end end context 'special types' do (Grape::Validations::Types::SPECIAL.keys - [File, Rack::Multipart::UploadedFile]).each do |type| it "is coerced to nil for type #{type}" do subject.params do requires :param, type: type end subject.get '/empty_string' do params[:param].class end get '/empty_string', param: '' expect(last_response).to be_successful expect(last_response.body).to eq('NilClass') end end context 'variant-member-type collections' do [ Array[Integer, String], [Integer, String, Array[Integer, String]] ].each do |type| it "is coerced to nil for type #{type}" do subject.params do requires :param, type: type end subject.get '/empty_string' do params[:param].class end get '/empty_string', param: '' expect(last_response).to be_successful expect(last_response.body).to eq('NilClass') end end end end end end context 'using coerce_with' do it 'parses parameters with Array type' do subject.params do requires :values, type: Array, coerce_with: ->(val) { val.split(/\s+/).map(&:to_i) } end subject.get '/ints' do params[:values] end get '/ints', values: '1 2 3 4' expect(last_response).to be_successful expect(JSON.parse(last_response.body)).to eq([1, 2, 3, 4]) get '/ints', values: 'a b c d' expect(last_response).to be_successful expect(JSON.parse(last_response.body)).to eq([0, 0, 0, 0]) end it 'parses parameters with Array[String] type' do subject.params do requires :values, type: Array[String], coerce_with: ->(val) { val.split(/\s+/) } end subject.get '/strings' do params[:values] end get '/strings', values: '1 2 3 4' expect(last_response).to be_successful expect(JSON.parse(last_response.body)).to eq(%w[1 2 3 4]) get '/strings', values: 'a b c d' expect(last_response).to be_successful expect(JSON.parse(last_response.body)).to eq(%w[a b c d]) end it 'parses parameters with Array[Array[String]] type and coerce_with' do subject.params do requires :values, type: Array[Array[String]], coerce_with: ->(val) { val.is_a?(String) ? [val.split(',').map(&:strip)] : val } end subject.post '/coerce_nested_strings' do params[:values] end post '/coerce_nested_strings', Grape::Json.dump(values: 'a,b,c,d'), 'CONTENT_TYPE' => 'application/json' expect(last_response).to be_created expect(JSON.parse(last_response.body)).to eq([%w[a b c d]]) post '/coerce_nested_strings', Grape::Json.dump(values: [%w[a c], %w[b]]), 'CONTENT_TYPE' => 'application/json' expect(last_response).to be_created expect(JSON.parse(last_response.body)).to eq([%w[a c], %w[b]]) post '/coerce_nested_strings', Grape::Json.dump(values: [[]]), 'CONTENT_TYPE' => 'application/json' expect(last_response).to be_created expect(JSON.parse(last_response.body)).to eq([[]]) post '/coerce_nested_strings', Grape::Json.dump(values: [['a', { bar: 0 }], ['b']]), 'CONTENT_TYPE' => 'application/json' expect(last_response).to be_bad_request end it 'parses parameters with Array[Integer] type' do subject.params do requires :values, type: Array[Integer], coerce_with: ->(val) { val.split(/\s+/).map(&:to_i) } end subject.get '/ints' do params[:values] end get '/ints', values: '1 2 3 4' expect(last_response).to be_successful expect(JSON.parse(last_response.body)).to eq([1, 2, 3, 4]) get '/ints', values: 'a b c d' expect(last_response).to be_successful expect(JSON.parse(last_response.body)).to eq([0, 0, 0, 0]) end it 'parses parameters even if type is valid' do subject.params do requires :values, type: Array, coerce_with: ->(array) { array.map { |val| val.to_i + 1 } } end subject.get '/ints' do params[:values] end get '/ints', values: [1, 2, 3, 4] expect(last_response).to be_successful expect(JSON.parse(last_response.body)).to eq([2, 3, 4, 5]) get '/ints', values: %w[a b c d] expect(last_response).to be_successful expect(JSON.parse(last_response.body)).to eq([1, 1, 1, 1]) end context 'Array type and coerce_with should' do before do subject.params do optional :arr, type: Array, coerce_with: (lambda do |val| if val.nil? [] else val end end) end subject.get '/' do params[:arr].class.to_s end end it 'coerce nil value to array' do get '/', arr: nil expect(last_response).to be_successful expect(last_response.body).to eq('Array') end it 'not coerce missing field' do get '/' expect(last_response).to be_successful expect(last_response.body).to eq('NilClass') end it 'coerce array as array' do get '/', arr: [] expect(last_response).to be_successful expect(last_response.body).to eq('Array') end end it 'uses parse where available' do subject.params do requires :ints, type: Array, coerce_with: JSON do requires :i, type: Integer requires :j end end subject.get '/ints' do ints = params[:ints].first 'coercion works' if ints[:i] == 1 && ints[:j] == '2' end get '/ints', ints: [{ i: 1, j: '2' }] expect(last_response).to be_bad_request expect(last_response.body).to eq('ints is invalid') get '/ints', ints: '{"i":1,"j":"2"}' expect(last_response).to be_bad_request expect(last_response.body).to eq('ints is invalid') get '/ints', ints: '[{"i":"1","j":"2"}]' expect(last_response).to be_successful expect(last_response.body).to eq('coercion works') end it 'accepts any callable' do subject.params do requires :ints, type: Hash, coerce_with: JSON.method(:parse) do requires :int, type: Integer, coerce_with: ->(val) { val == 'three' ? 3 : val } end end subject.get '/ints' do params[:ints][:int] end get '/ints', ints: '{"int":"3"}' expect(last_response).to be_bad_request expect(last_response.body).to eq('ints[int] is invalid') get '/ints', ints: '{"int":"three"}' expect(last_response).to be_successful expect(last_response.body).to eq('3') get '/ints', ints: '{"int":3}' expect(last_response).to be_successful expect(last_response.body).to eq('3') end context 'Integer type and coerce_with should' do before do subject.params do optional :int, type: Integer, coerce_with: (lambda do |val| if val.nil? 0 else val.to_i end end) end subject.get '/' do params[:int].class.to_s end end it 'coerce nil value to integer' do get '/', int: nil expect(last_response).to be_successful expect(last_response.body).to eq('Integer') end it 'not coerce missing field' do get '/' expect(last_response).to be_successful expect(last_response.body).to eq('NilClass') end it 'coerce integer as integer' do get '/', int: 1 expect(last_response).to be_successful expect(last_response.body).to eq('Integer') end end context 'Integer type and coerce_with potentially returning nil' do before do subject.params do requires :int, type: Integer, coerce_with: (lambda do |val| case val when '0' nil when /^-?\d+$/ val.to_i else val end end) end subject.get '/' do params[:int].class.to_s end end it 'accepts value that coerces to nil' do get '/', int: '0' expect(last_response).to be_successful expect(last_response.body).to eq('NilClass') end it 'coerces to Integer' do get '/', int: '1' expect(last_response).to be_successful expect(last_response.body).to eq('Integer') end it 'returns invalid value if coercion returns a wrong type' do get '/', int: 'lol' expect(last_response).to be_bad_request expect(last_response.body).to eq('int is invalid') end end it 'must be supplied with :type or :coerce' do expect do subject.params do requires :ints, coerce_with: JSON end end.to raise_error(ArgumentError) end end context 'first-class JSON' do it 'parses objects, hashes, and arrays' do subject.params do requires :splines, type: JSON do requires :x, type: Integer, values: [1, 2, 3] optional :ints, type: Array[Integer] optional :obj, type: Hash do optional :y end end end subject.get '/' do if params[:splines].is_a? Hash params[:splines][:obj][:y] elsif params[:splines].any? { |s| s.key? :obj } 'arrays work' end end get '/', splines: '{"x":1,"ints":[1,2,3],"obj":{"y":"woof"}}' expect(last_response).to be_successful expect(last_response.body).to eq('woof') get '/', splines: { x: 1, ints: [1, 2, 3], obj: { y: 'woof' } } expect(last_response).to be_successful expect(last_response.body).to eq('woof') get '/', splines: '[{"x":2,"ints":[]},{"x":3,"ints":[4],"obj":{"y":"quack"}}]' expect(last_response).to be_successful expect(last_response.body).to eq('arrays work') get '/', splines: [{ x: 2, ints: [5] }, { x: 3, ints: [4], obj: { y: 'quack' } }] expect(last_response).to be_successful expect(last_response.body).to eq('arrays work') get '/', splines: '{"x":4,"ints":[2]}' expect(last_response).to be_bad_request expect(last_response.body).to eq('splines[x] does not have a valid value') get '/', splines: { x: 4, ints: [2] } expect(last_response).to be_bad_request expect(last_response.body).to eq('splines[x] does not have a valid value') get '/', splines: '[{"x":1,"ints":[]},{"x":4,"ints":[]}]' expect(last_response).to be_bad_request expect(last_response.body).to eq('splines[x] does not have a valid value') get '/', splines: [{ x: 1, ints: [5] }, { x: 4, ints: [6] }] expect(last_response).to be_bad_request expect(last_response.body).to eq('splines[x] does not have a valid value') end it 'works when declared optional' do subject.params do optional :splines, type: JSON do requires :x, type: Integer, values: [1, 2, 3] optional :ints, type: Array[Integer] optional :obj, type: Hash do optional :y end end end subject.get '/' do if params[:splines].is_a? Hash params[:splines][:obj][:y] elsif params[:splines].any? { |s| s.key? :obj } 'arrays work' end end get '/', splines: '{"x":1,"ints":[1,2,3],"obj":{"y":"woof"}}' expect(last_response).to be_successful expect(last_response.body).to eq('woof') get '/', splines: '[{"x":2,"ints":[]},{"x":3,"ints":[4],"obj":{"y":"quack"}}]' expect(last_response).to be_successful expect(last_response.body).to eq('arrays work') get '/', splines: '{"x":4,"ints":[2]}' expect(last_response).to be_bad_request expect(last_response.body).to eq('splines[x] does not have a valid value') get '/', splines: '[{"x":1,"ints":[]},{"x":4,"ints":[]}]' expect(last_response).to be_bad_request expect(last_response.body).to eq('splines[x] does not have a valid value') end it 'accepts Array[JSON] shorthand' do subject.params do requires :splines, type: Array[JSON] do requires :x, type: Integer, values: [1, 2, 3] requires :y end end subject.get '/' do params[:splines].first[:y].class.to_s spline = params[:splines].first "#{spline[:x].class}.#{spline[:y].class}" end get '/', splines: '{"x":"1","y":"woof"}' expect(last_response).to be_successful expect(last_response.body).to eq("#{integer_class_name}.String") get '/', splines: '[{"x":1,"y":2},{"x":1,"y":"quack"}]' expect(last_response).to be_successful expect(last_response.body).to eq("#{integer_class_name}.#{integer_class_name}") get '/', splines: '{"x":"4","y":"woof"}' expect(last_response).to be_bad_request expect(last_response.body).to eq('splines[x] does not have a valid value') get '/', splines: '[{"x":"4","y":"woof"}]' expect(last_response).to be_bad_request expect(last_response.body).to eq('splines[x] does not have a valid value') end it "doesn't make sense using coerce_with" do expect do subject.params do requires :bad, type: JSON, coerce_with: JSON do requires :x end end end.to raise_error(ArgumentError) expect do subject.params do requires :bad, type: Array[JSON], coerce_with: JSON do requires :x end end end.to raise_error(ArgumentError) end end context 'multiple types' do it 'coerces to first possible type' do subject.params do requires :a, types: [Grape::API::Boolean, Integer, String] end subject.get '/' do params[:a].class.to_s end get '/', a: 'true' expect(last_response).to be_successful expect(last_response.body).to eq('TrueClass') get '/', a: '5' expect(last_response).to be_successful expect(last_response.body).to eq(integer_class_name) get '/', a: 'anything else' expect(last_response).to be_successful expect(last_response.body).to eq('String') end it 'fails when no coercion is possible' do subject.params do requires :a, types: [Grape::API::Boolean, Integer] end subject.get '/' do params[:a].class.to_s end get '/', a: true expect(last_response).to be_successful
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
true
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/validators/length_validator_spec.rb
spec/grape/validations/validators/length_validator_spec.rb
# frozen_string_literal: true describe Grape::Validations::Validators::LengthValidator do let_it_be(:app) do Class.new(Grape::API) do params do requires :list, length: { min: 2, max: 3 } end post 'with_min_max' do end params do requires :list, type: [Integer], length: { min: 2 } end post 'with_min_only' do end params do requires :list, type: [Integer], length: { max: 3 } end post 'with_max_only' do end params do requires :list, type: Integer, length: { max: 3 } end post 'type_is_not_array' do end params do requires :list, type: Hash, length: { max: 3 } end post 'type_supports_length' do end params do requires :list, type: [Integer], length: { min: -3 } end post 'negative_min' do end params do requires :list, type: [Integer], length: { max: -3 } end post 'negative_max' do end params do requires :list, type: [Integer], length: { min: 2.5 } end post 'float_min' do end params do requires :list, type: [Integer], length: { max: 2.5 } end post 'float_max' do end params do requires :list, type: [Integer], length: { min: 15, max: 3 } end post 'min_greater_than_max' do end params do requires :list, type: [Integer], length: { min: 3, max: 3 } end post 'min_equal_to_max' do end params do requires :list, type: [JSON], length: { min: 0 } end post 'zero_min' do end params do requires :list, type: [JSON], length: { max: 0 } end post 'zero_max' do end params do requires :list, type: [Integer], length: { min: 2, message: 'not match' } end post '/custom-message' do end params do requires :code, length: { is: 2 } end post 'is' do end params do requires :code, length: { is: -2 } end post 'negative_is' do end params do requires :code, length: { is: 2, max: 10 } end post 'is_with_max' do end end end describe '/with_min_max' do context 'when length is within limits' do it do post '/with_min_max', list: [1, 2] expect(last_response.status).to eq(201) expect(last_response.body).to eq('') end end context 'when length is exceeded' do it do post '/with_min_max', list: [1, 2, 3, 4, 5] expect(last_response.status).to eq(400) expect(last_response.body).to eq('list is expected to have length within 2 and 3') end end context 'when length is less than minimum' do it do post '/with_min_max', list: [1] expect(last_response.status).to eq(400) expect(last_response.body).to eq('list is expected to have length within 2 and 3') end end end describe '/with_max_only' do context 'when length is less than limits' do it do post '/with_max_only', list: [1, 2] expect(last_response.status).to eq(201) expect(last_response.body).to eq('') end end context 'when length is exceeded' do it do post '/with_max_only', list: [1, 2, 3, 4, 5] expect(last_response.status).to eq(400) expect(last_response.body).to eq('list is expected to have length less than or equal to 3') end end end describe '/with_min_only' do context 'when length is greater than limit' do it do post '/with_min_only', list: [1, 2] expect(last_response.status).to eq(201) expect(last_response.body).to eq('') end end context 'when length is less than limit' do it do post '/with_min_only', list: [1] expect(last_response.status).to eq(400) expect(last_response.body).to eq('list is expected to have length greater than or equal to 2') end end end describe '/zero_min' do context 'when length is equal to the limit' do it do post '/zero_min', list: '[]' expect(last_response.status).to eq(201) expect(last_response.body).to eq('') end end context 'when length is greater than limit' do it do post '/zero_min', list: [{ key: 'value' }] expect(last_response.status).to eq(201) expect(last_response.body).to eq('') end end end describe '/zero_max' do context 'when length is within the limit' do it do post '/zero_max', list: '[]' expect(last_response.status).to eq(201) expect(last_response.body).to eq('') end end context 'when length is greater than limit' do it do post '/zero_max', list: [{ key: 'value' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('list is expected to have length less than or equal to 0') end end end describe '/type_is_not_array' do context 'does not raise an error' do it do expect do post 'type_is_not_array', list: 12 end.not_to raise_error end end end describe '/type_supports_length' do context 'when length is within limits' do it do post 'type_supports_length', list: { key: 'value' } expect(last_response.status).to eq(201) expect(last_response.body).to eq('') end end context 'when length exceeds the limit' do it do post 'type_supports_length', list: { key: 'value', key1: 'value', key3: 'value', key4: 'value' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('list is expected to have length less than or equal to 3') end end end describe '/negative_min' do context 'when min is negative' do it do expect { post 'negative_min', list: [12] }.to raise_error(ArgumentError, 'min must be an integer greater than or equal to zero') end end end describe '/negative_max' do 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 describe '/float_min' do context 'when min is not an integer' do it do expect { post 'float_min', list: [12] }.to raise_error(ArgumentError, 'min must be an integer greater than or equal to zero') end end end describe '/float_max' do context 'when max is not an integer' do it do expect { post 'float_max', list: [12] }.to raise_error(ArgumentError, 'max must be an integer greater than or equal to zero') end end end describe '/min_greater_than_max' do context 'raises an error' do it do expect { post 'min_greater_than_max', list: [1, 2] }.to raise_error(ArgumentError, 'min 15 cannot be greater than max 3') end end end describe '/min_equal_to_max' do context 'when array meets expectations' do it do post 'min_equal_to_max', list: [1, 2, 3] expect(last_response.status).to eq(201) expect(last_response.body).to eq('') end end context 'when array is less than min' do it do post 'min_equal_to_max', list: [1, 2] expect(last_response.status).to eq(400) expect(last_response.body).to eq('list is expected to have length within 3 and 3') end end context 'when array is greater than max' do it do post 'min_equal_to_max', list: [1, 2, 3, 4] expect(last_response.status).to eq(400) expect(last_response.body).to eq('list is expected to have length within 3 and 3') end end end describe '/custom-message' do context 'is within limits' do it do post '/custom-message', list: [1, 2, 3] expect(last_response.status).to eq(201) expect(last_response.body).to eq('') end end context 'is outside limit' do it do post '/custom-message', list: [1] expect(last_response.status).to eq(400) expect(last_response.body).to eq('list not match') end end end describe '/is' do context 'when length is exact' do it do post 'is', code: 'ZZ' expect(last_response.status).to eq(201) expect(last_response.body).to eq('') end end context 'when length exceeds the limit' do it do post 'is', code: 'aze' expect(last_response.status).to eq(400) expect(last_response.body).to eq('code is expected to have length exactly equal to 2') end end context 'when length is less than the limit' do it do post 'is', code: 'a' expect(last_response.status).to eq(400) expect(last_response.body).to eq('code is expected to have length exactly equal to 2') end end context 'when length is zero' do it do post 'is', code: '' expect(last_response.status).to eq(400) expect(last_response.body).to eq('code is expected to have length exactly equal to 2') end end end describe '/negative_is' do context 'when `is` is negative' do it do expect { post 'negative_is', code: 'ZZ' }.to raise_error(ArgumentError, 'is must be an integer greater than zero') end end end describe '/is_with_max' do context 'when `is` is combined with max' do it do expect { post 'is_with_max', code: 'ZZ' }.to raise_error(ArgumentError, 'is cannot be combined with min or max') end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/validators/mutually_exclusive_spec.rb
spec/grape/validations/validators/mutually_exclusive_spec.rb
# frozen_string_literal: true describe Grape::Validations::Validators::MutuallyExclusiveValidator do let_it_be(:app) do Class.new(Grape::API) do rescue_from Grape::Exceptions::ValidationErrors do |e| error!(e.errors.transform_keys! { |key| key.join(',') }, 400) end params do optional :beer optional :wine optional :grapefruit mutually_exclusive :beer, :wine, :grapefruit end post do end params do optional :beer optional :wine optional :grapefruit optional :other mutually_exclusive :beer, :wine, :grapefruit end post 'mixed-params' do end params do optional :beer optional :wine optional :grapefruit mutually_exclusive :beer, :wine, :grapefruit, message: 'you should not mix beer and wine' end post '/custom-message' do end params do requires :item, type: Hash do optional :beer optional :wine optional :grapefruit mutually_exclusive :beer, :wine, :grapefruit end end post '/nested-hash' do end params do optional :item, type: Hash do optional :beer optional :wine optional :grapefruit mutually_exclusive :beer, :wine, :grapefruit end end post '/nested-optional-hash' do end params do requires :items, type: Array do optional :beer optional :wine optional :grapefruit mutually_exclusive :beer, :wine, :grapefruit end end post '/nested-array' do end params do requires :items, type: Array do requires :nested_items, type: Array do optional :beer, :wine, :grapefruit, type: Grape::API::Boolean mutually_exclusive :beer, :wine, :grapefruit end end end post '/deeply-nested-array' do end end end describe '#validate!' do subject(:validate) { post path, params } context 'when all mutually exclusive params are present' do let(:path) { '/' } let(:params) { { beer: true, wine: true, grapefruit: true } } it 'returns a validation error' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'beer,wine,grapefruit' => ['are mutually exclusive'] ) end context 'mixed with other params' do let(:path) { '/mixed-params' } let(:params) { { beer: true, wine: true, grapefruit: true, other: true } } it 'returns a validation error' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'beer,wine,grapefruit' => ['are mutually exclusive'] ) end end end context 'when a subset of mutually exclusive params are present' do let(:path) { '/' } let(:params) { { beer: true, grapefruit: true } } it 'returns a validation error' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'beer,grapefruit' => ['are mutually exclusive'] ) end end context 'when custom message is specified' do let(:path) { '/custom-message' } let(:params) { { beer: true, wine: true } } it 'returns a validation error' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'beer,wine' => ['you should not mix beer and wine'] ) end end context 'when no mutually exclusive params are present' do let(:path) { '/' } let(:params) { { beer: true, somethingelse: true } } it 'does not return a validation error' do validate expect(last_response.status).to eq 201 end end context 'when mutually exclusive params are nested inside required hash' do let(:path) { '/nested-hash' } let(:params) { { item: { beer: true, wine: true } } } it 'returns a validation error with full names of the params' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'item[beer],item[wine]' => ['are mutually exclusive'] ) end end context 'when mutually exclusive params are nested inside optional hash' do let(:path) { '/nested-optional-hash' } context 'when params are passed' do let(:params) { { item: { beer: true, wine: true } } } it 'returns a validation error with full names of the params' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'item[beer],item[wine]' => ['are mutually exclusive'] ) end end context 'when params are empty' do let(:params) { {} } it 'does not return a validation error' do validate expect(last_response.status).to eq 201 end end end context 'when mutually exclusive params are nested inside array' do let(:path) { '/nested-array' } let(:params) { { items: [{ beer: true, wine: true }, { wine: true, grapefruit: true }] } } it 'returns a validation error with full names of the params' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'items[0][beer],items[0][wine]' => ['are mutually exclusive'], 'items[1][wine],items[1][grapefruit]' => ['are mutually exclusive'] ) end end context 'when mutually exclusive params are deeply nested' do let(:path) { '/deeply-nested-array' } let(:params) { { items: [{ nested_items: [{ beer: true, wine: true }] }] } } it 'returns a validation error with full names of the params' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'items[0][nested_items][0][beer],items[0][nested_items][0][wine]' => ['are mutually exclusive'] ) end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/validators/values_validator_spec.rb
spec/grape/validations/validators/values_validator_spec.rb
# frozen_string_literal: true describe Grape::Validations::Validators::ValuesValidator do let(:values_model) do Class.new do class << self def values @values ||= [] [default_values + @values].flatten.uniq end def add_value(value) @values ||= [] @values << value end def excepts @excepts ||= [] [default_excepts + @excepts].flatten.uniq end def add_except(except) @excepts ||= [] @excepts << except end def include?(value) values.include?(value) end def even?(value) value.to_i.even? end private def default_values %w[valid-type1 valid-type2 valid-type3].freeze end def default_excepts %w[invalid-type1 invalid-type2 invalid-type3].freeze end end end end let(:app) do Class.new(Grape::API) do default_format :json resources :custom_message do params do requires :type, values: { value: ValuesModel.values, message: 'value does not include in values' } end get '/' do { type: params[:type] } end params do optional :type, values: { value: -> { ValuesModel.values }, message: 'value does not include in values' }, default: 'valid-type2' end get '/lambda' do { type: params[:type] } end end params do requires :type, values: ValuesModel.values end get '/' do { type: params[:type] } end params do requires :type, values: [] end get '/empty' params do optional :type, values: { value: ValuesModel.values }, default: 'valid-type2' end get '/default/hash/valid' do { type: params[:type] } end params do optional :type, values: ValuesModel.values, default: 'valid-type2' end get '/default/valid' do { type: params[:type] } end params do optional :type, values: -> { ValuesModel.values }, default: 'valid-type2' end get '/lambda' do { type: params[:type] } end params do optional :type, type: Integer, values: 1.. end get '/endless' do { type: params[:type] } end params do requires :type, values: ->(v) { ValuesModel.include? v } end get '/lambda_val' do { type: params[:type] } end params do requires :number, type: Integer, values: ->(v) { v > 0 } end get '/lambda_int_val' do { number: params[:number] } end params do requires :type, values: -> { [] } end get '/empty_lambda' params do optional :type, values: ValuesModel.values, default: -> { ValuesModel.values.sample } end get '/default_lambda' do { type: params[:type] } end params do optional :type, values: -> { ValuesModel.values }, default: -> { ValuesModel.values.sample } end get '/default_and_values_lambda' do { type: params[:type] } end params do optional :type, type: Grape::API::Boolean, desc: 'A boolean', values: [true] end get '/values/optional_boolean' do { type: params[:type] } end params do requires :type, type: Integer, desc: 'An integer', values: [10, 11], default: 10 end get '/values/coercion' do { type: params[:type] } end params do requires :type, type: Array[Integer], desc: 'An integer', values: [10, 11], default: 10 end get '/values/array_coercion' do { type: params[:type] } end params do optional :optional, type: Array do requires :type, values: %w[a b] end end get '/optional_with_required_values' params do requires :type, type: Integer, values: 1..5, except_values: [3] end get '/mixed/value/except' do { type: params[:type] } end params do optional :optional, type: Array[String], values: %w[a b c] end put '/optional_with_array_of_string_values' params do requires :type, values: ->(v) { ValuesModel.include? v } end get '/proc' do { type: params[:type] } end params do requires :type, values: { value: ->(v) { ValuesModel.include? v }, message: 'failed check' } end get '/proc/message' params do requires :number, values: { value: ->(v) { ValuesModel.even? v }, message: 'must be even' } end get '/proc/custom_message' do { message: 'success' } end params do requires :input_one, :input_two, values: { value: ->(v1, v2) { v1 + v2 > 10 } } end get '/proc/arity2' params do optional :name, type: String, values: %w[a b], allow_blank: true end get '/allow_blank' params do with(type: String) do requires :type, values: ValuesModel.values end end get 'values_wrapped_by_with_block' end end before do stub_const('ValuesModel', values_model) end describe '#bad encoding' do let(:app) do Class.new(Grape::API) do default_format :json params do requires :type, type: String, values: %w[a b] end get '/bad_encoding' end end context 'when value as bad encoding' do it 'does not raise an error' do expect { get '/bad_encoding', type: "Hello \x80" }.not_to raise_error end end end context 'with a custom validation message' do it 'allows a valid value for a parameter' do get('/custom_message', type: 'valid-type1') expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: 'valid-type1' }.to_json) end it 'does not allow an invalid value for a parameter' do get('/custom_message', type: 'invalid-type') expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type value does not include in values' }.to_json) end it 'validates against values in a proc' do ValuesModel.add_value('valid-type4') get('/custom_message/lambda', type: 'valid-type4') expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: 'valid-type4' }.to_json) end it 'does not allow an invalid value for a parameter using lambda' do get('/custom_message/lambda', type: 'invalid-type') expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type value does not include in values' }.to_json) end end it 'allows a valid value for a parameter' do get('/', type: 'valid-type1') expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: 'valid-type1' }.to_json) end it 'does not allow an invalid value for a parameter' do get('/', type: 'invalid-type') expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type does not have a valid value' }.to_json) end it 'rejects all values if values is an empty array' do get('/empty', type: 'invalid-type') expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type does not have a valid value' }.to_json) end context 'nil value for a parameter' do it 'does not allow for root params scope' do get('/', type: nil) expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type does not have a valid value' }.to_json) end it 'allows for a required param in child scope' do get('/optional_with_required_values') expect(last_response.status).to eq 200 end it 'accepts for an optional param with a list of values' do put('/optional_with_array_of_string_values', optional: nil) expect(last_response.status).to eq 200 end end it 'allows a valid default value' do get('/default/valid') expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: 'valid-type2' }.to_json) end it 'allows a valid default value' do get('/default/hash/valid') expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: 'valid-type2' }.to_json) end it 'allows a proc for values' do get('/lambda', type: 'valid-type1') expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: 'valid-type1' }.to_json) end it 'does not validate updated values without proc' do app # Instantiate with the existing values. ValuesModel.add_value('valid-type4') get('/', type: 'valid-type4') expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type does not have a valid value' }.to_json) end it 'validates against values in a proc' do ValuesModel.add_value('valid-type4') get('/lambda', type: 'valid-type4') expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: 'valid-type4' }.to_json) end it 'does not allow an invalid value for a parameter using lambda' do get('/lambda', type: 'invalid-type') expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type does not have a valid value' }.to_json) end it 'validates against values in an endless range' do get('/endless', type: 10) expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: 10 }.to_json) end it 'does not allow an invalid value for a parameter using an endless range' do get('/endless', type: 0) expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type does not have a valid value' }.to_json) end it 'does not allow non-numeric string value for int value using lambda' do get('/lambda_int_val', number: 'foo') expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'number is invalid, number does not have a valid value' }.to_json) end it 'does not allow nil for int value using lambda' do get('/lambda_int_val', number: nil) expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'number does not have a valid value' }.to_json) end it 'allows numeric string for int value using lambda' do get('/lambda_int_val', number: '3') expect(last_response.status).to eq 200 expect(last_response.body).to eq({ number: 3 }.to_json) end it 'allows value using lambda' do get('/lambda_val', type: 'valid-type1') expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: 'valid-type1' }.to_json) end it 'does not allow invalid value using lambda' do get('/lambda_val', type: 'invalid-type') expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type does not have a valid value' }.to_json) end it 'validates against an empty array in a proc' do get('/empty_lambda', type: 'any') expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type does not have a valid value' }.to_json) end it 'validates default value from proc' do get('/default_lambda') expect(last_response.status).to eq 200 end it 'validates default value from proc against values in a proc' do get('/default_and_values_lambda') expect(last_response.status).to eq 200 end it 'raises IncompatibleOptionValues on an invalid default value from proc' do subject = Class.new(Grape::API) expect do subject.params { optional :type, values: %w[valid-type1 valid-type2 valid-type3], default: "#{ValuesModel.values.sample}_invalid" } end.to raise_error Grape::Exceptions::IncompatibleOptionValues end it 'raises IncompatibleOptionValues on an invalid default value' do subject = Class.new(Grape::API) expect do subject.params { optional :type, values: %w[valid-type1 valid-type2 valid-type3], default: 'invalid-type' } end.to raise_error Grape::Exceptions::IncompatibleOptionValues end it 'raises IncompatibleOptionValues when type is incompatible with values array' do subject = Class.new(Grape::API) expect do subject.params { optional :type, values: %w[valid-type1 valid-type2 valid-type3], type: Symbol } end.to raise_error Grape::Exceptions::IncompatibleOptionValues end context 'boolean values' do it 'allows a value from the list' do get('/values/optional_boolean', type: true) expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: true }.to_json) end it 'rejects a value which is not in the list' do get('/values/optional_boolean', type: false) expect(last_response.body).to eq({ error: 'type does not have a valid value' }.to_json) end end it 'allows values to be a kind of the coerced type not just an instance of it' do get('/values/coercion', type: 10) expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: 10 }.to_json) end it 'allows values to be a kind of the coerced type in an array' do get('/values/array_coercion', type: [10]) expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: [10] }.to_json) end it 'raises IncompatibleOptionValues when values contains a value that is not a kind of the type' do subject = Class.new(Grape::API) expect do subject.params { requires :type, values: [10.5, 11], type: Integer } end.to raise_error Grape::Exceptions::IncompatibleOptionValues end it 'raises IncompatibleOptionValues when except contains a value that is not a kind of the type' do subject = Class.new(Grape::API) expect do subject.params { requires :type, except_values: [10.5, 11], type: Integer } end.to raise_error Grape::Exceptions::IncompatibleOptionValues end it 'allows a blank value when the allow_blank option is true' do get 'allow_blank', name: nil expect(last_response.status).to eq(200) get 'allow_blank', name: '' expect(last_response.status).to eq(200) end context 'with a lambda values' do subject do Class.new(Grape::API) do params do optional :type, type: String, values: -> { [SecureRandom.uuid] }, default: -> { SecureRandom.uuid } end get '/random_values' end end def app subject end before do expect(SecureRandom).to receive(:uuid).and_return('foo').once end it 'only evaluates values dynamically with each request' do get '/random_values', type: 'foo' expect(last_response.status).to eq 200 end it 'chooses default' do get '/random_values' expect(last_response.status).to eq 200 end end context 'with a range of values' do subject(:app) do Class.new(Grape::API) do params do optional :value, type: Float, values: 0.0..10.0 end get '/value' do { value: params[:value] }.to_json end params do optional :values, type: Array[Float], values: 0.0..10.0 end get '/values' do { values: params[:values] }.to_json end end end it 'allows a single value inside of the range' do get('/value', value: 5.2) expect(last_response.status).to eq 200 expect(last_response.body).to eq({ value: 5.2 }.to_json) end it 'allows an array of values inside of the range' do get('/values', values: [8.6, 7.5, 3, 0.9]) expect(last_response.status).to eq 200 expect(last_response.body).to eq({ values: [8.6, 7.5, 3.0, 0.9] }.to_json) end it 'rejects a single value outside the range' do get('/value', value: 'a') expect(last_response.status).to eq 400 expect(last_response.body).to eq('value is invalid, value does not have a valid value') end it 'rejects an array of values if any of them are outside the range' do get('/values', values: [8.6, 75, 3, 0.9]) expect(last_response.status).to eq 400 expect(last_response.body).to eq('values does not have a valid value') end end context 'with mixed values and excepts' do it 'allows value, but not in except' do get '/mixed/value/except', type: 2 expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: 2 }.to_json) end it 'rejects except' do get '/mixed/value/except', type: 3 expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type has a value not allowed' }.to_json) end it 'rejects outside except and outside value' do get '/mixed/value/except', type: 10 expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type does not have a valid value' }.to_json) end end context 'custom validation using proc' do it 'accepts a single valid value' do get '/proc', type: 'valid-type1' expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: 'valid-type1' }.to_json) end it 'accepts multiple valid values' do get '/proc', type: %w[valid-type1 valid-type3] expect(last_response.status).to eq 200 expect(last_response.body).to eq({ type: %w[valid-type1 valid-type3] }.to_json) end it 'rejects a single invalid value' do get '/proc', type: 'invalid-type1' expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type does not have a valid value' }.to_json) end it 'rejects an invalid value among valid ones' do get '/proc', type: %w[valid-type1 invalid-type1 valid-type3] expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type does not have a valid value' }.to_json) end it 'uses supplied message' do get '/proc/message', type: 'invalid-type1' expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type failed check' }.to_json) end context 'when proc has an arity of 1' do it 'accepts a valid value' do get '/proc/custom_message', number: 4 expect(last_response.status).to eq 200 expect(last_response.body).to eq({ message: 'success' }.to_json) end it 'rejects an invalid value' do get '/proc/custom_message', number: 5 expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'number must be even' }.to_json) end end context 'when arity is > 1' do it 'returns an error status code' do get '/proc/arity2', input_one: 2, input_two: 3 expect(last_response.status).to eq 400 end end end context 'when wrapped by with block' do it 'rejects an invalid value' do get 'values_wrapped_by_with_block' expect(last_response.status).to eq 400 expect(last_response.body).to eq({ error: 'type is missing, type does not have a valid value' }.to_json) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/validators/at_least_one_of_validator_spec.rb
spec/grape/validations/validators/at_least_one_of_validator_spec.rb
# frozen_string_literal: true describe Grape::Validations::Validators::AtLeastOneOfValidator do let_it_be(:app) do Class.new(Grape::API) do rescue_from Grape::Exceptions::ValidationErrors do |e| error!(e.errors.transform_keys! { |key| key.join(',') }, 400) end params do optional :beer, :wine, :grapefruit at_least_one_of :beer, :wine, :grapefruit end post do end params do optional :beer, :wine, :grapefruit, :other at_least_one_of :beer, :wine, :grapefruit end post 'mixed-params' do end params do optional :beer, :wine, :grapefruit at_least_one_of :beer, :wine, :grapefruit, message: 'you should choose something' end post '/custom-message' do end params do requires :item, type: Hash do optional :beer, :wine, :grapefruit at_least_one_of :beer, :wine, :grapefruit, message: 'fail' end end post '/nested-hash' do end params do requires :items, type: Array do optional :beer, :wine, :grapefruit at_least_one_of :beer, :wine, :grapefruit, message: 'fail' end end post '/nested-array' do end params do requires :items, type: Array do requires :nested_items, type: Array do optional :beer, :wine, :grapefruit at_least_one_of :beer, :wine, :grapefruit, message: 'fail' end end end post '/deeply-nested-array' do end end end describe '#validate!' do subject(:validate) { post path, params } context 'when all restricted params are present' do let(:path) { '/' } let(:params) { { beer: true, wine: true, grapefruit: true } } it 'does not return a validation error' do validate expect(last_response.status).to eq 201 end context 'mixed with other params' do let(:path) { '/mixed-params' } let(:params) { { beer: true, wine: true, grapefruit: true, other: true } } it 'does not return a validation error' do validate expect(last_response.status).to eq 201 end end end context 'when a subset of restricted params are present' do let(:path) { '/' } let(:params) { { beer: true, grapefruit: true } } it 'does not return a validation error' do validate expect(last_response.status).to eq 201 end end context 'when none of the restricted params is selected' do let(:path) { '/' } let(:params) { { other: true } } it 'returns a validation error' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'beer,wine,grapefruit' => ['are missing, at least one parameter must be provided'] ) end context 'when custom message is specified' do let(:path) { '/custom-message' } it 'returns a validation error' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'beer,wine,grapefruit' => ['you should choose something'] ) end end end context 'when exactly one of the restricted params is selected' do let(:path) { '/' } let(:params) { { beer: true } } it 'does not return a validation error' do validate expect(last_response.status).to eq 201 end end context 'when restricted params are nested inside hash' do let(:path) { '/nested-hash' } context 'when at least one of them is present' do let(:params) { { item: { beer: true, wine: true } } } it 'does not return a validation error' do validate expect(last_response.status).to eq 201 end end context 'when none of them are present' do let(:params) { { item: { other: true } } } it 'returns a validation error with full names of the params' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'item[beer],item[wine],item[grapefruit]' => ['fail'] ) end end end context 'when restricted params are nested inside array' do let(:path) { '/nested-array' } context 'when at least one of them is present' do let(:params) { { items: [{ beer: true, wine: true }, { grapefruit: true }] } } it 'does not return a validation error' do validate expect(last_response.status).to eq 201 end end context 'when none of them are present' do let(:params) { { items: [{ beer: true, other: true }, { other: true }] } } it 'returns a validation error with full names of the params' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'items[1][beer],items[1][wine],items[1][grapefruit]' => ['fail'] ) end end end context 'when restricted params are deeply nested' do let(:path) { '/deeply-nested-array' } context 'when at least one of them is present' do let(:params) { { items: [{ nested_items: [{ wine: true }] }] } } it 'does not return a validation error' do validate expect(last_response.status).to eq 201 end end context 'when none of them are present' do let(:params) { { items: [{ nested_items: [{ other: true }] }] } } it 'returns a validation error with full names of the params' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'items[0][nested_items][0][beer],items[0][nested_items][0][wine],items[0][nested_items][0][grapefruit]' => ['fail'] ) end end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/validators/presence_validator_spec.rb
spec/grape/validations/validators/presence_validator_spec.rb
# frozen_string_literal: true describe Grape::Validations::Validators::PresenceValidator do subject do Class.new(Grape::API) do format :json end end def app subject end context 'without validation' do before do subject.resource :bacons do get do 'All the bacon' end end end it 'does not validate for any params' do get '/bacons' expect(last_response.status).to eq(200) expect(last_response.body).to eq('All the bacon'.to_json) end end context 'with a custom validation message' do before do subject.resource :requires do params do requires :email, type: String, allow_blank: { value: false, message: 'has no value' }, regexp: { value: /^\S+$/, message: 'format is invalid' }, message: 'is required' end get do 'Hello' end end end it 'requires when missing' do get '/requires' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"email is required, email has no value"}') end it 'requires when empty' do get '/requires', email: '' expect(last_response.body).to eq('{"error":"email has no value, email format is invalid"}') end it 'valid when set' do get '/requires', email: 'bob@example.com' expect(last_response.status).to eq(200) expect(last_response.body).to eq('Hello'.to_json) end end context 'with a required regexp parameter supplied in the POST body' do before do subject.format :json subject.params do requires :id, regexp: /^[0-9]+$/ end subject.post do { ret: params[:id] } end end it 'validates id' do post '/' expect(last_response).to be_bad_request expect(last_response.body).to eq('{"error":"id is missing"}') post '/', { id: 'a56b' }.to_json, 'CONTENT_TYPE' => 'application/json' expect(last_response.body).to eq('{"error":"id is invalid"}') expect(last_response).to be_bad_request post '/', { id: 56 }.to_json, 'CONTENT_TYPE' => 'application/json' expect(last_response.body).to eq('{"ret":56}') expect(last_response).to be_created end end context 'with a required non-empty string' do before do subject.params do requires :email, type: String, allow_blank: false, regexp: /^\S+$/ end subject.get do 'Hello' end end it 'requires when missing' do get '/' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"email is missing, email is empty"}') end it 'requires when empty' do get '/', email: '' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"email is empty, email is invalid"}') end it 'valid when set' do get '/', email: 'bob@example.com' expect(last_response.status).to eq(200) expect(last_response.body).to eq('Hello'.to_json) end end context 'with multiple parameters per requires' do before do subject.params do requires :one, :two end subject.get '/single-requires' do 'Hello' end subject.params do requires :one requires :two end subject.get '/multiple-requires' do 'Hello' end end it 'validates for all defined params' do get '/single-requires' expect(last_response.status).to eq(400) single_requires_error = last_response.body get '/multiple-requires' expect(last_response.status).to eq(400) expect(last_response.body).to eq(single_requires_error) end end context 'with required parameters and no type' do before do subject.params do requires :name, :company end subject.get do 'Hello' end end it 'validates name, company' do get '/' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"name is missing, company is missing"}') get '/', name: 'Bob' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"company is missing"}') get '/', name: 'Bob', company: 'TestCorp' expect(last_response.status).to eq(200) expect(last_response.body).to eq('Hello'.to_json) end end context 'with nested parameters' do before do subject.params do requires :user, type: Hash do requires :first_name requires :last_name end end subject.get '/nested' do 'Nested' end end it 'validates nested parameters' do get '/nested' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"user is missing, user[first_name] is missing, user[last_name] is missing"}') get '/nested', user: { first_name: 'Billy' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"user[last_name] is missing"}') get '/nested', user: { first_name: 'Billy', last_name: 'Bob' } expect(last_response.status).to eq(200) expect(last_response.body).to eq('Nested'.to_json) end end context 'with triply nested required parameters' do before do subject.params do requires :admin, type: Hash do requires :admin_name requires :super, type: Hash do requires :user, type: Hash do requires :first_name requires :last_name end end end end subject.get '/nested_triple' do 'Nested triple' end end it 'validates triple nested parameters' do get '/nested_triple' expect(last_response.status).to eq(400) expect(last_response.body).to include '{"error":"admin is missing' get '/nested_triple', user: { first_name: 'Billy' } expect(last_response.status).to eq(400) expect(last_response.body).to include '{"error":"admin is missing' get '/nested_triple', admin: { super: { first_name: 'Billy' } } expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"admin[admin_name] is missing, admin[super][user] is missing, admin[super][user][first_name] is missing, admin[super][user][last_name] is missing"}') get '/nested_triple', super: { user: { first_name: 'Billy', last_name: 'Bob' } } expect(last_response.status).to eq(400) expect(last_response.body).to include '{"error":"admin is missing' get '/nested_triple', admin: { super: { user: { first_name: 'Billy' } } } expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"admin[admin_name] is missing, admin[super][user][last_name] is missing"}') get '/nested_triple', admin: { admin_name: 'admin', super: { user: { first_name: 'Billy' } } } expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"admin[super][user][last_name] is missing"}') get '/nested_triple', admin: { admin_name: 'admin', super: { user: { first_name: 'Billy', last_name: 'Bob' } } } expect(last_response.status).to eq(200) expect(last_response.body).to eq('Nested triple'.to_json) end end context 'with reused parameter documentation once required and once optional' do before do docs = { name: { type: String, desc: 'some name' } } subject.params do requires :all, using: docs end subject.get '/required' do 'Hello required' end subject.params do optional :all, using: docs end subject.get '/optional' do 'Hello optional' end end it 'works with required' do get '/required' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"name is missing"}') get '/required', name: 'Bob' expect(last_response.status).to eq(200) expect(last_response.body).to eq('Hello required'.to_json) end it 'works with optional' do get '/optional' expect(last_response.status).to eq(200) expect(last_response.body).to eq('Hello optional'.to_json) get '/optional', name: 'Bob' expect(last_response.status).to eq(200) expect(last_response.body).to eq('Hello optional'.to_json) end end context 'with a custom type' do it 'does not validate their type when it is missing' do custom_type = Class.new do def self.parse(value) return if value.blank? new end end subject.params do requires :custom, type: custom_type end subject.get '/custom' do 'custom' end get 'custom' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"custom is missing"}') get 'custom', custom: 'filled' expect(last_response.status).to eq(200) end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/validators/same_as_validator_spec.rb
spec/grape/validations/validators/same_as_validator_spec.rb
# frozen_string_literal: true describe Grape::Validations::Validators::SameAsValidator do let_it_be(:app) do Class.new(Grape::API) do params do requires :password requires :password_confirmation, same_as: :password end post do end params do requires :password requires :password_confirmation, same_as: { value: :password, message: 'not match' } end post '/custom-message' do end end end describe '/' do context 'is the same' do it do post '/', password: '987654', password_confirmation: '987654' expect(last_response.status).to eq(201) expect(last_response.body).to eq('') end end context 'is not the same' do it do post '/', password: '123456', password_confirmation: 'whatever' expect(last_response.status).to eq(400) expect(last_response.body).to eq('password_confirmation is not the same as password') end end end describe '/custom-message' do context 'is the same' do it do post '/custom-message', password: '987654', password_confirmation: '987654' expect(last_response.status).to eq(201) expect(last_response.body).to eq('') end end context 'is not the same' do it do post '/custom-message', password: '123456', password_confirmation: 'whatever' expect(last_response.status).to eq(400) expect(last_response.body).to eq('password_confirmation not match') end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/validators/exactly_one_of_validator_spec.rb
spec/grape/validations/validators/exactly_one_of_validator_spec.rb
# frozen_string_literal: true describe Grape::Validations::Validators::ExactlyOneOfValidator do let_it_be(:app) do Class.new(Grape::API) do rescue_from Grape::Exceptions::ValidationErrors do |e| error!(e.errors.transform_keys! { |key| key.join(',') }, 400) end params do optional :beer optional :wine optional :grapefruit exactly_one_of :beer, :wine, :grapefruit end post do end params do optional :beer optional :wine optional :grapefruit optional :other exactly_one_of :beer, :wine, :grapefruit end post 'mixed-params' do end params do optional :beer optional :wine optional :grapefruit exactly_one_of :beer, :wine, :grapefruit, message: 'you should choose one' end post '/custom-message' do end params do requires :item, type: Hash do optional :beer optional :wine optional :grapefruit exactly_one_of :beer, :wine, :grapefruit end end post '/nested-hash' do end params do optional :item, type: Hash do optional :beer optional :wine optional :grapefruit exactly_one_of :beer, :wine, :grapefruit end end post '/nested-optional-hash' do end params do requires :items, type: Array do optional :beer optional :wine optional :grapefruit exactly_one_of :beer, :wine, :grapefruit end end post '/nested-array' do end params do requires :items, type: Array do requires :nested_items, type: Array do optional :beer, :wine, :grapefruit, type: Grape::API::Boolean exactly_one_of :beer, :wine, :grapefruit end end end post '/deeply-nested-array' do end end end describe '#validate!' do subject(:validate) { post path, params } context 'when all params are present' do let(:path) { '/' } let(:params) { { beer: true, wine: true, grapefruit: true } } it 'returns a validation error' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'beer,wine,grapefruit' => ['are mutually exclusive'] ) end context 'mixed with other params' do let(:path) { '/mixed-params' } let(:params) { { beer: true, wine: true, grapefruit: true, other: true } } it 'returns a validation error' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'beer,wine,grapefruit' => ['are mutually exclusive'] ) end end end context 'when a subset of params are present' do let(:path) { '/' } let(:params) { { beer: true, grapefruit: true } } it 'returns a validation error' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'beer,grapefruit' => ['are mutually exclusive'] ) end end context 'when custom message is specified' do let(:path) { '/custom-message' } let(:params) { { beer: true, wine: true } } it 'returns a validation error' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'beer,wine' => ['you should choose one'] ) end end context 'when exacly one param is present' do let(:path) { '/' } let(:params) { { beer: true, somethingelse: true } } it 'does not return a validation error' do validate expect(last_response.status).to eq 201 end end context 'when none of the params are present' do let(:path) { '/' } let(:params) { { somethingelse: true } } it 'returns a validation error' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'beer,wine,grapefruit' => ['are missing, exactly one parameter must be provided'] ) end end context 'when params are nested inside required hash' do let(:path) { '/nested-hash' } let(:params) { { item: { beer: true, wine: true } } } it 'returns a validation error with full names of the params' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'item[beer],item[wine]' => ['are mutually exclusive'] ) end end context 'when params are nested inside optional hash' do let(:path) { '/nested-optional-hash' } context 'when params are passed' do let(:params) { { item: { beer: true, wine: true } } } it 'returns a validation error with full names of the params' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'item[beer],item[wine]' => ['are mutually exclusive'] ) end end context 'when params are empty' do let(:params) { { other: true } } it 'does not return a validation error' do validate expect(last_response.status).to eq 201 end end end context 'when params are nested inside array' do let(:path) { '/nested-array' } let(:params) { { items: [{ beer: true, wine: true }, { wine: true, grapefruit: true }] } } it 'returns a validation error with full names of the params' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'items[0][beer],items[0][wine]' => [ 'are mutually exclusive' ], 'items[1][wine],items[1][grapefruit]' => [ 'are mutually exclusive' ] ) end end context 'when params are deeply nested' do let(:path) { '/deeply-nested-array' } let(:params) { { items: [{ nested_items: [{ beer: true, wine: true }] }] } } it 'returns a validation error with full names of the params' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'items[0][nested_items][0][beer],items[0][nested_items][0][wine]' => [ 'are mutually exclusive' ] ) end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/validators/all_or_none_validator_spec.rb
spec/grape/validations/validators/all_or_none_validator_spec.rb
# frozen_string_literal: true describe Grape::Validations::Validators::AllOrNoneOfValidator do let_it_be(:app) do Class.new(Grape::API) do rescue_from Grape::Exceptions::ValidationErrors do |e| error!(e.errors.transform_keys! { |key| key.join(',') }, 400) end params do optional :beer, :wine, type: Grape::API::Boolean all_or_none_of :beer, :wine end post do end params do optional :beer, :wine, :other, type: Grape::API::Boolean all_or_none_of :beer, :wine end post 'mixed-params' do end params do optional :beer, :wine, type: Grape::API::Boolean all_or_none_of :beer, :wine, message: 'choose all or none' end post '/custom-message' do end params do requires :item, type: Hash do optional :beer, :wine, type: Grape::API::Boolean all_or_none_of :beer, :wine end end post '/nested-hash' do end params do requires :items, type: Array do optional :beer, :wine, type: Grape::API::Boolean all_or_none_of :beer, :wine end end post '/nested-array' do end params do requires :items, type: Array do requires :nested_items, type: Array do optional :beer, :wine, type: Grape::API::Boolean all_or_none_of :beer, :wine end end end post '/deeply-nested-array' do end end end describe '#validate!' do subject(:validate) { post path, params } context 'when all restricted params are present' do let(:path) { '/' } let(:params) { { beer: true, wine: true } } it 'does not return a validation error' do validate expect(last_response.status).to eq 201 end context 'mixed with other params' do let(:path) { '/mixed-params' } let(:params) { { beer: true, wine: true, other: true } } it 'does not return a validation error' do validate expect(last_response.status).to eq 201 end end end context 'when a subset of restricted params are present' do let(:path) { '/' } let(:params) { { beer: true } } it 'returns a validation error' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'beer,wine' => ['provide all or none of parameters'] ) end end context 'when custom message is specified' do let(:path) { '/custom-message' } let(:params) { { beer: true } } it 'returns a validation error' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'beer,wine' => ['choose all or none'] ) end end context 'when no restricted params are present' do let(:path) { '/' } let(:params) { { somethingelse: true } } it 'does not return a validation error' do validate expect(last_response.status).to eq 201 end end context 'when restricted params are nested inside required hash' do let(:path) { '/nested-hash' } let(:params) { { item: { beer: true } } } it 'returns a validation error with full names of the params' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'item[beer],item[wine]' => ['provide all or none of parameters'] ) end end context 'when mutually exclusive params are nested inside array' do let(:path) { '/nested-array' } let(:params) { { items: [{ beer: true, wine: true }, { wine: true }] } } it 'returns a validation error with full names of the params' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'items[1][beer],items[1][wine]' => ['provide all or none of parameters'] ) end end context 'when mutually exclusive params are deeply nested' do let(:path) { '/deeply-nested-array' } let(:params) { { items: [{ nested_items: [{ beer: true }] }] } } it 'returns a validation error with full names of the params' do validate expect(last_response.status).to eq 400 expect(JSON.parse(last_response.body)).to eq( 'items[0][nested_items][0][beer],items[0][nested_items][0][wine]' => [ 'provide all or none of parameters' ] ) end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/validators/except_values_validator_spec.rb
spec/grape/validations/validators/except_values_validator_spec.rb
# frozen_string_literal: true describe Grape::Validations::Validators::ExceptValuesValidator do describe 'IncompatibleOptionValues' do subject { api } context 'when a default value is set' do let(:api) do ev = except_values dv = default_value Class.new(Grape::API) do params do optional :type, except_values: ev, default: dv end end end context 'when default value is in exclude' do let(:except_values) { 1..10 } let(:default_value) { except_values.to_a.sample } it 'raises IncompatibleOptionValues' do expect { subject }.to raise_error Grape::Exceptions::IncompatibleOptionValues end end context 'when default array has excluded values' do let(:except_values) { 1..10 } let(:default_value) { [8, 9, 10] } it 'raises IncompatibleOptionValues' do expect { subject }.to raise_error Grape::Exceptions::IncompatibleOptionValues end end end context 'when type is incompatible' do let(:api) do Class.new(Grape::API) do params do optional :type, except_values: 1..10, type: Symbol end end end it 'raises IncompatibleOptionValues' do expect { subject }.to raise_error Grape::Exceptions::IncompatibleOptionValues end end end { req_except: { requires: { except_values: %w[invalid-type1 invalid-type2 invalid-type3] }, tests: [ { value: 'invalid-type1', rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: 'invalid-type3', rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: 'valid-type', rc: 200, body: { type: 'valid-type' }.to_json } ] }, req_except_hash: { requires: { except_values: { value: %w[invalid-type1 invalid-type2 invalid-type3] } }, tests: [ { value: 'invalid-type1', rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: 'invalid-type3', rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: 'valid-type', rc: 200, body: { type: 'valid-type' }.to_json } ] }, req_except_custom_message: { requires: { except_values: { value: %w[invalid-type1 invalid-type2 invalid-type3], message: 'is not allowed' } }, tests: [ { value: 'invalid-type1', rc: 400, body: { error: 'type is not allowed' }.to_json }, { value: 'invalid-type3', rc: 400, body: { error: 'type is not allowed' }.to_json }, { value: 'valid-type', rc: 200, body: { type: 'valid-type' }.to_json } ] }, req_except_no_value: { requires: { except_values: { message: 'is not allowed' } }, tests: [ { value: 'invalid-type1', rc: 200, body: { type: 'invalid-type1' }.to_json } ] }, req_except_empty: { requires: { except_values: [] }, tests: [ { value: 'invalid-type1', rc: 200, body: { type: 'invalid-type1' }.to_json } ] }, req_except_lambda: { requires: { except_values: -> { %w[invalid-type1 invalid-type2 invalid-type3 invalid-type4] } }, tests: [ { value: 'invalid-type1', rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: 'invalid-type4', rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: 'valid-type', rc: 200, body: { type: 'valid-type' }.to_json } ] }, req_except_lambda_custom_message: { requires: { except_values: { value: -> { %w[invalid-type1 invalid-type2 invalid-type3 invalid-type4] }, message: 'is not allowed' } }, tests: [ { value: 'invalid-type1', rc: 400, body: { error: 'type is not allowed' }.to_json }, { value: 'invalid-type4', rc: 400, body: { error: 'type is not allowed' }.to_json }, { value: 'valid-type', rc: 200, body: { type: 'valid-type' }.to_json } ] }, opt_except_default: { optional: { except_values: %w[invalid-type1 invalid-type2 invalid-type3], default: 'valid-type2' }, tests: [ { value: 'invalid-type1', rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: 'invalid-type3', rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: 'valid-type', rc: 200, body: { type: 'valid-type' }.to_json }, { rc: 200, body: { type: 'valid-type2' }.to_json } ] }, opt_except_lambda_default: { optional: { except_values: -> { %w[invalid-type1 invalid-type2 invalid-type3] }, default: 'valid-type2' }, tests: [ { value: 'invalid-type1', rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: 'invalid-type3', rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: 'valid-type', rc: 200, body: { type: 'valid-type' }.to_json }, { rc: 200, body: { type: 'valid-type2' }.to_json } ] }, req_except_type_coerce: { requires: { type: Integer, except_values: [10, 11] }, tests: [ { value: 'invalid-type1', rc: 400, body: { error: 'type is invalid' }.to_json }, { value: 11, rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: '11', rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: '3', rc: 200, body: { type: 3 }.to_json }, { value: 3, rc: 200, body: { type: 3 }.to_json } ] }, opt_except_type_coerce_default: { optional: { type: Integer, except_values: [10, 11], default: 12 }, tests: [ { value: 'invalid-type1', rc: 400, body: { error: 'type is invalid' }.to_json }, { value: 10, rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: '3', rc: 200, body: { type: 3 }.to_json }, { value: 3, rc: 200, body: { type: 3 }.to_json }, { rc: 200, body: { type: 12 }.to_json } ] }, opt_except_array_type_coerce_default: { optional: { type: Array[Integer], except_values: [10, 11], default: 12 }, tests: [ { value: 'invalid-type1', rc: 400, body: { error: 'type is invalid' }.to_json }, { value: 10, rc: 400, body: { error: 'type is invalid' }.to_json }, { value: [10], rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: ['3'], rc: 200, body: { type: [3] }.to_json }, { value: [3], rc: 200, body: { type: [3] }.to_json }, { rc: 200, body: { type: 12 }.to_json } ] }, req_except_range: { optional: { type: Integer, except_values: 10..12 }, tests: [ { value: 11, rc: 400, body: { error: 'type has a value not allowed' }.to_json }, { value: 13, rc: 200, body: { type: 13 }.to_json } ] } }.each do |path, param_def| param_def[:tests].each do |t| describe "when #{path}" do let(:app) do Class.new(Grape::API) do default_format :json params do requires :type, **param_def[:requires] if param_def.key? :requires optional :type, **param_def[:optional] if param_def.key? :optional end get path do { type: params[:type] } end end end let(:body) do {}.tap do |body| body[:type] = t[:value] if t.key? :value end end before do get path.to_s, **body end it "returns body #{t[:body]} with status #{t[:rc]}" do expect(last_response.status).to eq t[:rc] expect(last_response.body).to eq t[:body] end end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/validators/allow_blank_validator_spec.rb
spec/grape/validations/validators/allow_blank_validator_spec.rb
# frozen_string_literal: true describe Grape::Validations::Validators::AllowBlankValidator do let_it_be(:app) do Class.new(Grape::API) do default_format :json params do requires :name, allow_blank: false end get '/disallow_blank' params do optional :name, type: String, allow_blank: false end get '/opt_disallow_string_blank' params do optional :name, allow_blank: false end get '/disallow_blank_optional_param' params do requires :name, allow_blank: true end get '/allow_blank' params do requires :val, type: DateTime, allow_blank: true end get '/allow_datetime_blank' params do requires :val, type: DateTime, allow_blank: false end get '/disallow_datetime_blank' params do requires :val, type: DateTime end get '/default_allow_datetime_blank' params do requires :val, type: Date, allow_blank: true end get '/allow_date_blank' params do requires :val, type: Integer, allow_blank: true end get '/allow_integer_blank' params do requires :val, type: Float, allow_blank: true end get '/allow_float_blank' params do requires :val, type: Integer, allow_blank: true end get '/allow_integer_blank' params do requires :val, type: Symbol, allow_blank: true end get '/allow_symbol_blank' params do requires :val, type: Grape::API::Boolean, allow_blank: true end get '/allow_boolean_blank' params do requires :val, type: Grape::API::Boolean, allow_blank: false end get '/disallow_boolean_blank' params do optional :user, type: Hash do requires :name, allow_blank: false end end get '/disallow_blank_required_param_in_an_optional_group' params do optional :user, type: Hash do requires :name, type: Date, allow_blank: true end end get '/allow_blank_date_param_in_an_optional_group' params do optional :user, type: Hash do optional :name, allow_blank: false requires :age end end get '/disallow_blank_optional_param_in_an_optional_group' params do requires :user, type: Hash do requires :name, allow_blank: false end end get '/disallow_blank_required_param_in_a_required_group' params do requires :user, type: Hash do requires :name, allow_blank: false end end get '/disallow_string_value_in_a_required_hash_group' params do requires :user, type: Hash do optional :name, allow_blank: false end end get '/disallow_blank_optional_param_in_a_required_group' params do optional :user, type: Hash do optional :name, allow_blank: false end end get '/disallow_string_value_in_an_optional_hash_group' resources :custom_message do params do requires :name, allow_blank: { value: false, message: 'has no value' } end get params do optional :name, allow_blank: { value: false, message: 'has no value' } end get '/disallow_blank_optional_param' params do requires :name, allow_blank: true end get '/allow_blank' params do requires :val, type: DateTime, allow_blank: true end get '/allow_datetime_blank' params do requires :val, type: DateTime, allow_blank: { value: false, message: 'has no value' } end get '/disallow_datetime_blank' params do requires :val, type: DateTime end get '/default_allow_datetime_blank' params do requires :val, type: Date, allow_blank: true end get '/allow_date_blank' params do requires :val, type: Integer, allow_blank: true end get '/allow_integer_blank' params do requires :val, type: Float, allow_blank: true end get '/allow_float_blank' params do requires :val, type: Integer, allow_blank: true end get '/allow_integer_blank' params do requires :val, type: Symbol, allow_blank: true end get '/allow_symbol_blank' params do requires :val, type: Grape::API::Boolean, allow_blank: true end get '/allow_boolean_blank' params do requires :val, type: Grape::API::Boolean, allow_blank: { value: false, message: 'has no value' } end get '/disallow_boolean_blank' params do optional :user, type: Hash do requires :name, allow_blank: { value: false, message: 'has no value' } end end get '/disallow_blank_required_param_in_an_optional_group' params do optional :user, type: Hash do requires :name, type: Date, allow_blank: true end end get '/allow_blank_date_param_in_an_optional_group' params do optional :user, type: Hash do optional :name, allow_blank: { value: false, message: 'has no value' } requires :age end end get '/disallow_blank_optional_param_in_an_optional_group' params do requires :user, type: Hash do requires :name, allow_blank: { value: false, message: 'has no value' } end end get '/disallow_blank_required_param_in_a_required_group' params do requires :user, type: Hash do requires :name, allow_blank: { value: false, message: 'has no value' } end end get '/disallow_string_value_in_a_required_hash_group' params do requires :user, type: Hash do optional :name, allow_blank: { value: false, message: 'has no value' } end end get '/disallow_blank_optional_param_in_a_required_group' params do optional :user, type: Hash do optional :name, allow_blank: { value: false, message: 'has no value' } end end get '/disallow_string_value_in_an_optional_hash_group' end end end describe 'bad encoding' do let(:app) do Class.new(Grape::API) do default_format :json params do requires :name, type: String, allow_blank: false end get '/bad_encoding' end end context 'when value has bad encoding' do it 'does not raise an error' do expect { get('/bad_encoding', { name: "Hello \x80" }) }.not_to raise_error end end end context 'invalid input' do it 'refuses empty string' do get '/disallow_blank', name: '' expect(last_response.status).to eq(400) get '/disallow_datetime_blank', val: '' expect(last_response.status).to eq(400) end it 'refuses only whitespaces' do get '/disallow_blank', name: ' ' expect(last_response.status).to eq(400) get '/disallow_blank', name: " \n " expect(last_response.status).to eq(400) get '/disallow_blank', name: "\n" expect(last_response.status).to eq(400) end it 'refuses nil' do get '/disallow_blank', name: nil expect(last_response.status).to eq(400) end it 'refuses missing' do get '/disallow_blank' expect(last_response.status).to eq(400) end end context 'custom validation message' do context 'with invalid input' do it 'refuses empty string' do get '/custom_message', name: '' expect(last_response.body).to eq('{"error":"name has no value"}') end it 'refuses empty string for an optional param' do get '/custom_message/disallow_blank_optional_param', name: '' expect(last_response.body).to eq('{"error":"name has no value"}') end it 'refuses only whitespaces' do get '/custom_message', name: ' ' expect(last_response.body).to eq('{"error":"name has no value"}') get '/custom_message', name: " \n " expect(last_response.body).to eq('{"error":"name has no value"}') get '/custom_message', name: "\n" expect(last_response.body).to eq('{"error":"name has no value"}') end it 'refuses nil' do get '/custom_message', name: nil expect(last_response.body).to eq('{"error":"name has no value"}') end end context 'with valid input' do it 'accepts valid input' do get '/custom_message', name: 'bob' expect(last_response.status).to eq(200) end it 'accepts empty input when allow_blank is false' do get '/custom_message/allow_blank', name: '' expect(last_response.status).to eq(200) end it 'accepts empty input' do get '/custom_message/default_allow_datetime_blank', val: '' expect(last_response.status).to eq(200) end it 'accepts empty when datetime allow_blank' do get '/custom_message/allow_datetime_blank', val: '' expect(last_response.status).to eq(200) end it 'accepts empty when date allow_blank' do get '/custom_message/allow_date_blank', val: '' expect(last_response.status).to eq(200) end context 'allow_blank when Numeric' do it 'accepts empty when integer allow_blank' do get '/custom_message/allow_integer_blank', val: '' expect(last_response.status).to eq(200) end it 'accepts empty when float allow_blank' do get '/custom_message/allow_float_blank', val: '' expect(last_response.status).to eq(200) end it 'accepts empty when integer allow_blank' do get '/custom_message/allow_integer_blank', val: '' expect(last_response.status).to eq(200) end end it 'accepts empty when symbol allow_blank' do get '/custom_message/allow_symbol_blank', val: '' expect(last_response.status).to eq(200) end it 'accepts empty when boolean allow_blank' do get '/custom_message/allow_boolean_blank', val: '' expect(last_response.status).to eq(200) end it 'accepts false when boolean allow_blank' do get '/custom_message/disallow_boolean_blank', val: false expect(last_response.status).to eq(200) end end context 'in an optional group' do context 'as a required param' do it 'accepts a missing group, even with a disallwed blank param' do get '/custom_message/disallow_blank_required_param_in_an_optional_group' expect(last_response.status).to eq(200) end it 'accepts a nested missing date value' do get '/custom_message/allow_blank_date_param_in_an_optional_group', user: { name: '' } expect(last_response.status).to eq(200) end it 'refuses a blank value in an existing group' do get '/custom_message/disallow_blank_required_param_in_an_optional_group', user: { name: '' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"user[name] has no value"}') end end context 'as an optional param' do it 'accepts a missing group, even with a disallwed blank param' do get '/custom_message/disallow_blank_optional_param_in_an_optional_group' expect(last_response.status).to eq(200) end it 'accepts a nested missing optional value' do get '/custom_message/disallow_blank_optional_param_in_an_optional_group', user: { age: '29' } expect(last_response.status).to eq(200) end it 'refuses a blank existing value in an existing scope' do get '/custom_message/disallow_blank_optional_param_in_an_optional_group', user: { age: '29', name: '' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"user[name] has no value"}') end end end context 'in a required group' do context 'as a required param' do it 'refuses a blank value in a required existing group' do get '/custom_message/disallow_blank_required_param_in_a_required_group', user: { name: '' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"user[name] has no value"}') end it 'refuses a string value in a required hash group' do get '/custom_message/disallow_string_value_in_a_required_hash_group', user: '' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"user is invalid, user[name] is missing"}') end end context 'as an optional param' do it 'accepts a nested missing value' do get '/custom_message/disallow_blank_optional_param_in_a_required_group', user: { age: '29' } expect(last_response.status).to eq(200) end it 'refuses a blank existing value in an existing scope' do get '/custom_message/disallow_blank_optional_param_in_a_required_group', user: { age: '29', name: '' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"user[name] has no value"}') end it 'refuses a string value in an optional hash group' do get '/custom_message/disallow_string_value_in_an_optional_hash_group', user: '' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"user is invalid"}') end end end end context 'valid input' do it 'allows missing optional strings' do get 'opt_disallow_string_blank' expect(last_response.status).to eq(200) end it 'accepts valid input' do get '/disallow_blank', name: 'bob' expect(last_response.status).to eq(200) end it 'accepts empty input when allow_blank is false' do get '/allow_blank', name: '' expect(last_response.status).to eq(200) end it 'accepts empty input' do get '/default_allow_datetime_blank', val: '' expect(last_response.status).to eq(200) end it 'accepts empty when datetime allow_blank' do get '/allow_datetime_blank', val: '' expect(last_response.status).to eq(200) end it 'accepts empty when date allow_blank' do get '/allow_date_blank', val: '' expect(last_response.status).to eq(200) end context 'allow_blank when Numeric' do it 'accepts empty when integer allow_blank' do get '/allow_integer_blank', val: '' expect(last_response.status).to eq(200) end it 'accepts empty when float allow_blank' do get '/allow_float_blank', val: '' expect(last_response.status).to eq(200) end it 'accepts empty when integer allow_blank' do get '/allow_integer_blank', val: '' expect(last_response.status).to eq(200) end end it 'accepts empty when symbol allow_blank' do get '/allow_symbol_blank', val: '' expect(last_response.status).to eq(200) end it 'accepts empty when boolean allow_blank' do get '/allow_boolean_blank', val: '' expect(last_response.status).to eq(200) end it 'accepts false when boolean allow_blank' do get '/disallow_boolean_blank', val: false expect(last_response.status).to eq(200) end it 'accepts value when time allow_blank' do get '/disallow_datetime_blank', val: Time.now expect(last_response.status).to eq(200) end end context 'in an optional group' do context 'as a required param' do it 'accepts a missing group, even with a disallwed blank param' do get '/disallow_blank_required_param_in_an_optional_group' expect(last_response.status).to eq(200) end it 'accepts a nested missing date value' do get '/allow_blank_date_param_in_an_optional_group', user: { name: '' } expect(last_response.status).to eq(200) end it 'refuses a blank value in an existing group' do get '/disallow_blank_required_param_in_an_optional_group', user: { name: '' } expect(last_response.status).to eq(400) end end context 'as an optional param' do it 'accepts a missing group, even with a disallwed blank param' do get '/disallow_blank_optional_param_in_an_optional_group' expect(last_response.status).to eq(200) end it 'accepts a nested missing optional value' do get '/disallow_blank_optional_param_in_an_optional_group', user: { age: '29' } expect(last_response.status).to eq(200) end it 'refuses a blank existing value in an existing scope' do get '/disallow_blank_optional_param_in_an_optional_group', user: { age: '29', name: '' } expect(last_response.status).to eq(400) end end end context 'in a required group' do context 'as a required param' do it 'refuses a blank value in a required existing group' do get '/disallow_blank_required_param_in_a_required_group', user: { name: '' } expect(last_response.status).to eq(400) end it 'refuses a string value in a required hash group' do get '/disallow_string_value_in_a_required_hash_group', user: '' expect(last_response.status).to eq(400) end end context 'as an optional param' do it 'accepts a nested missing value' do get '/disallow_blank_optional_param_in_a_required_group', user: { age: '29' } expect(last_response.status).to eq(200) end it 'refuses a blank existing value in an existing scope' do get '/disallow_blank_optional_param_in_a_required_group', user: { age: '29', name: '' } expect(last_response.status).to eq(400) end it 'refuses a string value in an optional hash group' do get '/disallow_string_value_in_an_optional_hash_group', user: '' expect(last_response.status).to eq(400) end end end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false
ruby-grape/grape
https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/validations/validators/default_validator_spec.rb
spec/grape/validations/validators/default_validator_spec.rb
# frozen_string_literal: true describe Grape::Validations::Validators::DefaultValidator do let_it_be(:app) do Class.new(Grape::API) do default_format :json params do optional :id optional :type, default: 'default-type' end get '/' do { id: params[:id], type: params[:type] } end params do optional :type1, default: 'default-type1' optional :type2, default: 'default-type2' end get '/user' do { type1: params[:type1], type2: params[:type2] } end params do requires :id optional :type1, default: 'default-type1' optional :type2, default: 'default-type2' end get '/message' do { id: params[:id], type1: params[:type1], type2: params[:type2] } end params do optional :random, default: -> { Random.rand } optional :not_random, default: Random.rand end get '/numbers' do { random_number: params[:random], non_random_number: params[:non_random_number] } end params do optional :array, type: Array do requires :name optional :with_default, default: 'default' end end get '/array' do { array: params[:array] } end params do requires :thing1 optional :more_things, type: Array do requires :nested_thing requires :other_thing, default: 1 end end get '/optional_array' do { thing1: params[:thing1] } end params do requires :root, type: Hash do optional :some_things, type: Array do requires :foo optional :options, type: Array do requires :name, type: String requires :value, type: String end end end end get '/nested_optional_array' do { root: params[:root] } end params do requires :root, type: Hash do optional :some_things, type: Array do requires :foo optional :options, type: Array do optional :name, type: String optional :value, type: String end end end end get '/another_nested_optional_array' do { root: params[:root] } end params do requires :foo optional :bar, default: ->(params) { params[:foo] } optional :qux, default: ->(params) { params[:bar] } end get '/default_values_from_other_params' do { foo: params[:foo], bar: params[:bar], qux: params[:qux] } end end end it 'lets you leave required values nested inside an optional blank' do get '/optional_array', thing1: 'stuff' expect(last_response.status).to eq(200) expect(last_response.body).to eq({ thing1: 'stuff' }.to_json) end it 'allows optional arrays to be omitted' do params = { some_things: [{ foo: 'one', options: [{ name: 'wat', value: 'nope' }] }, { foo: 'two' }, { foo: 'three', options: [{ name: 'wooop', value: 'yap' }] }] } get '/nested_optional_array', root: params expect(last_response.status).to eq(200) expect(last_response.body).to eq({ root: params }.to_json) end it 'does not allows faulty optional arrays' do params = { some_things: [ { foo: 'one', options: [{ name: 'wat', value: 'nope' }] }, { foo: 'two', options: [{ name: 'wat' }] }, { foo: 'three' } ] } error = { error: 'root[some_things][1][options][0][value] is missing' } get '/nested_optional_array', root: params expect(last_response.status).to eq(400) expect(last_response.body).to eq(error.to_json) end it 'allows optional arrays with optional params' do params = { some_things: [ { foo: 'one', options: [{ value: 'nope' }] }, { foo: 'two', options: [{ name: 'wat' }] }, { foo: 'three' } ] } get '/another_nested_optional_array', root: params expect(last_response.status).to eq(200) expect(last_response.body).to eq({ root: params }.to_json) end it 'set default value for optional param' do get('/') expect(last_response.status).to eq(200) expect(last_response.body).to eq({ id: nil, type: 'default-type' }.to_json) end it 'set default values for optional params' do get('/user') expect(last_response.status).to eq(200) expect(last_response.body).to eq({ type1: 'default-type1', type2: 'default-type2' }.to_json) end it 'set default values for missing params in the request' do get('/user?type2=value2') expect(last_response.status).to eq(200) expect(last_response.body).to eq({ type1: 'default-type1', type2: 'value2' }.to_json) end it 'set default values for optional params and allow to use required fields in the same time' do get('/message?id=1') expect(last_response.status).to eq(200) expect(last_response.body).to eq({ id: '1', type1: 'default-type1', type2: 'default-type2' }.to_json) end it 'sets lambda based defaults at the time of call' do get('/numbers') expect(last_response.status).to eq(200) before = JSON.parse(last_response.body) get('/numbers') expect(last_response.status).to eq(200) after = JSON.parse(last_response.body) expect(before['non_random_number']).to eq(after['non_random_number']) expect(before['random_number']).not_to eq(after['random_number']) end it 'sets default values for grouped arrays' do get('/array?array[][name]=name&array[][name]=name2&array[][with_default]=bar2') expect(last_response.status).to eq(200) expect(last_response.body).to eq({ array: [{ name: 'name', with_default: 'default' }, { name: 'name2', with_default: 'bar2' }] }.to_json) end context 'optional group with defaults' do subject do Class.new(Grape::API) do default_format :json end end def app subject end context 'optional array without default value includes optional param with default value' do before do subject.params do optional :optional_array, type: Array do optional :foo_in_optional_array, default: 'bar' end end subject.post '/optional_array' do { optional_array: params[:optional_array] } end end it 'returns nil for optional array if param is not provided' do post '/optional_array' expect(last_response.status).to eq(201) expect(last_response.body).to eq({ optional_array: nil }.to_json) end end context 'optional array with default value includes optional param with default value' do before do subject.params do optional :optional_array_with_default, type: Array, default: [] do optional :foo_in_optional_array, default: 'bar' end end subject.post '/optional_array_with_default' do { optional_array_with_default: params[:optional_array_with_default] } end end it 'sets default value for optional array if param is not provided' do post '/optional_array_with_default' expect(last_response.status).to eq(201) expect(last_response.body).to eq({ optional_array_with_default: [] }.to_json) end end context 'optional hash without default value includes optional param with default value' do before do subject.params do optional :optional_hash_without_default, type: Hash do optional :foo_in_optional_hash, default: 'bar' end end subject.post '/optional_hash_without_default' do { optional_hash_without_default: params[:optional_hash_without_default] } end end it 'returns nil for optional hash if param is not provided' do post '/optional_hash_without_default' expect(last_response.status).to eq(201) expect(last_response.body).to eq({ optional_hash_without_default: nil }.to_json) end it 'does not fail even if invalid params is passed to default validator' do expect { post '/optional_hash_without_default', optional_hash_without_default: '5678' }.not_to raise_error expect(last_response.status).to eq(400) expect(last_response.body).to eq({ error: 'optional_hash_without_default is invalid' }.to_json) end end context 'optional hash with default value includes optional param with default value' do before do subject.params do optional :optional_hash_with_default, type: Hash, default: {} do optional :foo_in_optional_hash, default: 'bar' end end subject.post '/optional_hash_with_default_empty_hash' do { optional_hash_with_default: params[:optional_hash_with_default] } end subject.params do optional :optional_hash_with_default, type: Hash, default: { foo_in_optional_hash: 'parent_default' } do optional :some_param optional :foo_in_optional_hash, default: 'own_default' end end subject.post '/optional_hash_with_default_inner_params' do { foo_in_optional_hash: params[:optional_hash_with_default][:foo_in_optional_hash] } end end it 'sets default value for optional hash if param is not provided' do post '/optional_hash_with_default_empty_hash' expect(last_response.status).to eq(201) expect(last_response.body).to eq({ optional_hash_with_default: {} }.to_json) end it 'sets default value from parent defaults for inner param if parent param is not provided' do post '/optional_hash_with_default_inner_params' expect(last_response.status).to eq(201) expect(last_response.body).to eq({ foo_in_optional_hash: 'parent_default' }.to_json) end it 'sets own default value for inner param if parent param is provided' do post '/optional_hash_with_default_inner_params', optional_hash_with_default: { some_param: 'param' } expect(last_response.status).to eq(201) expect(last_response.body).to eq({ foo_in_optional_hash: 'own_default' }.to_json) end end end context 'optional with nil as value' do subject do Class.new(Grape::API) do default_format :json end end def app subject end context 'primitive types' do [ [Integer, 0], [Integer, 42], [Float, 0.0], [Float, 4.2], [BigDecimal, 0.0], [BigDecimal, 4.2], [Numeric, 0], [Numeric, 42], [Date, Date.today], [DateTime, DateTime.now], [Time, Time.now], [Time, Time.at(0)], [Grape::API::Boolean, false], [String, ''], [String, 'non-empty-string'], [Symbol, :symbol], [TrueClass, true], [FalseClass, false] ].each do |type, default| it 'respects the default value' do subject.params do optional :param, type: type, default: default end subject.get '/default_value' do params[:param] end get '/default_value', param: nil expect(last_response.status).to eq(200) expect(last_response.body).to eq(default.to_json) end end end context 'structures types' do [ [Hash, {}], [Hash, { test: 'non-empty' }], [Array, []], [Array, ['non-empty']], [Array[Integer], []], [Set, []], [Set, [1]] ].each do |type, default| it 'respects the default value' do subject.params do optional :param, type: type, default: default end subject.get '/default_value' do params[:param] end get '/default_value', param: nil expect(last_response.status).to eq(200) expect(last_response.body).to eq(default.to_json) end end end context 'special types' do [ [JSON, ''], [JSON, { test: 'non-empty-string' }.to_json], [Array[JSON], []], [Array[JSON], [{ test: 'non-empty-string' }.to_json]], [File, ''], [File, { test: 'non-empty-string' }.to_json], [Rack::Multipart::UploadedFile, ''], [Rack::Multipart::UploadedFile, { test: 'non-empty-string' }.to_json] ].each do |type, default| it 'respects the default value' do subject.params do optional :param, type: type, default: default end subject.get '/default_value' do params[:param] end get '/default_value', param: nil expect(last_response.status).to eq(200) expect(last_response.body).to eq(default.to_json) end end end context 'variant-member-type collections' do [ [Array[Integer, String], [0, '']], [Array[Integer, String], [42, 'non-empty-string']], [[Integer, String, Array[Integer, String]], [0, '', [0, '']]], [[Integer, String, Array[Integer, String]], [42, 'non-empty-string', [42, 'non-empty-string']]] ].each do |type, default| it 'respects the default value' do subject.params do optional :param, type: type, default: default end subject.get '/default_value' do params[:param] end get '/default_value', param: nil expect(last_response.status).to eq(200) expect(last_response.body).to eq(default.to_json) end end end end context 'array with default values and given conditions' do subject do Class.new(Grape::API) do default_format :json end end def app subject end it 'applies the default values only if the conditions are met' do subject.params do requires :ary, type: Array do requires :has_value, type: Grape::API::Boolean given has_value: ->(has_value) { has_value } do optional :type, type: String, values: %w[str int], default: 'str' given type: ->(type) { type == 'str' } do optional :str, type: String, default: 'a' end given type: ->(type) { type == 'int' } do optional :int, type: Integer, default: 1 end end end end subject.post('/nested_given_and_default') { declared(self.params) } params = { ary: [ { has_value: false }, { has_value: true, type: 'int', int: 123 }, { has_value: true, type: 'str', str: 'b' } ] } expected = { 'ary' => [ { 'has_value' => false, 'type' => nil, 'int' => nil, 'str' => nil }, { 'has_value' => true, 'type' => 'int', 'int' => 123, 'str' => nil }, { 'has_value' => true, 'type' => 'str', 'int' => nil, 'str' => 'b' } ] } post '/nested_given_and_default', params expect(last_response.status).to eq(201) expect(JSON.parse(last_response.body)).to eq(expected) end end it 'sets default value for optional params using other params values' do expected_foo_value = 'foo-value' get("/default_values_from_other_params?foo=#{expected_foo_value}") expect(last_response.status).to eq(200) expect(last_response.body).to eq({ foo: expected_foo_value, bar: expected_foo_value, qux: expected_foo_value }.to_json) end end
ruby
MIT
17fb0cf64296e9c9c968ea7b62f7614538070be4
2026-01-04T15:38:22.454413Z
false