Browse Source

add compound validation for bedsit

CLDC-858-no-of-beds-validation-sales
Ted-U 2 years ago
parent
commit
197cc5e46c
  1. 7
      app/models/sales_log.rb
  2. 19
      app/models/validations/sales_validations.rb
  3. 27
      spec/models/validations/sales_validations_spec.rb

7
app/models/sales_log.rb

@ -1,5 +1,10 @@
class SalesLogValidator < ActiveModel::Validator 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 end
class SalesLog < Log class SalesLog < Log

19
app/models/validations/sales_validations.rb

@ -0,0 +1,19 @@
module Validations::SalesValidations
# Validations methods need to be called 'validate_<page_name>' 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

27
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
Loading…
Cancel
Save