我想测试一个文件是否正确地附加到了一个记录上。
我有一个带有缩略图的通知模型。
class Notification < ApplicationRecord
has_one_attached :thumbnail
end
我正在通过活动作业使用sidekiq。
# config/application.rb
module MyApp
class Application < Rails::Application
config.active_job.queue_adapter = :sidekiq
end
end
我已经将存储适配器设置为本地文件系统,并立即执行作业
# config/environments/test.rb
Rails.application.configure do
config.active_storage.service = :test
config.active_job.queue_adapter = :inline
end
我有以下使用水豚和硒的规格:
it 'creates the model' do
click_on class: 'create-action'
attach_file('notification[thumbnail]', Rails.root.join('spec/fixtures/uploads/notification_thumbnail.jpg'))
fill_in 'notification[title]', with: 'MyString'
expect do
click_on 'Create notification'
end.to change { ActiveStorage::Attachment.count }.by(1)
new_notification = Notification.order(created_at: :desc).first
expect(page).to have_content(I18n.t('successfully_created_resource', resource: 'MyString'))
new_notification.reload
expect(new_notification.thumbnail).to be_attached
end
为了进一步研究,我创建了一个简单的规范:
it 'has an attached thumbnail' do
notification = build(:notification)
notification.thumbnail = fixture_file_upload(Rails.root.join('spec/fixtures/uploads/notification_thumbnail.jpg'), 'image/jpg')
notification.save
puts ActiveStorage::Blob.order(created_at: :desc).first.attachments.inspect
expect(notification.thumbnail).to be_attached
expect(notification.reload.thumbnail).to be_attached
end
第一个期望总是会过去,而后者有时会失败。
查看附件时,它有record_id
0
#<ActiveRecord::Associations::CollectionProxy [#<ActiveStorage::Attachment id: 1, name: "thumbnail", record_type: "Notification", record_id: 0, blob_id: 1, created_at: "2020-11-30 10:40:28">]>
有人能向我解释这种行为吗?并给我一些如何正确避免它/编写测试的建议吗?
在调查另一个错误时,我意识到ActiveStorage并没有像设置部分的红色大框警告的那样设置为与UUID一起使用。
2.7.0 :001 > "2a".to_i
=> 2
2.7.0 :002 > "a2".to_i
=> 0