【问题标题】:how to test file size in Rspec如何在 Rspec 中测试文件大小
【发布时间】:2019-02-23 16:48:34
【问题描述】:

我是 Rspec 的新手。我想通过夹具目录中超过 10Mb 的图像来测试文件大小。

user_spec.rb

require 'carrierwave/test/matchers'
...

it "is invalid avatar size" do
  image_path = File.join(Rails.root, "spec/fixtures/sample.jpg")
  user = FactoryBot.build(:user, avatar: File.open(image_path))
  user.valid?
  expect(user.errors[:avatar]).to include("should be less than 5MB")
end

工厂/用户.rb

FactoryBot.define do
  factory :user do
    name "Donald Fagen"
    username "donald"
    email "donald-fagen@gmail.com"
    password "Thenightfly"
    avatar { Rack::Test::UploadedFile.new(Rails.root.join('spec/fixtures/sample.jpg'), 'image/jpg') }
  end
end

用户.rb

validate :avatar_size
...

private

  def avatar_size
    if avatar.size > 5.megabytes
      errors.add(:avatar, "should be less than 5MB")
    end
  end

但它会返回

1) User validations test invalid information is invalid avatar size
     Failure/Error: expect(user.errors[:avatar]).to include("should be less than 5MB")
       expected [] to include "should be less than 5MB"

看起来 avatar_size 方法不起作用。我应该在构建用户对象后保存到 avatar_size 吗?请告诉我如何检查文件大小。

  • 导轨:5.1.6
  • rspec-rails: 3.8.1
  • factory_bot_rails:4.11.1

【问题讨论】:

    标签: ruby-on-rails rspec factory-bot


    【解决方案1】:

    问题在于样本数据。它大约是 10MB,但我使用的是 resize_to_fit: [300, 300],所以它被压缩了。我通过“binding.pry”检查过,它小于 5MB。

    [3] pry(#<RSpec::ExampleGroups::User::ValidationsTest::InvalidInformation>)> @user.avatar.size
    => 43866
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 2015-08-04
      • 2023-03-21
      • 2012-05-18
      • 1970-01-01
      相关资源
      最近更新 更多