我有一个带有以下代码的控制器。
def apply
file_id = params[:file_id]
if file_id.nil? && params[:file].nil?
render json: '"No resume was provided"', status: :unprocessable_entity
return
end
if params[:job_id].nil?
render json: '"Invalid data was posted"', status: :unprocessable_entity
return
end
job = Job.find(params[:job_id]) if Job.exists?(params[:job_id])
if job.nil?
render json: '"Unable to locate job for application"', status: :unprocessable_entity
return
end
if file_id.nil? || file_id.to_i == 0
resume = ApiController.save_file job.owner
else
resume = UploadedFile.find(file_id)
end
resume.person = ApiController.save_person(job.owner)
resume.save_by(job.owner)
render json: '"successfully saved application"', status: 200
end
def self.save_file(owner)
resume = UploadedFile.new
resume.attachment = params[:file]
resume.owner = owner
unless resume.save_by(User.system)
render json: '"There was an error uploading this file, please make sure the file type is an accepted file type."', status: :unprocessable_entity
return
end
return resume
end
def self.save_person(owner)
person = Person.new(apply_params.permit(:first_name, :last_name, :zip))
...
result = person.save_by(owner)
unless result
render json: '"Errors occurred while saving person."', status: :unprocessable_entity
return
end
return person
end
我试图单独测试所有3个方法,但由于apply方法调用了save_file和save_person方法,我认为我需要在测试apply方法时将它们存根,对吧?所以,这让我想到了这段代码......
describe 'apply' do
before(:each) do
@file = Rack::Test::UploadedFile.new(Rails.root.join('spec/fixtures/files/test-resume.txt'), 'plain/text')
@fake_uploaded_file = UploadedFile.new
@fake_job = Job.new
@fake_job.id = 1
@fake_person = Person.new
allow(Job).to receive(:find).and_return(@fake_job)
allow(Job).to receive(:exists?).and_return(true)
allow(UploadedFile).to receive(:find).and_return(@fake_uploaded_file)
allow(controller).to receive(:save_file).and_return(@fake_uploaded_file)
allow(controller).to receive(:save_person).and_return(@fake_person)
end
it 'accepts an uploaded file and saves it' do
post :apply, file: @file, job_id:1, format: :json
expect(controller).to receive(:save_file)
end
end
当我尝试运行此测试时,我收到ApiController未实现的错误消息:save_file如何正确测试此apply方法以存根save_file和save_person方法?感谢。
答案 0 :(得分:0)
save_file和save_person方法是类方法。所以它们应该像这样存在。
allow(ApiController).to receive(:save_file).and_return(@fake_uploaded_file)
allow(ApiController).to receive(:save_person).and_return(@fake_person)