0

I have the following RSpec test:

 it 'should not list alerts, since I do not have access to this model' do
   get :index, params: { model_id: @model2.id, workspace_id: @workspace.id }, as: :json
   expect(response).to have_http_status(:forbidden)
 end

and it is failing because Apipie is complaining the workspace_id is a String when it is actually not, it is an Integer. I debugged the call, inspected @workspace and id is definitely an Integer.

I'm seeing this issue now that I'm migrating the application to Rails 5.2.0 (previously Rails 4).

Has anyone seen something like this?

Luiz E.
  • 6,769
  • 10
  • 58
  • 98

3 Answers3

2

The GET request doesn't contains body, while you're trying to send some payload. In the case of GET request all params passed as url query (e.g. /index?model_id=1&workspace_id=1) and all params are string.

You have two options here:

  • Change GET to POST, it will allow request with body.
  • Convert string to integer in the action.
Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
  • nope. the apipie validation can actually see that the workspace_id is 1, but see it as an integer, so the `params` are not sent through the body, they are being sent via query param – Luiz E. Oct 08 '18 at 19:04
  • There is no types in url query params, all url-query params are strings. – Roman Kiselenko Oct 08 '18 at 19:05
  • 1
    who knows, that's an open-source lib, inspect changelogs, the issues, maybe some changes happened. – Roman Kiselenko Oct 08 '18 at 19:07
0

Yes. I hit the same problem. I am using Rack::Test with rspec, and Rack::Test is automagically (bug) converting every value to a string. Not sure what other back-end bits also do this.

The only way I found to get rack-test to send anything other than strings as values, was by overriding the request methods as described here: https://stackoverflow.com/a/37234290/2326613

There is also a problem where BigDecimal values are being forced into strings by "as: :json" - not affecting the OP (IDs being Integers) but could be others finding this question by search. The workaround to fix that bug was depreciated and removed by the Rails team. So, to be able to follow JSON conventions which your JSON-consumer may expect (vs Rails conventions), you need to override the BigDecimal-as_json method to fix it: https://github.com/rails/rails/issues/25017

JosephK
  • 668
  • 10
  • 18
0

If someone is facing the same integer converted to string issue while making a POST/PUT/PATCH request. If you pass the params converted with to_json and pass 'CONTENT_TYPE' => 'application/json' as env, integer will be passed as is to the controller.

let(:params) do
  {
    down_payment: 10_000,
    asking_price: 100_000,
    payment_schedule: 'weekly',
    amortization_period: 5
  }
end

it 'works' do
  post '/', params.to_json, 'CONTENT_TYPE' => 'application/json'
end

This will work as expected.

Ayer
  • 120
  • 2
  • 6