【发布时间】:2023-03-31 14:35:02
【问题描述】:
当我尝试使用 RSpec 测试更新操作时遇到两个问题,这里是 controller 文件:
#volunteers_controller.rb
module Api
module V1
class VolunteersController < ApplicationController
before_action :find_volunteer, only: %i[show update destroy]
def update
@volunteer.update!(volunteer_params)
head :no_content
end
private
def find_volunteer
@volunteer = Volunteer.find_by!(id: params[:id])
end
def volunteer_params
params.require(:volunteer).permit(:image_url, :name, :job_desc)
end
end
end
end
这是test 文件:
require 'rails_helper'
RSpec.describe Api::V1::VolunteersController, type: :request do
...
describe '#update' do
let(:volunteer) { Volunteer.create!( :image_url=>"first.jpg", :name=>"test1", :job_desc=>"description") }
let(:params){
{:volunteer => {
"image_url"=>"new.jpg",
"name"=>"test1",
"job_desc"=>"description"
}
}
}
it 'updates a certain volunteer' do
patch :patch, :params => params #failed, bad URL
expect(volunteer.image_url).to eq("new.jpg") #failed, still return 'first.jpg'
end
it 'returns a no_content header' do
patch "http://localhost:3000/api/v1/volunteers/#{volunteer.id}", :params => params
expect(response).to have_http_status "204"
end
end
end
private
def json_parse(string)
if string.class==String
json = JSON.parse(string)
end
json
end
所以我的问题是:
- 当尝试编写这样的 URL 时:
patch :patch, :params => params,我收到以下错误:
Api::V1::VolunteersController#update updates a certain volunteer
Failure/Error: patch :patch, :params => params
URI::InvalidURIError:
bad URI(is not URI?): "http://www.example.com:80patch"
如何将 URL 更改为:"http://localhost:3000/api/v1/volunteers/#{volunteer.id}"?
- 我手动测试更新操作,将
binding.pry放入update操作,它确实更新了volunteer主题,但是,当它返回测试时,它显示它没有得到更新, 这是为什么?
谢谢!!
【问题讨论】:
-
@AbdullahFadhel 这显然是行不通的,因为这是一个请求规范,而不是控制器规范。
-
@AbdullahFadhel 无论如何谢谢!!
标签: ruby-on-rails ruby unit-testing testing rspec