此问题可能是由于相同的文件名引起的,因此可以通过使用FactoryBot的序列来确保每个文件有唯一的名称来解决。以下是示例代码:
# 在factory文件中定义序列
FactoryBot.define do
factory :file_attachment, class: 'ActiveStorage::Attachment' do
record { nil }
blob { nil }
sequence(:name) { |n| "file_#{n}.jpg" }
after(:build) do |attachment, evaluator|
blob = evaluator.blob || create(:file_blob)
attachment.name ||= blob.filename
attachment.record ||= create(:post)
attachment.blob ||= blob
end
end
end
# 在测试中使用序列
describe Post do
let(:file_attachment) { build(:file_attachment) }
it 'creates a file attachment with a unique name' do
expect(file_attachment.name).not_to be_nil
expect(file_attachment.name).not_to eq build(:file_attachment).name
end
end