Last Updated: February 25, 2016
·
3.259K
· zedtux

Paperclip validates_attachment_size with RSpec (>= 2.3.5 | <= 3.0.0)

I'm going to show you how to test with RSpec 1.3.2 the validatesattachmentsize validator for the gem paperclip between versions 2.3.5 and 3.0.0.

I'm upgrading a huge application from Rails 2.2.2 to 2.3.17. During this upgrade we decided to also upgrade paperclip to the latest version we can have.
So we are now using the version 2.7.5.

Fixing our specs I found one spec testing the validatesattachmentsize validator that wasn't working any more:

it "should validate size of file is less than 10Mb" do
  file = File.new("#{Rails.root}/spec/fixtures/file.txt")
  file.stub(:size).and_return(11.megabytes)

  @information.attachment = file
  @information.should_not be_valid
  @information.should have(1).error_on(:attachment)
end

RSpec is well stubbing the size attribute of the file, but the paperclip gem is not using directly the size attribute (or I mean at the end, it's not that one that is used).

Having a look at the gem code, I found that paperclip is calling the IOStream#to_tempfile to convert passed file into a stream.
Then the size of the stream is used to fill in the attachment_file_size field.

To fix this, Nick Sieger has implemented the following (commit ef7233d25700a7e69cebd2334b656fa9ca0ae927:

def to_tempfile(object)
  return object.to_tempfile if object.respond_to?(:to_tempfile)
  ...

This will save us! :-)

Now the passing spec is the following:

it "should validate size of file is less than 10Mb" do
  file = File.new("#{Rails.root}/spec/fixtures/file.txt")
  file.stub(:size).and_return(11.megabytes)
  file.stub(:to_tempfile).and_return(file)

  @information.attachment = file
  @information.should_not be_valid
  @information.should have(1).error_on(:attachment_file_size)
end

1 Response
Add your response

A way of doing this with FactoryGirl is to have it in the factory:

picture_file_name 'picture.jpg'
picture_content_type 'image/jpeg'
picture_file_size 1.megabyte
over 1 year ago ·