I have installed this gem to validate and test active storage:
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
When I run all tests together everything seems to be working well, but when I run only model specs, it hangs! Why?! 😳
$ rspec spec/models
.....
It is a matter of correct configuration of 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
I found the answer here: https://stackoverflow.com/a/62310984/7896107