我试图弄清楚如何使用Fabrication和Rspec宝石测试文件附件。手动测试网站时文件上传工作正常,没有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
以下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
答案 0 :(得分:2)
1)我必须修改我在“更新#1”中提到的Fabricator来解决我的问题。这是使用Rack :: Test :: Upload.new
的Fabricator的一种更简单的格式Fabricator(:application) do
email Faker::Internet.email
name Faker::Name.name
resume_url {
Rack::Test::UploadedFile.new(
"./spec/support/files/hey_look_a_pdf_pdf_lolz.pdf",
"application/pdf"
)
}
end
2)我使用的是Fabricator.build(:application).attributes
,它与文件附件不兼容。相反,我开始使用Fabricator.attributes_for(:application)
,一切都开始运作良好。这是过客。
describe ApplicationsController do
context "PUT /applications/:id" do
let(:job) { Fabricate(:job) }
let(:application) do
Fabricate.attributes_for(
:application,
email: "old@example.com",
id: SecureRandom.uuid,
job_id: job.id
)
end
it "creates an application" do
expect { put(
:update,
application: application,
id: application["id"]
)}.to change{Application.count}.from(0).to(1)
end
end
end