Ruby on rails 轨道。图片大小的测试验证

Ruby on rails 轨道。图片大小的测试验证,ruby-on-rails,ruby,rspec,rspec-rails,Ruby On Rails,Ruby,Rspec,Rspec Rails,我的模型中有验证,验证:图片大小,我的模型: class Post < ApplicationRecord belongs_to :user default_scope -> { order(created_at: :desc) } mount_uploader :picture, PictureUploader validates :content, presence: true, length: { maximum

我的模型中有验证,
验证:图片大小
,我的模型:

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
但结果是
true
,而不是
false
。有人能告诉我哪里出了错,或者建议其他方法来测试图片大小验证吗?

看看


您必须调用
picture.file.size.to\u f/(1000*1000)

来代替
picture.size



您必须调用
picture.file.size.to\u f/(1000*1000)

而不是
picture.size
来更新
picture\u size
并添加调试
put picture.size
,以查看图像的大小是否正确tests@dziamber完成后,返回91990(如果图片的实际大小为6138MB,则不太理解这意味着什么)您正在使用回形针上载图像或任何其他宝石?而不是
picture.size
尝试
File.size(图像路径)
@dziamber gem'carrierwave'Update
picture\u size
并添加调试
put picture.size
,以查看图像的大小是否正确tests@dziamber完成后,返回91990(如果图片的实际大小为6138 mb,我不太明白这意味着什么)您正在使用回形针上载图像或任何其他宝石?而不是
picture.size
尝试
File.size(图像路径)
@dziamber gem'carrierwave',但是如果在运行
rails服务器时有效,为什么我需要更改验证方法?只有在运行测试时才会中断?我不知道,除非您显示与此问题相关的所有代码。如果您只收到一次预期结果,那么并不意味着代码在每种情况下都能正常工作,即使我更改了对于您的回答,它仍然上传文件通过验证,但是出现了一些额外的错误测试。请为它粘贴整个模型和测试文件。但是,如果在运行
rails server
时有效,为什么我需要更改验证方法?只有在运行测试时才会中断?除非您显示与此问题相关的所有代码,否则我不知道。如果您收到预期结果一旦出现,并不意味着代码在每种情况下都能正常工作顺便说一句,即使我更改了您的答案,它仍然会上传文件通过验证,但会出现一些额外的错误测试。请为它粘贴整个模型和测试文件
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