2014-05-06 77 views
0

我想弄清楚如何測試文件附件W /製作和Rspec寶石。當手動測試網站時,文件上傳工作正常,沒有Rspec覆蓋。問題似乎是我不知道如何在PUT請求中包含附件。定義製造商W /文件附件和測試文件上傳W/rspec

如何添加文件附件,優選地使用一個製造者,該試驗

製造商:

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"=>"[email protected]", 
# "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(: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 

回答

2

好的,我明白了。有兩件。

1)我不得不修複製造商,我在「Update#1」中提到我的問題。下面是一個使用機架製造者一個簡單的格式::測試:: Upload.new

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: "[email protected]", 
     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