user1105595
user1105595

Reputation: 601

Testing custom validators presence in params in ruby grape API

I have a very simple grape-powered API. Lets say that it looks like this:

class MyApi < Grape::API
  params do
    requires :name, type: String
    requires :id, type: Integer, positive_value: true
  end

  get '/' do 
    # whatever...
  end
end

I have custom PositiveValue validator, which works just fine for id.

I would like to create spec that makes sure that my params has correct options passed. I would like to avoid making full request specs, but instead of that I'd like to check if name param has type: String, and make sure it's required:

  # my_api_spec.rb
  describe 'params' do
     let(:params) { described_class.new.router.map['GET'].first.options[:params] }
     specify do
       expect(params['name']).to include(type: 'String') # this one works fine
       expect(params['id']].to include(type: 'Integer', positive_value: true) # this one fails
     end
  end

It turns out that this params have {:required=>true, :type=>"Integer"} hash. How can I test and make sure that my custom validators are being used for given param?

Thanks for help in advance.

Upvotes: 0

Views: 817

Answers (1)

Vasfed
Vasfed

Reputation: 18504

I'd advise against diving that deep into implementation details from tests - if one day you'll decide to replace grape with something else (or grape itself releases a new incompatible version) - your tests will become useless in a time when you need them most.

Also testing for presence of positive_value: true does not guarantee that your validator gets actually called with expected parameters and works correctly, so at least add:

expect_any_instance_of(PositiveValue).to receive(:validate_param!).with('id', {'id'=>123, 'name'=>'name'}).and_call_original

Best way is to write an actual request spec. You can stub out heavy processing parts, if you worry about it, but make your controller actually process the parameters and return some error just like if this error happens in production.

Upvotes: 0

Related Questions