将Active Storage文件附加到灯具

时间:2018-07-18 21:47:41

标签: ruby-on-rails ruby-on-rails-5 fixtures rails-activestorage

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

灯具如何?

在模型中使用has_one_attached :file时,我尝试了键filefile_attachments,但是它不起作用。

我是否必须为ActiveStorage::Attachment和/或ActiveStorage::Blob明确创建灯具文件?

1 个答案:

答案 0 :(得分:2)

在测试中,我发现必须使用fixture_file_upload进行附加。这是RSpec中的2个示例,但是我相信fixture_file_upload方法也应在minitest中起作用。关键是在顶部包含ActionDispatch::TestProcess(除非您使用的是minitest,否则我认为不包含include即可使用)。

附件文件保存在: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

请求规范

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