Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/file_validators/validators/file_size_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions spec/lib/file_validators/validators/file_size_validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
16 changes: 16 additions & 0 deletions spec/support/matchers/allow_file_size_on_nil_activesupport_file.rb
Original file line number Diff line number Diff line change
@@ -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