将 Active Storage 文件附加到装置

gae*_*anm 5 ruby-on-rails fixtures ruby-on-rails-5 rails-activestorage

该文档仅显示将文件附加到模型的方法(http://edgeguides.rubyonrails.org/active_storage_overview.html#attaching-file-io-objects)。

固定装置怎么样?

在我的模型中,has_one_attached :file我尝试了按键filefile_attachments但不起作用。

我是否必须明确创建固定装置文件ActiveStorage::Attachment和/或ActiveStorage::Blob

one*_*one 2

在我的测试中,我发现我必须使用fixture_file_upload. 这是 RSpec 中的 2 个示例,但我相信该fixture_file_upload方法也应该适用于 minitest。关键是包含ActionDispatch::TestProcess在顶部(除非您使用的是 minitest,那么我认为它无需包含即可使用)。

附件文件保存在:spec/fixturs/files/filename.gif

附件型号规格

require 'rails_helper'
include ActionDispatch::TestProcess

RSpec.describe Whatever, type: :model do
  it 'is valid/invalid depending on file presence' do
    file = fixture_file_upload(Rails.root.join('spec/fixtures/files', 'parrot.gif'), 'image/gif')

    expect(SomeClass.new(an_attribute: 'something', file: file)).to be_valid

    expect(SomeClass.new(an_attribute: 'something').to be_invalid
  end
end
Run Code Online (Sandbox Code Playgroud)

请求规格

require 'rails_helper'
include ActionDispatch::TestProcess

RSpec.describe "whatever", type: :request do
  file = fixture_file_upload(Rails.root.join('spec/fixtures/files', 'parrot.gif'), 'image/gif')

  describe 'POST on whatever controller' do
    it 'saves the record when a file is attached' do
      expect{
        post whatever_path, params: { params: { file: file } }
      }.to change { WhateverModel.count }.by(1)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)