From a3128a880beee78c1474ee86b51a30ad20bce955 Mon Sep 17 00:00:00 2001 From: Ted-U <92022120+Ted-U@users.noreply.github.com> Date: Tue, 27 Sep 2022 12:09:20 +0100 Subject: [PATCH] add validations to number of beds question in sales --- app/models/sales_log.rb | 7 ++++- app/models/validations/sales_validations.rb | 11 ++++++++ .../validations/sales_validations_spec.rb | 27 +++++++++++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 app/models/validations/sales_validations.rb create mode 100644 spec/models/validations/sales_validations_spec.rb diff --git a/app/models/sales_log.rb b/app/models/sales_log.rb index a2a6dcff3..3168e1c24 100644 --- a/app/models/sales_log.rb +++ b/app/models/sales_log.rb @@ -1,5 +1,10 @@ class SalesLogValidator < ActiveModel::Validator - def validate(record); end + include Validations::SalesValidations + + def validate(record) + validation_methods = public_methods.select { |method| method.starts_with?("validate_") } + validation_methods.each { |meth| public_send(meth, record) } + end end class SalesLog < Log diff --git a/app/models/validations/sales_validations.rb b/app/models/validations/sales_validations.rb new file mode 100644 index 000000000..db1ae05c6 --- /dev/null +++ b/app/models/validations/sales_validations.rb @@ -0,0 +1,11 @@ +module Validations::SalesValidations + # Validations methods need to be called 'validate_' to run on model save + # or 'validate_' to run on submit as well + + def validate_beds(record) + # Integer(record.offered_before_type_cast) + if record.beds.present? && !record.beds.to_i.between?(1, 9) + record.errors.add :beds, "Number of bedrooms must be between 1 and 9" + end + end +end \ No newline at end of file diff --git a/spec/models/validations/sales_validations_spec.rb b/spec/models/validations/sales_validations_spec.rb new file mode 100644 index 000000000..22894f35f --- /dev/null +++ b/spec/models/validations/sales_validations_spec.rb @@ -0,0 +1,27 @@ +require "rails_helper" + +RSpec.describe Validations::SalesValidations do + subject(:property_validator) { property_validator_class.new } + + let(:property_validator_class) { Class.new { include Validations::SalesValidations } } + let(:record) { FactoryBot.create(:sales_log) } + + describe "#validate_beds" do + let(:expected_error) { "Number of bedrooms must be between 1 and 9" } + + it "does not add an error if offered is valid (number between 1 and 9)" do + record.beds = 9 + property_validator.validate_beds(record) + expect(record.errors).to be_empty + end + + it "does add an error if offered is invalid (number not between 1 and 9)" do + record.beds = 10 + property_validator.validate_beds(record) + expect(record.errors).eql?(expected_error) + record.beds = 0 + property_validator.validate_beds(record) + expect(record.errors).eql?(expected_error) + end + end +end \ No newline at end of file