How can I use Rspec to test that a model using Paperclip is validating the size of an uploaded file?

别来无恙 提交于 2019-12-05 03:01:30

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!