diff --git a/app/models/sales_log.rb b/app/models/sales_log.rb index 0f0ca54c7..f947064b6 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..a49c7b087 --- /dev/null +++ b/app/models/validations/sales_validations.rb @@ -0,0 +1,19 @@ +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 + + def validate_beds_proptype(record) + # Integer(record.offered_before_type_cast) + if record.beds.present? && record.beds.to_i != 1 && record.proptype == 2 + record.errors.add :beds, "A bedsit can not have more than 1 bedroom" + record.errors.add :proptype, "A bedsit can not have more than 1 bedroom" + end + end +end diff --git a/spec/models/validations/sales_validations_spec.rb b/spec/models/validations/sales_validations_spec.rb new file mode 100644 index 000000000..6dce00697 --- /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