【问题标题】:Attach Active Storage file to fixtures将 Active Storage 文件附加到灯具
【发布时间】:2018-12-26 22:20:03
【问题描述】:

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

固定装置怎么样?

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

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

【问题讨论】:

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


【解决方案1】:

在我的测试中,我发现我必须使用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

请求规范

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

【讨论】:

  • 也许我的问题不够清楚,但我说的是在 YAML 夹具文件中附加文件,而不是在测试中。
  • 看起来有可能:stackoverflow.com/questions/50453596/… 虽然我同意这个答案的结论,但有比使用 .attachfixture_file_upload 将其放入 YAML 更简单的测试方法跨度>
猜你喜欢
  • 1970-01-01
  • 2019-06-22
  • 2020-11-04
  • 1970-01-01
  • 2018-09-28
  • 2019-11-01
  • 1970-01-01
  • 2019-08-16
  • 1970-01-01
相关资源
最近更新 更多