我正在进行一些简单的集成测试。我想测试用户控制器中的sold_items操作。我已经确认路由存在并通过从浏览器访问它返回json。然而,rspec告诉我路线不存在。请看下面的规格,错误和我的route.rb。谢谢!
规格:
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"
修改
规范
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第二个建议
要求&#39; rails_helper&#39;
RSpec.describe UsersController, type: [:request, :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
失败
看起来像user.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传递到它工作的URL时...
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
答案 0 :(得分:1)
看来你的语法错了。
更改:强>
get "users/#{user.id}/sold_items"
要强>
rails 4
get "users/:id/sold_items", id: user.id
rails 5
get "users/:id/sold_items", params: { id: user.id }