-1
我正在做一些簡單的集成測試。我想測試用戶控制器中的sold_items操作。我已經確認路由存在並通過從瀏覽器訪問它返回json。但是,rspec告訴我路由不存在。請看下面,規格,錯誤和我的route.rb。謝謝!Rails/rspec,集成測試失敗,「無路由匹配」,但路由確實存在
規格:
require 'rails_helper'
RSpec.describe UsersController, type: :controller do
describe "GET #items" do
it "returns http success" do
user = FactoryGirl.create(:user)
get "users/#{user.id}/sold_items"
expect(response).to have_http_status(:success)
end
end
end
失敗消息:
1) UsersController GET #items returns http success
Failure/Error: get "users/#{user.id}/sold_items"
ActionController::UrlGenerationError:
No route matches {:action=>"users/10/sold_items", :controller=>"users"}
# ./spec/controllers/users_controller_spec.rb:8:in `block (3 levels) in <top (required)>'
的routes.rb
Rails.application.routes.draw do
resources :users
resources :items
get "users/:id/sold_items" => "users#sold_items"
EDIT
規格
require 'rails_helper'
RSpec.describe UsersController, type: :controller do
describe "GET #items" do
it "returns http success" do
user = FactoryGirl.create(:user)
get "users/:id/sold_items", id: user.id
expect(response).to have_http_status(:success)
end
end
end
失敗消息
2) UsersController GET #items returns http success
Failure/Error: get "users/:id/sold_items", id: user.id
ActionController::UrlGenerationError:
No route matches {:action=>"users/:id/sold_items", :controller=>"users", :id=>"12"}
# ./spec/controllers/users_controller_spec.rb:8:in `block (3 levels) in <top (required)>'
EDIT.2 MarvC第二建議
需要 'rails_helper'
RSpec.describe UsersController, type: [:request, :controller] do
describe "GET #items" do
it "returns http success" do
user = FactoryGirl.create(:user)
get "https://stackoverflow.com/users/:id/sold_items", id: user.id
expect(response).to have_http_status(:success)
end
end
end
失敗
看起來像用戶.ID未正確這裏傳遞
2) UsersController GET #items returns http success
Failure/Error: @sold_items = User.find(params[:id]).seller_items.sold
ActiveRecord::RecordNotFound:
Couldn't find User with 'id'=:id
# ./app/controllers/users_controller.rb:6:in `sold_items'
# ./spec/controllers/users_controller_spec.rb:8:in `block (3 levels) in <top (required)>'
一個解決辦法: 當我使用字符串插值來傳遞user.id到它的工作原理網址...
require 'rails_helper'
RSpec.describe UsersController, type: [:request, :controller] do
describe "GET #items" do
it "returns http success" do
user = FactoryGirl.create(:user)
get "users/#{user.id}/sold_items", id: user.id
expect(response).to have_http_status(:success)
end
end
end
我實現了你從rails 4建議的語法,請參閱編輯。規範仍然失敗,沒有路由匹配錯誤 – matthewalexander
嘗試添加':request':在'RSpec.describe UsersController,類型:[:request,:controller] do' – mrvncaragay
我能夠使它與request:request一起工作。但是,我不得不使用字符串插值。請參閱Edit.2 – matthewalexander