Ruby on rails 在测试中未找到Rails路由
这个应用程序是一个Rails 4应用程序,只是一个API(目前)。我可以从浏览器中点击我的URL,但是当我在测试中尝试访问它时,它找不到URL。我明白了:Ruby on rails 在测试中未找到Rails路由,ruby-on-rails,unit-testing,testing,ruby-on-rails-4,tdd,Ruby On Rails,Unit Testing,Testing,Ruby On Rails 4,Tdd,这个应用程序是一个Rails 4应用程序,只是一个API(目前)。我可以从浏览器中点击我的URL,但是当我在测试中尝试访问它时,它找不到URL。我明白了: No route matches {:action=>"/api/v1/users/20", :controller=>"api/v1/users"} 我的测试中还没有任何断言。仅尝试先克服此错误: # /spec/controllers/api/v1/users_controller_spec.rb require 'rail
No route matches {:action=>"/api/v1/users/20", :controller=>"api/v1/users"}
我的测试中还没有任何断言。仅尝试先克服此错误:
# /spec/controllers/api/v1/users_controller_spec.rb
require 'rails_helper'
RSpec.describe Api::V1::UsersController, :type => :controller do
describe "User API" do
it "can return a user by ID" do
user = FactoryGirl.create(:user)
get "/api/v1/users/#{user.id}"
end
end
end
和我的控制器:
# app/controllers/api/v1/users_controller.rb
class Api::V1::UsersController < ApplicationController
before_action :set_user, only: [:show]
def show
end
private
def set_user
@user = User.find(params[:id])
end
end
和rake routes
给我:
Prefix Verb URI Pattern Controller#Action
api_v1_user GET /api/v1/users/:id(.:format) api/v1/users#show {:format=>"json"}
还有我的宝贝:
group :test do
gem 'capybara'
end
group :development, :test do
gem 'rspec-rails'
gem 'factory_girl_rails'
gem 'database_cleaner'
end
我确信我在这里遗漏了一些简单的东西,但我已经花了几个小时没有弄清楚。你可以尝试使用水豚的探视方法,而不是获取。在里面 /spec/controllers/api/v1/users\u controller\u spec.rb
require 'rails_helper'
require 'capybara' # unless you're already doing this in spec_helper.rb
RSpec.describe Api::V1::UsersController, :type => :controller do
describe "User API" do
it "can return a user by ID" do
user = FactoryGirl.create(:user)
visit "/api/v1/users/#{user.id}"
end
end
end
我想我终于明白了。。。在某种程度上。我想因为这是一个单元测试,所以我需要通过
get
操作名而不是URL。现在我有了这个,它正在工作:
RSpec.describe Api::V1::UsersController, :type => :controller do
describe "User API" do
it "can return a user by ID" do
user = FactoryGirl.create(:user)
# get "/api/v1/users/#{user.id}" # This failed.
get :show, id: user.id, format: 'json' # This works!
end
end
end
我确实想测试以确保URL没有改变。我想这更像是一个集成测试,所以我想我可能会在features
目录中这样做,并按照@NickM提到的方式进行
更新
我正在编写一个API应用程序。在修复上述问题后,我得到了一个缺少模板的错误。我不得不更改我的get
方法,使其也有一个format参数
RSpec.describe Api::V1::UsersController, :type => :controller do
describe "User API" do
it "can return a user by ID" do
user = FactoryGirl.create(:user)
# get "/api/v1/users/#{user.id}" # This failed.
get :show, id: user.id, format: 'json' # This works!
end
end
end