The 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
The test which 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 a 20 MB file into the repo just to test this. Is there a way similar to the one I tried above that will actually work?
The best way I've done this is to use the built-in shoulda matchers for Paperclip. The documentation at that link is really good, but here's an overview from the docs of what you can do with it:
In spec_helper.rb, you'll need to require the matchers:
require "paperclip/matchers"
And include the module:
Spec::Runner.configure do |config|
config.include Paperclip::Shoulda::Matchers
end
Example that validates the attachment size:
describe User do
it { should validate_attachment_size(:avatar).
less_than(2.megabytes) }
end
If you're interested, the source for the matchers can be found on GitHub
来源:https://stackoverflow.com/questions/14789060/how-can-i-use-rspec-to-test-that-a-model-using-paperclip-is-validating-the-size