Skip to content

Commit

Permalink
[Validator] Handle case when all files are marked for destruction for…
Browse files Browse the repository at this point in the history
… attached validator (#88)
  • Loading branch information
Mth0158 committed Dec 19, 2023
1 parent dda77f5 commit 4cc5493
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/active_storage_validations/attached_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ def check_validity!
end

def validate_each(record, attribute, _value)
return if record.send(attribute).attached?
return if record.send(attribute).attached? &&
!Array.wrap(record.send(attribute)).all? { |file| file.marked_for_destruction? }

errors_options = initialize_error_options(options)

add_error(record, attribute, ERROR_TYPES.first, **errors_options)
end
end
Expand Down
15 changes: 15 additions & 0 deletions test/dummy/app/models/attached/validator/check.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# frozen_string_literal: true

# == Schema Information
#
# Table name: attached_validator_checks
#
# id :integer not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
#

class Attached::Validator::Check < ApplicationRecord
has_one_attached :has_to_be_attached
validates :has_to_be_attached, attached: true
end
28 changes: 28 additions & 0 deletions test/validators/attached_validator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,34 @@
# Checked by Rails options tests
end

describe 'Validator checks' do
let(:model) { validator_test_class::Check.new(params) }

describe 'when provided with a file' do
# validates :has_to_be_attached, attached: true
subject { model.has_to_be_attached.attach(image_1920x1080_file) and model }

it { is_expected_to_be_valid }
end

describe 'when not provided with a file' do
# validates :has_to_be_attached, attached: true
subject { model }

it { is_expected_not_to_be_valid }
it { is_expected_to_have_error_message("blank", error_options: {}) }
end

describe 'when provided with a file that is marked for destruction' do
# validates :has_to_be_attached, attached: true
subject { model.has_to_be_attached.attach(image_1920x1080_file) and model.has_to_be_attached.mark_for_destruction and model }

focus
it { is_expected_not_to_be_valid }
it { is_expected_to_have_error_message("blank", error_options: {}) }
end
end

describe 'Rails options' do
%i(allow_nil allow_blank).each do |unsupported_validation_option|
describe ":#{unsupported_validation_option}" do
Expand Down

0 comments on commit 4cc5493

Please sign in to comment.