经过几个小时尝试自己解决这个问题。
当我在浏览器中完成所有操作时,一切都运行良好。仅当执行使用下一个类的测试(带有规范)时才会出现问题:
class Album < ApplicationRecord
has_one_attached :cover do |attachable|
attachable.variant :thumb, resize: '100x100'
attachable.variant :medium, resize: '400x400'
end
# Associations
has_many :songs, dependent: :destroy
# Validations
validates :title, :artist_name, presence: true
validates :cover, attached: true
end
class Song < ApplicationRecord
# Attachments
has_one_attached :audio
# Associations
belongs_to :album
# Scopes
scope :ordered, -> { order(disk_number: :asc, track_number: :asc) }
end
当我对专辑进行测试时,我认为测试没有任何问题,因为这是一个基本测试。但问题在于歌曲的测试:
RSpec.describe Song do
subject(:song) { create(:song, album:) }
let(:album) { create(:album, cover: file_fixture('cover.jpg')) }
describe 'associations' do
it { expect(song).to belong_to('album') }
end
describe 'validates' do
it do
expect(album).to validate_presence_of(:title)
expect(album).to validate_presence_of(:artist_name)
end
end
describe '#ordered' do
subject(:ordered) { described_class.ordered }
context 'when have only one disc' do
let(:song1) { create(:song, track_number: 1, album:) }
let(:song2) { create(:song, track_number: 2, album:) }
it 'returns array with correct ordered songs' do
expect(ordered).to eq([song, song2])
end
end
context 'when you have two disc and the same track number' do
let(:song1) { create(:song, track_number: 1, disk_number: 1, album:) }
let(:song2) { create(:song, track_number: 1, disk_number: 2, album:) }
it 'returns array with ordered by track and disc' do
expect(ordered).to eq([song1, song2])
end
end
end
...
end
执行此操作时...我得到下一个结果:
Song
associations
is expected to belong to album required: true
validates
is expected to validate that :artist_name cannot be empty/falsy
#ordered
when have only one disc
我看到这篇文章,我在其中读到仅使用 File.open ins Rails 7,因为使用其他选项我也遇到了同样的问题。
当到达这一点时,测试冻结了 90% 的时间(在 Intel 处理器中,在 ARM 处理器中为 60%)。我托盘了很多东西。但只有在 FactoryBot 中我尝试将图像附加到封面属性中时才失败:
FactoryBot.define do
factory :album do
title { 'MyString' }
artist_name { 'Artist' }
label { 'MyString' }
upc { 'MyString' }
release_date { '2024-03-24 13:14:12' }
cover { File.open('spec/fixtures/cover.jpg') }
end
end
我也尝试过使用“trait”来定义“cover”属性,但得到了相同的结果。但如果我不使用附件,那么测试就可以完美地工作。
test.log 有此消息(它是简历,因为它很长):
Error performing ActiveStorage::AnalyzeJob (Job ID: ee23c48f-38ed-4a96-a3f5-a3b11645a028) from Async(default) in 5.02ms: ActiveJob::DeserializationError (Error while trying to deserialize arguments: undefined method `clear' for nil):
在我的设置中:
config.active_storage.variant_processor = :mini_magick
因为我知道 ruby-vips 不是最好的选择,有时还会出现问题。
有人对此有所了解,或者有任何想法。
您可以像这样将文件附加到模型
trait :with_cover do
after(:create) do |album|
album.cover.attach(Rack::Test::UploadedFile.new("#{Rails.root}/spec/fixtures/cover.jpg"))
end
end