password_policy_spec.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. require 'rails_helper'
  2. RSpec.describe PasswordPolicy do
  3. subject(:instance) { described_class.new('some_password') }
  4. let(:passing_job_class) { make_job_class(valid: true, applicable: true, error: 'passing job') }
  5. let(:failing_job_class) { make_job_class(valid: false, applicable: true, error: 'failing job') }
  6. let(:another_failing_job_class) { make_job_class(valid: false, applicable: true, error: 'another failing job') }
  7. let(:not_applicable_job_class) { make_job_class(valid: false, applicable: false, error: 'not applicable job') }
  8. describe '#valid?' do
  9. it 'returns true when all backends pass' do
  10. instance.backends = Set.new [passing_job_class]
  11. expect(instance).to be_valid
  12. end
  13. it 'returns false when one of backends fail' do
  14. instance.backends = Set.new [passing_job_class, failing_job_class]
  15. expect(instance).not_to be_valid
  16. end
  17. it 'returns true when one of backends fail but is not applicable' do
  18. instance.backends = Set.new [passing_job_class, not_applicable_job_class]
  19. expect(instance).to be_valid
  20. end
  21. end
  22. describe '#error' do
  23. it 'returns nil when no errors present' do
  24. instance.backends = Set.new
  25. expect(instance.error).to be_nil
  26. end
  27. it 'returns Array with the error when an error is present' do
  28. instance.backends = Set.new [failing_job_class]
  29. expect(instance.errors.first).to eq(['failing job'])
  30. end
  31. it 'returns Array with the first error when multiple errors are present' do
  32. instance.backends = Set.new [another_failing_job_class, failing_job_class]
  33. expect(instance.errors.first).to eq(['another failing job'])
  34. end
  35. end
  36. describe '#errors' do
  37. it 'returns empty Array when all backends pass' do
  38. instance.backends = Set.new [passing_job_class]
  39. expect(instance.errors).to be_kind_of(Array).and(be_blank)
  40. end
  41. it 'returns an Array of Arrays when one of backends fail' do
  42. instance.backends = Set.new [failing_job_class]
  43. expect(instance.errors.first).to be_kind_of(Array)
  44. end
  45. end
  46. def make_job_class(valid:, applicable:, error:)
  47. klass = Class.new(PasswordPolicy::Backend)
  48. klass.define_method(:valid?) { valid }
  49. klass.define_singleton_method(:applicable?) { applicable }
  50. klass.define_method(:error) { [error] }
  51. klass
  52. end
  53. end