我已经安装了这个 gem 来验证和测试活动存储:
gem 'active_storage_validations'
gem 'shoulda-matchers', '~> 6.0'
# app/models/asset.rb
class Asset < ApplicationRecord
has_one_attached :portrait
validates(
:name,
presence: true,
uniqueness: true,
format: {
with: /\A[\w\.\-\(\)\+]+\z/s,
message: 'Only alphanumeric, and _-()+. characters are allowed.' # rubocop:disable Rails/I18nLocaleTexts
}
)
validates(
:portrait,
content_type: ['image/png', 'image/jpeg', 'image/svg+xml'],
dimension: { width: { in: 8..512 }, height: { in: 8..512 } },
size: { less_than: 250.kilobytes }
)
end
# spec/models/asset_spec.rb
require 'rails_helper'
RSpec.describe Asset do
subject(:asset) { build(:asset) }
it { is_expected.to validate_uniqueness_of :name }
it { is_expected.to allow_value('123-45+a_').for(:name) }
it { is_expected.not_to allow_value('123=').for(:name) }
it { is_expected.to validate_size_of(:portrait).less_than(250.kilobytes) }
end
# spec/support/active_storage.rb required by spec/rails_helper.rb
require 'active_storage_validations/matchers'
require 'ostruct'
RSpec.configure do |config|
config.include ActiveStorageValidations::Matchers
end
# spec/support/shoulda_matchers.rb required by spec/rails_helper.rb
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
# spec/factories/assets.rb
FactoryBot.define do
factory :asset do
name { "#{Forgery::Internet.user_name}#{Asset.count}" }
portrait { nil }
end
end
当我一起运行所有测试时,一切似乎都运行良好,但是当我仅运行模型规格时,它挂起!为什么?! 😳
$ rspec spec/models
.....
这是 Active Job 正确配置的问题:
# config/environments/test.rb
Rails.application.configure do
# Use inline job processing to make things happen immediately
config.active_job.queue_adapter = :inline
endd