【问题标题】:How do you test a specific image file extension in Rails?如何在 Rails 中测试特定的图像文件扩展名?
【发布时间】:2021-03-17 14:11:31
【问题描述】:

我有一个自定义验证,以防止为帐户 logo 上传 JPG 或 PNG 以外的图像文件类型。

是否可以存根具有特定文件扩展名的文件来测试处理上传的控制器的补丁操作?

这是自定义验证的样子:

has_one_attached :logo

validate :correct_logo_file_type

def correct_logo_file_type
    if logo.attached? && !logo.content_type.in?(%w(image/jpg image/png))
      errors.add(:logo, :incorrect_file_type)
    end
end

【问题讨论】:

  • 一个你可以做的而不是拥有函数的方法是将它写成:validates_format_of :image, with: %r{\.(png|jpg|jpeg)$}i, message: "your message"

标签: ruby-on-rails file validation minitest


【解决方案1】:

ACCEPTABLE_TYPES = ['image/png', 'image/gif'].freeze

has_one_attached :screenshot, 依赖: :destroy

验证 :acceptable_image

私人

定义可接受的图像

返回 true 除非 screenshot.attached?

errors.add(:screenshot, 'must be a PNG or GIF') unless ACCEPTABLE_TYPES.include?(screenshot.content_type)

结束

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多