我已经安装了这个 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
当我一起运行所有测试时,一切似乎都运行良好,但是当我仅运行模型规格时,它挂起!为什么?! 😳
$ rspec spec/models
.....
我的答案并不理想,但我找到了解决方法。由于某些神秘的原因,Shoulda Matchers 挂在唯一性验证期望上。
it { is_expected.to validate_uniqueness_of :name }
它还挂有
expect(errors).to be_of_kind(:name, :taken)
。
subject(:asset) { build(:asset) }
it 'validates uniqueness of name' do
create(:asset, name: asset.name)
asset.validate
expect(asset.errors).to be_of_kind(:name, :taken)
end
尽管如此,它不会这样悬挂:
subject(:asset) { build(:asset) }
it 'validates uniqueness of name' do
create(:asset, name: asset.name)
asset.validate
expect(asset.errors.where(:name, :taken)).to be_truthy
end