2013-02-09 35 views
3

模型:如何使用Rspec来测试使用Paperclip的模型是否验证上传文件的大小?

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的文件到回购只是为了测试这一点。有没有类似于我上面尝试过的那种方法实际上可行?

+0

添加一个模拟的文件,它的功能大小应该做的伎俩 – scones 2013-02-09 14:25:04

+0

我猜你正在使用'早该-matchers'不已经有validate_size_of匹配内置的原因很明显。 第二件事是,我担心你会需要像你提到的那样粗暴地写测试。 – 2013-02-09 14:25:35

回答

6

我这样做的最好方法是使用内置的shoulda matchers for Paperclip。在该链接的文档是非常好的,但这里是从,你可以用它做什么的文档的概述:

在spec_helper.rb,你需要要求的匹配:

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 

如果你有兴趣,对匹配器的来源可以是found on GitHub

+0

谢谢。我不会在spec_helper中获得包含位。 – 2013-02-09 14:49:05