grape
grape copied to clipboard
Accessing endpoint's params
Goal
I want to test params of the endpoint without making additional request because it makes tests quicker and more readable.
Context
It would be nice to be able to access param list of the endpoint just by initializing the class. If we have a class:
class MyApi < Grape::API
params do
requires :id, type: Integer, positive_value: true # positive_value - is a custom validation
end
get '/foo' do
# ...
end
end
Let's consider very simple interface to make it obvious. There can be a method MyApi.new.action_params(:get, '/foo') and it returns a list:
{
id: {type: Integer, required: true, custom_validations: [:positive_value]
}
And specs may look like:
describe 'checking GET /foo params' do
subject { MyApi.new.action_params(:get, '/foo') }
it { is_expected[:id].to eq((:type: 'Integer', required: true, custom_validations: []) }
end
Suggestion
Return array of classes EndpointParam:
class EndpointParam < Dry::Struct
attribute :name, Types::String
attribute :required, Types::Bool
attribute :type, Types::Any
attribute :custom_validators, Types::Array.of(EndpointParam)
end
Matcher:
describe 'checking GET /foo params' do
subject { MyApi.new.action_params(:get, '/foo') }
it { is_expected.to have_param(:id).with_type(Types::String).being_required.with_custom_validators(:positive_value) }
end
It was discussed here https://groups.google.com/forum/#!topic/ruby-grape/uww_W6c7Obs and examples are got also from there