Rails-API 是一个用于构建 API 的 Rails 框架。活动存储(Active Storage)是 Rails 5.2 引入的一个功能,用于处理文件上传和附件管理。以下是如何在 Rails-API 中测试活动存储的基础概念和相关信息。
活动存储(Active Storage):
以下是一个简单的示例,展示如何在 Rails-API 中测试活动存储。
首先,确保你的 rails_helper.rb
或 spec_helper.rb
文件中包含以下内容:
require 'rails_helper'
RSpec.describe "Active Storage", type: :request do
let(:user) { create(:user) }
let(:file) { fixture_file_upload('files/test.jpg', 'image/jpeg') }
before do
sign_in user
end
end
RSpec.describe Attachment, type: :model do
it "attaches a file correctly" do
attachment = build(:attachment, file: file)
expect(attachment.file).to be_attached
end
end
RSpec.describe "Attachments", type: :request do
describe "POST /attachments" do
it "creates a new attachment" do
post "/attachments", params: { attachment: { file: file } }
expect(response).to have_http_status(:created)
expect(Attachment.last.file).to be_attached
end
end
describe "GET /attachments/:id/download" do
it "downloads the file" do
attachment = create(:attachment, file: file)
get "/attachments/#{attachment.id}/download"
expect(response).to have_http_status(:ok)
expect(response.content_type).to eq("image/jpeg")
end
end
describe "DELETE /attachments/:id" do
it "deletes the attachment" do
attachment = create(:attachment, file: file)
delete "/attachments/#{attachment.id}"
expect(response).to have_http_status(:no_content)
expect(Attachment.find_by(id: attachment.id)).to be_nil
end
end
end
问题1:文件上传失败
config/storage.yml
和 config/environments/test.rb
中的配置,确保文件大小限制和类型支持正确。问题2:文件下载链接无效
问题3:文件删除后仍然存在
purge_later
或 purge_now
方法来删除存储服务中的文件。通过以上步骤和示例代码,你应该能够在 Rails-API 中有效地测试活动存储功能。
没有搜到相关的文章