该应用程序是一个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 '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


我的任何路线:

# config/routes.rb
Rails.application.routes.draw do
  namespace :api, defaults: {format: 'json'} do
    namespace :v1 do
      resources :users, only: [:show]
    end
  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


我确定这里缺少一些简单的东西,但是我花了几个小时,无法弄清。

最佳答案

您可以尝试使用Capybara的visit方法而不是get方法。在
/spec/controllers/api/v1/users_controller_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

10-08 03:09