带子域的RSPEC路由



我使用RSPEC只有Rails 5 API应用程序,并以这种方式版本:

app
  - controllers
    - api
      - v1 
        - users_controller.rb

我的api/v1/users_controller.rb

module Api::V1
  class UsersController < ApiController

我的configroutes.rb

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  constraints subdomain: 'api' do
    scope module: 'api' do
      namespace :v1 do
        resources :users
      end
    end
  end
end

当我使用rails routes检查路线时,它向我显示了。

  Prefix Verb   URI Pattern             Controller#Action
v1_users GET    /v1/users(.:format)     api/v1/users#index {:subdomain=>"api"}
         POST   /v1/users(.:format)     api/v1/users#create {:subdomain=>"api"}
 v1_user GET    /v1/users/:id(.:format) api/v1/users#show {:subdomain=>"api"}
         PATCH  /v1/users/:id(.:format) api/v1/users#update {:subdomain=>"api"}
         PUT    /v1/users/:id(.:format) api/v1/users#update {:subdomain=>"api"}
         DELETE /v1/users/:id(.:format) api/v1/users#destroy {:subdomain=>"api"}

我的规格文件:

require "rails_helper"
RSpec.describe Api::V1::UsersController, type: :routing do
  describe "routing" do
    it "routes to #index" do
      expect(:get => "/v1/users").to route_to("api/v1/users#index")
    end
    it "routes to #create" do
      expect(:post => "/v1/users").to route_to("api/v1/users#create")
    end
    it "routes to #show" do
      expect(:get => "/v1/users/1").to route_to("api/v1/users#show", :id => "1")
    end
    it "routes to #update via PUT" do
      expect(:put => "/v1/users/1").to route_to("api/v1/users#update", :id => "1")
    end
    it "routes to #update via PATCH" do
      expect(:patch => "/v1/users/1").to route_to("api/v1/users#update", :id => "1")
    end
    it "routes to #destroy" do
      expect(:delete => "/v1/users/1").to route_to("api/v1/users#destroy", :id => "1")
    end
  end
end

但是,当我使用RSPEC测试路线时,它会失败。

 bundle exec rspec spec/routing/users_routing_spec.rb
FFFFF
Failures:
  1) Api::V1::UsersController routing routes to #index
     Failure/Error: expect(:get => "/v1/users").to route_to("api/v1/users#index")
       No route matches "/v1/users"
     # ./spec/routing/users_routing_spec.rb:7:in `block (3 levels) in <top (required)>'

我不明白为什么。有什么想法吗?

您必须为您的规格指定"子域"。

before do
  Rails.application.routes.default_url_options[:host] = 'test.host'
end
it "routes to #index" do
  expect(:get => v1_users_url).to route_to('v1/users#index', subdomain: 'api')
end

最新更新