如何使用 Rspec 来测试使用 Paperclip 的模型是否正在验证上传文件的大小? [英] How can I use Rspec to test that a model using Paperclip is validating the size of an uploaded file?
问题描述
模型:
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
不起作用的测试:
describe Attachment do
it { should validate_presence_of :file }
it { should validate_size_of :file } # validate_size_of does not exist
end
我想避免将 20 MB 的文件转储到 repo 中只是为了测试这个.有没有一种类似于我上面尝试过的方法可以实际工作?
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?
推荐答案
我这样做的最好方法是使用内置的 应该是 Paperclip 的匹配器.该链接上的文档非常好,但以下是您可以使用它做什么的文档的概述:
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:
在 spec_helper.rb 中,您需要要求匹配器:
In spec_helper.rb, you'll need to require the matchers:
require "paperclip/matchers"
并包含模块:
Spec::Runner.configure do |config|
config.include Paperclip::Shoulda::Matchers
end
验证附件大小的示例:
describe User do
it { should validate_attachment_size(:avatar).
less_than(2.megabytes) }
end
如果您有兴趣,可以在 GitHub 上找到匹配器的来源
If you're interested, the source for the matchers can be found on GitHub
这篇关于如何使用 Rspec 来测试使用 Paperclip 的模型是否正在验证上传文件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!