diff --git a/app/controllers/case_logs_controller.rb b/app/controllers/case_logs_controller.rb index 311de1d7c..eaaf400a3 100644 --- a/app/controllers/case_logs_controller.rb +++ b/app/controllers/case_logs_controller.rb @@ -8,10 +8,16 @@ class CaseLogsController < ApplicationController end def create - @case_log = CaseLog.create!(create_params) + @case_log = CaseLog.create(create_params) respond_to do |format| format.html { redirect_to @case_log } - format.json { render json: @case_log } + format.json do + if @case_log.persisted? + render json: @case_log , status: :created + else + render json: { errors: @case_log.errors.full_messages }, status: :unprocessable_entity + end + end end end diff --git a/app/models/case_log.rb b/app/models/case_log.rb index aa17eddf6..187d285b9 100644 --- a/app/models/case_log.rb +++ b/app/models/case_log.rb @@ -5,22 +5,28 @@ class CaseLogValidator < ActiveModel::Validator def validate_tenant_code(record) if record.tenant_code.blank? - record.errors.add :tenant_code, "Tenant code can't be blank" + # record.errors.add :tenant_code, "Tenant code can't be blank" end end def validate_tenant_age(record) - if record.tenant_age.blank? - record.errors.add :tenant_age, "Tenant age can't be blank" - elsif !/^[1-9][0-9]?$|^100$/.match?(record.tenant_age.to_s) + # if record.tenant_age.blank? + # record.errors.add :tenant_age, "Tenant age can't be blank" + # elsif !/^[1-9][0-9]?$|^100$/.match?(record.tenant_age.to_s) + # record.errors.add :tenant_age, "Tenant age must be between 0 and 100" + # end + if record.tenant_age && !/^[1-9][0-9]?$|^100$/.match?(record.tenant_age.to_s) record.errors.add :tenant_age, "Tenant age must be between 0 and 100" end end def validate(record) question_to_validate = options[:previous_page] - if respond_to?("validate_#{question_to_validate}") + if question_to_validate && respond_to?("validate_#{question_to_validate}") public_send("validate_#{question_to_validate}", record) + else + validation_methods = public_methods(false) - [__callee__] + validation_methods.each { |meth| public_send(meth, record) } end end end diff --git a/spec/requests/case_log_controller_spec.rb b/spec/requests/case_log_controller_spec.rb index 54ba319bf..34d9f98bb 100644 --- a/spec/requests/case_log_controller_spec.rb +++ b/spec/requests/case_log_controller_spec.rb @@ -51,6 +51,16 @@ RSpec.describe CaseLogsController, type: :request do expect(json_response["property_postcode"]).to eq(property_postcode) end + context "invalid json params" do + let(:tenant_age) { 2000 } + + it "validates case log parameters" do + json_response = JSON.parse(response.body) + expect(response).to have_http_status(:unprocessable_entity) + expect(json_response["errors"]).to eq(["Tenant age Tenant age must be between 0 and 100"]) + end + end + context "request with invalid credentials" do let(:basic_credentials) do ActionController::HttpAuthentication::Basic.encode_credentials(api_username, "Oops")