gpt4 book ai didi

ruby-on-rails - 我如何使用 Rspec 来测试使用 Paperclip 的模型是否正在验证上传文件的大小?

转载 作者:数据小太阳 更新时间:2023-10-29 07:48:21 24 4
gpt4 key购买 nike

模型:

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 的文件转储到存储库中只是为了测试它。有没有一种与我上面尝试过的方法类似的方法确实有效?

最佳答案

我做到这一点的最好方法是使用内置的 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

关于ruby-on-rails - 我如何使用 Rspec 来测试使用 Paperclip 的模型是否正在验证上传文件的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14789060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com