我试图弄清楚如何使用 Fabrication 和 Rspec gem 测试文件附件。手动测试站点时,文件上传工作正常,只是没有 Rspec 覆盖。问题似乎是我不知道如何在 PUT 请求中包含附件。
如何在此测试中添加文件附件,最好使用制造商
制造商:
Fabricator(:application) do
email Faker::Internet.email
name Faker::Name.name
resume_url { File.open(
File.join(
Rails.root,
"spec",
"support",
"files",
"hey_look_a_pdf_pdf_lolz.pdf"
)
)
}
end
控制器:
class ApplicationsController < ApplicationController
def update
@application = Application.find_or_initialize_by(id: params[:id])
if @application.update(application_params)
flash[:success] = "Application has been saved :)"
redirect_to application_path(@application)
else
render :edit
end
end
private
def application_params
params[:application].permit(:email, :job_id, :name, :resume_url)
end
end
控制器测试
require "spec_helper"
# this is a sample application attributes being passed into controller
# it should have a file attachment, but haven't figured out how to do that
#
# {
# "id"=>"fa446fdf-b82d-48c0-8979-cbbb2de4fb47",
# "email"=>"old@example.com",
# "name"=>"Dr. Rebeca Dach",
# "resume_url"=>nil,
# "job_id"=>"cf66dbcf-d110-42cc-889b-0b5ceeeed239",
# "created_at"=>nil,
# "updated_at"=>nil
# }
describe ApplicationsController do
context "PUT /applications/:id" do
it "creates an application" do
expect { put(
:update,
application: application.attributes,
id: application.id
)}.to change{Application.count}.from(0).to(1)
end
end
end
更新#1
以下 Fabricator 似乎可以正常工作。我仍然无法让文件附件在控制器测试中工作。
Fabricator(:application) do
email Faker::Internet.email
name Faker::Name.name
resume_url { ActionDispatch::Http::UploadedFile.new(
tempfile: File.new(Rails.root.join(
"./spec/support/files/hey_look_a_pdf_pdf_lolz.pdf"
)),
filename: File.basename(File.new(Rails.root.join(
"./spec/support/files/hey_look_a_pdf_pdf_lolz.pdf"
)))
)}
end