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

Mat*_*son 3 ruby rspec ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)

测试不起作用:

describe Attachment do
  it { should validate_presence_of :file }
  it { should validate_size_of :file } # validate_size_of does not exist
end
Run Code Online (Sandbox Code Playgroud)

我想避免将一个20 MB的文件转储到repo中来测试它.有没有一种方法类似于我上面尝试过的实际工作方式?

Pet*_*own 7

我这样做的最好方法是使用Paperclip内置的shoulda匹配器.该链接的文档非常好,但是这里有一个关于你可以用它做什么的文档的概述:

在spec_helper.rb中,您需要要求匹配器:

require "paperclip/matchers"
Run Code Online (Sandbox Code Playgroud)

并包括模块:

Spec::Runner.configure do |config|
  config.include Paperclip::Shoulda::Matchers
end
Run Code Online (Sandbox Code Playgroud)

验证附件大小的示例:

describe User do
  it { should validate_attachment_size(:avatar).
                less_than(2.megabytes) }
end
Run Code Online (Sandbox Code Playgroud)

如果您有兴趣,可以在GitHub上找到匹配器的来源