From c78c4ebc23b51a451697ec22d2a0b3e8556f3d91 Mon Sep 17 00:00:00 2001 From: Alex Kotov Date: Sun, 24 Mar 2019 19:27:18 +0500 Subject: [PATCH] Improve validation of Account#public_name, #biography --- app/models/account.rb | 12 +++++++----- spec/models/account_spec.rb | 32 ++++++++++++++++++++++++++++---- 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/app/models/account.rb b/app/models/account.rb index 6c9e548..e58e470 100644 --- a/app/models/account.rb +++ b/app/models/account.rb @@ -50,6 +50,8 @@ class Account < ApplicationRecord after_initialize :generate_username + before_validation :turn_blanks_into_nils + before_create :generate_guest_token ############### @@ -64,11 +66,6 @@ class Account < ApplicationRecord format: USERNAME_RE, uniqueness: { case_sensitive: false } - validates :public_name, - allow_nil: true, - allow_blank: false, - presence: true - validates :biography, length: { maximum: 10_000 } ########### @@ -119,4 +116,9 @@ private def generate_guest_token self.guest_token = SecureRandom.hex end + + def turn_blanks_into_nils + self.public_name = nil if public_name.blank? + self.biography = nil if biography.blank? + end end diff --git a/spec/models/account_spec.rb b/spec/models/account_spec.rb index 8426741..dc92891 100644 --- a/spec/models/account_spec.rb +++ b/spec/models/account_spec.rb @@ -96,18 +96,42 @@ RSpec.describe Account do end it { is_expected.to allow_value nil } - - it { is_expected.not_to allow_value '' } - it { is_expected.not_to allow_value ' ' } + it { is_expected.to allow_value '' } + it { is_expected.to allow_value ' ' } it { is_expected.to allow_value Faker::Name.name } it { is_expected.to allow_value Faker::Name.first_name } it { is_expected.to allow_value 'Foo Bar' } + + context 'when it was set to blank value' do + subject { create :personal_account, public_name: ' ' * rand(100) } + + specify do + expect(subject.public_name).to eq nil + end + end end describe '#biography' do - it { is_expected.not_to validate_presence_of :biography } + def allow_value(*) + super.for :biography + end + it { is_expected.to validate_length_of(:biography).is_at_most(10_000) } + + it { is_expected.to allow_value nil } + it { is_expected.to allow_value '' } + it { is_expected.to allow_value ' ' } + + it { is_expected.to allow_value Faker::Lorem.sentence } + + context 'when it was set to blank value' do + subject { create :personal_account, biography: ' ' * rand(100) } + + specify do + expect(subject.biography).to eq nil + end + end end describe '#has_role?' do