如何在Rspec中测试文件大小

时间:2019-02-20 09:47:37

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

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

user_spec.rb

  private void Show_Dialog2()
    {
        UserDialogs.Instance.Alert("txt", "txt", "txt");
    }

factories / users.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

user.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

但是它返回

validate :avatar_size
...

private

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

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

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

1 个答案:

答案 0 :(得分:0)

问题在于样本数据。它大约有10MB,但是我正在使用resize_to_fit:[300,300],因此已压缩。我已经通过“ binding.pry”进行了检查,它小于5MB。

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