在Grape-api-RSpec测试中存根一个常量



假设我在Grape::API类中定义了一个常量:

class Activities < Grape::API
MAX_ALLOWED = 50000
...
end

在端点desc:

params do
requires :data, type: Array, allow_blank: false, array_length: MAX_ALLOWED
end

我想编写一个规范(使用RSpec)来测试端点的array_length选项。我想截断MAX_ALLOWED常量,因为我不想实际生成50k的伪数据。

我试过stub_const(API::V3::Resources::Activities::MAX_ALLOWED, 3)

但出现错误:NoMethodError: undefined method 'sub' for 40000:Fixnum

我也试过stub_const('API::V3::Resources::Activities::MAX_ALLOWED', 3)

但那根本没用。

最后,我尝试了:

before do
allow_any_instance_of(API::V3::Resources::Activities).to receive(:MAX_ALLOWED).and_return(1)
end

它也没有起作用。

EDIT:也尝试了allow而不是allow_any_instance_of,结果相同。

编辑2:以下是失败的规范:

context 'with more than 50,000 contacts' do
let(:options) {{ 'CONTENT_TYPE' => 'application/json' }}
# contacts_api, uri, resource, and request are defined elsewhere
before { contacts_api :post, "#{uri}#{resource}", request.to_json, options }
# Also tried this instead of stub_const:
# before do
#  allow_any_instance_of(API::V3::Resources::Activities).to receive(:MAX_ALLOWED).and_return(1)
# end
it 'returns a 400' do
stub_const('API::V3::Resources::Activities::MAX_ALLOWED', 3)
expect(response.status).to eq(400)
expect(resp_body['error_key']).to eq('api error')
expect(resp_body['error_message']).to eq('too many contacts')
end
end

编辑3:请求位于与stub_const相同的it块中(仍然失败):

it 'returns a 400' do
stub_const('API::V3::Resources::Activities::MAX_ALLOWED', 3) # this doesn't work
contacts_api :post, "#{uri}#{resource}", request.to_json, options
expect(response.status).to eq(400)
expect(resp_body['error_key']).to eq('contacts.api.bad_request')
expect(resp_body['error_message']).to eq('too many contacts')
end

知道如何为RSpec测试存根Grape::API类中定义的常量吗?

在请求之前需要完成存根处理。在这种情况下,您可以将它放入POST上方的before块中。

before { stub_const('API::V3::Resources::Activities::MAX_ALLOWED', 3) }
before { contacts_api :post, "#{uri}#{resource}", request.to_json, options }

最新更新