I'm working on a Rails + React web app. And there's one GET request which needs a parameter trainee_id
.
My question is:
Do I need to add params.require(:trainee_id)
and relative exception handler to verify the existence of the parameter?
Route: GET /results/trainees/:trainee_id/published
def get_trainee_published_result
result = Result.find_by(user_id: params[:trainee_id])
...
do stuff
...
end
I feel uncomfortable to use this parameter without checking. However, it seems that if the parameter is missing, the route would be invalid and this get_trainee_published_result
action wouldn't even be triggered.
There would also be some problems with Rspec testing if I include params.require(:trainee_id)
in my code. I could not test the case when parameter is missing (let(:params) { { trainee_id: nil } } ) because no route would match this request.
You're right, if a single defined route is the only way your controller action gets called, then the trainee_id
param will always be present. If you want to be validate this, you could write a routing spec that verifies GET /results/trainees/:trainee_id/published
calls your action with the given params:
expect(get: '/results/trainees/123/published')
.to route_to(controller: 'trainees', action: 'published', trainee_id: '123')
As for your action itself, I'd consider representing that you expect trainee_id
to always be present by accessing it via params.fetch(:trainee_id)
. If for any reason, trainee_id
isn't available in params
, that will throw a ActionController::ParameterMissing
error and the rest of your action won't complete.
If you wanted, you could check for this in a controller spec:
it 'throws an error when :trainee_id is missing' do
expect { get :published, params: { }) }.to raise_error(ActionController::ParameterMissing)
end