2016-12-02 104 views
1

我確認在我的模型,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。有人可以告訴我在哪裏犯了我的錯誤或建議任何其他方式來測試圖片大小驗證?

+0

更新'picture_size'並添加調試'把picture.size',看看圖像具有測試 –

+0

@dziamber做了適當的大小,它返回91990(不太明白這是什麼意思,如果圖片的實際尺寸是6,138 mb) –

+0

您正在使用回形針上傳圖片或任何其他寶石? –

回答

0

看看https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Validate-attachment-file-size

而不是picture.size你必須調用picture.file.size.to_f/(1000*1000)

+0

但爲什麼我需要更改驗證方法,如果它運行時我運行'rails服務器',它只會打破如果測試運行? –

+0

我不知道,除非你顯示與這個問題有關的所有代碼。如果您收到預期的結果一次,那麼它並不意味着代碼在任何情況下都可以正常工作 –

+0

順便說一句,即使當我更改爲答案時,它仍然上傳文件通過驗證,但會出現一些額外的失敗測試 –