From c140b79b7b16303a864b12becbc1d42d13f4ecbf Mon Sep 17 00:00:00 2001 From: Edward Prendergast Date: Wed, 8 Aug 2018 12:14:21 +0100 Subject: [PATCH] Support nil activestorage objects Fixes "Module::DelegationError: size delegated to attachment, but attachment is nil" --- .../validators/file_size_validator.rb | 2 ++ .../validators/file_size_validator_spec.rb | 11 +++++++++++ .../allow_file_size_on_nil_activesupport_file.rb | 16 ++++++++++++++++ 3 files changed, 29 insertions(+) create mode 100644 spec/support/matchers/allow_file_size_on_nil_activesupport_file.rb diff --git a/lib/file_validators/validators/file_size_validator.rb b/lib/file_validators/validators/file_size_validator.rb index 026cfa2..8ddf283 100644 --- a/lib/file_validators/validators/file_size_validator.rb +++ b/lib/file_validators/validators/file_size_validator.rb @@ -60,6 +60,8 @@ def check_options(klass, options) def value_byte_size(value) if value.respond_to?(:byte_size) value.byte_size + elsif value.respond_to?(:attached?) + value.size if value.attached? else value.size end diff --git a/spec/lib/file_validators/validators/file_size_validator_spec.rb b/spec/lib/file_validators/validators/file_size_validator_spec.rb index 4b65467..ab64753 100644 --- a/spec/lib/file_validators/validators/file_size_validator_spec.rb +++ b/spec/lib/file_validators/validators/file_size_validator_spec.rb @@ -208,4 +208,15 @@ def build_validator(options) expect { build_validator in: 5.kilobytes }.to raise_error(ArgumentError) end end + + ## + # trying to call #size on an ActiveStorage attachment + # causes errors when it is not defined e.g. + # "Module::DelegationError: size delegated to attachment, but attachment is nil" + context 'on ActiveStorage attachment' do + before { build_validator greater_than: 5.kilobytes } + + it { is_expected.not_to allow_file_size_on_nil_activesupport_file(6.kilobytes, @validator, + message: "Avatar file size must be greater than #{@storage_units[5120]}") } + end end diff --git a/spec/support/matchers/allow_file_size_on_nil_activesupport_file.rb b/spec/support/matchers/allow_file_size_on_nil_activesupport_file.rb new file mode 100644 index 0000000..a04311d --- /dev/null +++ b/spec/support/matchers/allow_file_size_on_nil_activesupport_file.rb @@ -0,0 +1,16 @@ +RSpec::Matchers.define :allow_file_size_on_nil_activesupport_file do |size, validator, message| + match do |model| + value = double + allow(value).to(receive(:size).and_raise(Module::DelegationError, "size delegated to attachment, but attachment is nil")) + allow(value).to(receive(:attached?).and_return(false)) + + allow_any_instance_of(model).to receive(:read_attribute_for_validation).and_return(value) + dummy = model.new + validator.validate(dummy) + if message.present? + dummy.errors.full_messages.exclude?(message[:message]) + else + dummy.errors.empty? + end + end +end