我確認在我的模型,validate :picture_size
,我的模型試驗驗證:Rails。圖片大小
class Post < ApplicationRecord
belongs_to :user
default_scope -> { order(created_at: :desc) }
mount_uploader :picture, PictureUploader
validates :content, presence: true,
length: { maximum: 50_000 }
validates :theme, presence: true,
length: { minimum: 3, maximum: 100 },
uniqueness: { case_sensitive: false }
validates :picture, presence: true
validate :picture_size
def to_param
random_link
end
private
def picture_size
return unless picture.size > 5.megabytes
errors.add(:picture, 'Файл должен быть меньше, чем 5МБ')
end
end
我上傳:
class PictureUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
process resize_to_limit: [600, 300]
storage :file
def default_url
ActionController::Base.helpers.asset_path("default/no-photo-wide.png")
end
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_white_list
%w(jpg jpeg gif png)
end
end
而且它工作得很好,當我運行軌道服務器。但是我寫了幾個測試,並且真的不知怎麼避免驗證並將圖片上傳到我的商店目錄。
我的測試:
let(:large_image) { Rack::Test::UploadedFile.new(File.open(File.join(Rails.root, '/spec/images/large-image.jpg'))) }
it 'will give error if picture is more then 5mb' do
post = Post.new(theme: 'foo', content: 'bar)
post.picture = large_image
post.save
puts Post.first.picture
expect(post.valid?).to be false
end
但結果是true
,不false
。有人可以告訴我在哪裏犯了我的錯誤或建議任何其他方式來測試圖片大小驗證?
更新'picture_size'並添加調試'把picture.size',看看圖像具有測試 –
@dziamber做了適當的大小,它返回91990(不太明白這是什麼意思,如果圖片的實際尺寸是6,138 mb) –
您正在使用回形針上傳圖片或任何其他寶石? –