Browse Source

Validate controller params

pull/44/head
baarkerlounger 4 years ago
parent
commit
5c82bd8861
  1. 10
      app/controllers/case_logs_controller.rb
  2. 16
      app/models/case_log.rb
  3. 12
      spec/requests/case_log_controller_spec.rb

10
app/controllers/case_logs_controller.rb

@ -7,10 +7,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

16
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

12
spec/requests/case_log_controller_spec.rb

@ -16,7 +16,7 @@ RSpec.describe CaseLogsController, type: :request do
let(:params) do
{
"tenant_code": tenant_code,
"tenant_age": 35,
"tenant_age": tenant_age,
"property_postcode": property_postcode
}
end
@ -40,5 +40,15 @@ RSpec.describe CaseLogsController, type: :request do
expect(json_response["tenant_age"]).to eq(tenant_age)
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
end
end

Loading…
Cancel
Save