规范中重新加载后 ActiveStorage 附件未关联

ActiveStorage attachment not associated after reload in specs

我想测试文件是否正确附加到记录。

我有一个带缩略图的通知模型。

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_id0

#<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 一起使用,正如 big red box in the setup section 警告的那样。

2.7.0 :001 > "2a".to_i
 => 2
2.7.0 :002 > "a2".to_i
 => 0