Skip to content

Commit

Permalink
Make user_id a required field on /api/v1/regions/:id/surveys endpoint
Browse files Browse the repository at this point in the history
Also add some basic tests for the endpoint
  • Loading branch information
aaronbrethorst committed Aug 23, 2024
1 parent 3ec2711 commit 4d117ae
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 6 deletions.
5 changes: 3 additions & 2 deletions app/controllers/api/v1/survey_responses_controller.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
class Api::V1::SurveyResponsesController < Api::V1::ApiController
skip_before_action :load_region

def create
@survey = Survey.find(params[:survey_id])
@survey_response = @survey.survey_responses.build
Expand All @@ -11,7 +12,7 @@ def create
if @survey_response.save
render 'create', status: :created, formats: :json
else
render_api_errors(@survey_response)
render_api_errors(model: @survey_response)
end
end

Expand All @@ -23,7 +24,7 @@ def update
if @survey_response.save
render 'create', status: :ok, formats: :json
else
render_api_errors(@survey_response)
render_api_errors(model: @survey_response)
end
end
end
7 changes: 6 additions & 1 deletion app/controllers/api/v1/surveys_controller.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
class Api::V1::SurveysController < ApplicationController
class Api::V1::SurveysController < Api::V1::ApiController
before_action :load_region

def index
if params[:user_id].blank?
render_api_errors(message: 'user_id is required')
return
end

@surveys = Survey.includes(:study).where(available: true, studies: { region: @region })
end

Expand Down
9 changes: 7 additions & 2 deletions app/helpers/api/v1/errors_helper.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
module Api::V1::ErrorsHelper
def render_api_errors(model)
@errors = model.errors.full_messages
def render_api_errors(model: nil, message: nil)
@errors = if model
model.errors.full_messages
else
[message]
end

render 'api/v1/common/errors', status: :unprocessable_entity, formats: :json
end
end
17 changes: 16 additions & 1 deletion spec/requests/api/v1/surveys_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@

RSpec.describe "Api::V1::Surveys", type: :request do
describe "GET /index" do
pending "add some examples (or delete) #{__FILE__}"
let(:region) { create(:region) }

describe "when user_id is blank" do
it "returns an error message" do
get api_v1_region_surveys_path(region, format: "json")
expect(response).to have_http_status(:unprocessable_entity)
expect(response.body).to include("user_id is required")
end
end

describe "when user_id is present" do
it "returns a list of surveys" do
get api_v1_region_surveys_path(region, format: "json", user_id: 1)
expect(response).to have_http_status(:ok)
end
end
end
end

0 comments on commit 4d117ae

Please sign in to comment.