How can I use Rspec to check that the model using Paperclip is checking the size of the uploaded file?
Model:
class Attachment < ActiveRecord::Base
belongs_to :narrative
attr_accessible :description, :user_id, :narrative_id
has_attached_file :file
validates_presence_of :user_id
validates_presence_of :narrative_id
validates_attachment :file, :presence => true,
:size => {:less_than => 20.megabytes}
end
Test that doesn't work:
describe Attachment do
it { should validate_presence_of :file }
it { should validate_size_of :file } # validate_size_of does not exist
end
I would like to avoid dumping the 20MB file in the repo in order to test this. Is there a way similar to the one I tried above that will actually work?
+3
source to share
1 answer
The best way I've done this is using the built-in socket helpers for Paperclip . The documentation for this link is really good, but here's an overview from the docs on what you can do with it:
In spec_helper.rb you need helpers:
require "paperclip/matchers"
And enable the module:
Spec::Runner.configure do |config|
config.include Paperclip::Shoulda::Matchers
end
An example confirming the size of the attachment:
describe User do
it { should validate_attachment_size(:avatar).
less_than(2.megabytes) }
end
If you're interested, the source for sockets can be found on GitHub
+6
source to share