0
votes

I have a before_filter which checks that the incoming params are correct. If an extra param is passed or if there is a required missing param, it immediately renders a JSON error (it's an API app) using RABL.

To do so, I have the following two lines in my error-catching function:

json = render_to_string(template: 'errors/error')
render :json => json, :status => status

I am trying to test the param validation method which is called in the before_filter callback using rspec.

Now rspec renders an empty template. This immediately throws an error in my controller once I call the validation method in my test as follows: controller.validate_json(params, [:amount], nil, nil), since the validate_json method uses some JSON parsing which fails on an empty string.

To fix this, I need to call render_views in rspec. When I do that, I get a very weird long error like this:

RuntimeError:
       ActionController::RackDelegation#status=....

with basically the ActionController object. All it says is RuntimeError. It does not say what type of error it is or anything. The error from this line:

render :json => json, :status => status

How else would I test the template in the controller? I know I probably need to have two different tests for views and controllers, but I do not have HTML views, but all JSON views, rendered in RABL. Without using render_views, then I cannot test the controller because part of testing the controller is seeing that it returned the correct status as well as the correct JSON. Furthermore, the validate_json method will fail on an empty JSON (due to empty string JSON parsing) and hence, I cannot really test the and controller separately.

1
so you are calling the method directly instead of doing a get to an action and looking at the response - phoet
validate_json is not an action. It is a helper method in the controller that validates incoming params. The reason it's in controller is so that I can call render as you can see above. If it was a lib, then I do not have access to rendering and other controller-specific functions so I cannot render an render (as in my question). Or is that not the right place for it to be? - darksky
it's the right place. but you should not call it directly in a controller test! you would call the action that the before-filter is configured to run at and check those results - phoet

1 Answers

0
votes

To fix the routing issue you'll want to add :format => :json to the get request in your spec.

get :index, :format => :json