From dc17cad1549825a86710eb44563274327ba345c0 Mon Sep 17 00:00:00 2001 From: Thor77 Date: Sun, 2 Dec 2018 13:51:54 +0100 Subject: [PATCH 1/2] Ensure uniqueness of generated Tournament.code --- app/models/tournament.rb | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/app/models/tournament.rb b/app/models/tournament.rb index 68b8495..3813f08 100644 --- a/app/models/tournament.rb +++ b/app/models/tournament.rb @@ -12,7 +12,16 @@ class Tournament < ApplicationRecord alias_attribute :owner, :user - after_initialize do |tournament| - tournament.code ||= SecureRandom.hex 3 + after_initialize :generate_code + + private + + def generate_code + return unless code.nil? + + loop do + self.code = SecureRandom.hex(3) + break if errors['code'].blank? + end end end From 8f88362264f3da5c06cc6b4924f98745fb764a72 Mon Sep 17 00:00:00 2001 From: Thor77 Date: Sun, 2 Dec 2018 13:53:26 +0100 Subject: [PATCH 2/2] Use code with only alphas for unqiue-validation Because in some ocassions a tournament code with only digits is generated which would fail this test because shoulda is not able to convert it to an uppercase version to test for case-sensitivity of the validation. --- spec/models/tournament_spec.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/spec/models/tournament_spec.rb b/spec/models/tournament_spec.rb index 5182e11..09a43af 100644 --- a/spec/models/tournament_spec.rb +++ b/spec/models/tournament_spec.rb @@ -10,7 +10,10 @@ RSpec.describe Tournament, type: :model do describe 'validation' do it { should validate_presence_of :name } it { should validate_presence_of :code } - it { should validate_uniqueness_of :code } + it do + tournament = create(:tournament, code: Faker::Dog.name) + expect(tournament).to validate_uniqueness_of :code + end it { should_not validate_presence_of :description } it { should_not validate_presence_of :public } end