Rspec-rails: Passing in boolean true to model in request test

Created on 4 Jan 2016  ·  6Comments  ·  Source: rspec/rspec-rails

Rails version: 4.1.10
Rspec-rails version: 3.0.2

I'm writing a request test and a model requires an attribute to be boolean true, not string true.

When passing this parameter in from a request test (param[:attribute] = true), the model receives: model.attribute = "true". ("true" as string)

When passing the parameter in from a controller test (param[:attribute] = true), the model receives: model.attribute = true. (true as boolean)

How can I pass true as a boolean to the model from the request test?

A gist of the above:
https://gist.github.com/a-leung/cc44372f1ae776726e89

Most helpful comment

If boolean params come to the controller as true/false and not as strings good chances are that you are passing them as a JSON in the body. In this case, you have to do this:

post :update, params: { id: user.id, attribute: true }, as: :json

or this:

post :update, params: { id: user.id }, body: { attribute: true }.to_json, as: :json

to pass them as booleans in tests also.

All 6 comments

Did you try model.attribute = (1 == 1)?

the problem is not assigning model.attribute, but in the differences between rspec params being passed in from the controller (params[:attribute] = true results in: model.attribute == true) and the request (params[:attribute] = true results in model.attribute == 'true').

given the same parameters, controller tests pass the boolean true to models, while request tests pass the string true to models.

let me know if things are not clear, I can create a simple rails project to demonstrate.

This is an issue in how rails tests behave, in reality params will always be strings, unless previously decoded by middleware, e.g. in the case of JSON which may be why the controller tests allow you to pass in real objects...

aaah ok. thanks for the clarification.

Is there any way to get requests tests to use the same middleware as controller tests?

They already will.

If boolean params come to the controller as true/false and not as strings good chances are that you are passing them as a JSON in the body. In this case, you have to do this:

post :update, params: { id: user.id, attribute: true }, as: :json

or this:

post :update, params: { id: user.id }, body: { attribute: true }.to_json, as: :json

to pass them as booleans in tests also.

Was this page helpful?
0 / 5 - 0 ratings