简体   繁体   English

测试自定义验证器是否存在于 ruby​​ 葡萄 API 中的参数中

[英]Testing custom validators presence in params in ruby grape API

I have a very simple grape-powered API.我有一个非常简单的由葡萄驱动的 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 .我有自定义的 PositiveValue 验证器,它适用于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:我想避免制定完整的请求规范,但我想检查name param 是否具有type: String ,并确保它是必需的:

  # 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.事实证明,这个参数有{:required=>true, :type=>"Integer"}哈希。 How can I test and make sure that my custom validators are being used for given param?如何测试并确保我的自定义验证器用于给定参数?

Thanks for help in advance.提前感谢您的帮助。

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:还测试是否存在positive_value: true并不能保证您的验证器实际使用预期参数调用并正常工作,因此至少添加:

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.如果您担心的话,您可以剔除繁重的处理部件,但让您的控制器实际处理参数并返回一些错误,就像此错误发生在生产中一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM