我想解決的問題
我希望 Rspec 補丁或測驗成功。在此之前我也測驗過PostsContoroller,我很困惑,因為我在測驗PostsContoroller時沒有得到同樣的錯誤。
錯誤
Failures:
1) Api::V1::PostItemsController update Update Content
Failure/Error: patch :update, params: { post: post_params }
ActionController::UrlGenerationError:
No route matches {:action=>"update", :controller=>"api/v1/post_items", :post=>{:id=>1, :content=>"Update-Content", :status=>false, :post_id=>1}}
# ./spec/controllers/post_items_spec.rb:11:in `block (3 levels) in <main>'
Finished in 0.35529 seconds (files took 5.58 seconds to load)
5 examples, 1 failure
代碼
工廠機器人
書本.rb
FactoryBot.define do
factory :book, class: Post do
sequence(:id) { |n| n}
sequence(:title) { |n| "title#{n}" }
sequence(:author) { |n| "author#{n}" }
sequence(:image) { |n| "image#{n}"}
end
end
內容.rb
FactoryBot.define do
factory :content, class: PostItem do
sequence(:id) { |n| n }
sequence(:content) { |n| "list#{n}"}
sequence(:status) { false }
end
end
規格
post_items_spec.rb
require 'rails_helper'
RSpec.describe Api::V1::PostItemsController, type: :controller do
describe 'update' do
it 'Update Content' do
book = create(:book)
content = create(:content, post_id: book.id)
post_params = { id: content.id, content: 'Update-Content', status: false, post_id: book.id }
patch :update, params: { post: post_params }
json = JSON.parse(response.body)
expect(response.status).to eq(200)
expect(json['Update-Content']).to eq('Update-content')
end
end
end
路線
**Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :posts
resources :post_items
end
end
end
uj5u.com熱心網友回復:
Rails 和 RSpec 團隊都不鼓勵使用控制器規范,并且已經有很長一段時間了。您應該撰寫一個請求規范,而不是發送真正的 HTTP 請求。
RSpec.describe 'Api V1 Post items', type: :request do
let(:book) { create(:book) }
describe "PATCH /api/v1/books" do
context "with valid parameters" do
subject do
patch api_v1_post_item_path(book),
params: { content: 'Update-Content' }
end
it { should be_successful }
it "updates the content" do
# refresh the record from the db
expect { book.reload }.to change(book, :title).to('Update-Content')
end
it "includes the updated entity in the response body" do
expect(response.parsed_body['content']).to eq 'Update-Content'
end
end
# @todo write specs with invalid parameters
# @todo write specs for authentication and authorization
end
end
另一個問題是您在工廠中生成 ID。永遠不要這樣做。當您實際保存記錄時,資料庫將自動分配 ID。當你使用build_stubbedFactoryBot 時會創建一個 mock id。使用序列生成 ID 會招致不良做法,例如將 ID 硬編碼到規范中,只會讓您頭疼。
如果您真的想挽救該控制器規范,則路由錯誤是由于您缺少 ID 引數這一事實引起的 - 因為您呼叫它是因為patch :update, params: { post: post_params }id 引數被埋在params[:post][:id]. 所以你想要patch :update, params: { id: post.id, post: post_params }我不推薦這個 - 使用該程式并撰寫未來的證明測驗,而不是讓所有的錯誤都溜走。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/416951.html
標籤:
上一篇:Mongo::Error::UnsupportedFeatures(位于(localhost:27017)的服務器報告有線版本(2),但此版本的Ruby驅動程式至少需要(6)。)
