【问题标题】:Testing Paperclip Attachment Filesize测试回形针附件文件大小
【发布时间】:2014-03-13 09:49:41
【问题描述】:

如果我想无条件地测试回形针附件的文件大小,我可以使用包含的标准匹配器:

it { should validate_attachment_size(:image).less_than(10.megabytes) }

但是我不希望附件成为必需项。因此,如果有附件,我只想测试附件大小。

我可以使用:

validates_attachment_size :image, less_than: 10.megabytes,
                          if: Proc.new {|model| model.image.exists?}

但是,这会导致断言失败:

1) NewsItem should validate the size of attachment image
   Failure/Error: it { should validate_attachment_size(:image).less_than(10.megabytes) }
   Attachment image must be between  and 10485760 bytes
   # ./spec/models/news_item_spec.rb:15:in `block (2 levels) in <top (required)>'

据我所知,通过删除image 来测试验证。但是,如果image 不存在,我使用 Proc 来避免验证,这意味着验证不会运行。

我应该如何解决这个问题?

【问题讨论】:

  • 不确定它是否适用于回形针验证,但是否可以在验证中添加 allow_nil: true 选项?理论上,如果没有提供附件,这应该跳过验证。
  • @rails4guides.com 不幸的是,它不适用于回形针验证。

标签: ruby-on-rails rspec ruby-on-rails-4 paperclip shoulda


【解决方案1】:

我将此验证用于回形针

# Paperclip
attr_accessible :imagem
has_attached_file :imagem, path: "public/produtos/:id/:style", url: "/produtos/:id/:style", default_url: 'missing/thumb.png'
validates_attachment_size :imagem, less_than: 10.megabyte
validates_attachment_content_type :imagem, content_type: ['image/jpeg', 'image/png', 'image/gif']

default_url:设置默认图片,如果对象没有图片。

【讨论】:

    猜你喜欢
    • 2013-01-26
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多