【问题标题】:ActionController::UrlGenerationError: No route matches action and controllerActionController::UrlGenerationError: 没有路由匹配动作和控制器
【发布时间】:2015-09-21 22:43:26
【问题描述】:

我在其他相关问题中找不到解决方案,所以我问自己的问题。

问题很简单。这是我得到的错误:

Failure/Error: get 'api/v2/special_keys#show'
 ActionController::UrlGenerationError:
   No route matches {:action=>"api/v2/special_keys#show", :controller=>"api/v2/special_keys"}

这是我的routes.rb

resources :special_keys, only: [] do
  collection do
    get '', to: 'special_keys#show'
  end
end

这是rake routes的输出:

GET /api/v2/special_keys(.:format) api/v2/special_keys#show {:format=>"json"}

还有我的规格:

require 'rails_helper'

describe Api::V2::SpecialKeysController do
  describe 'GET #show' do
    it 'gets the policy and signature' do
      get '/api/v2/special_keys'

      expect(response.status).to eql 200
    end
  end
end

【问题讨论】:

  • 你的控制器代码是什么样的?难道你只允许json格式?
  • 是的,我确实只允许 json 格式。
  • 在下面试试我的答案。

标签: ruby-on-rails rspec


【解决方案1】:

尝试将您的测试重写为:

require 'rails_helper'

describe Api::V2::SpecialKeysController do
  describe 'GET #show' do
    it 'gets the policy and signature' do
      get '/api/v2/special_keys', {format: :json}

      expect(response.status).to eql 200
    end
  end
end

【讨论】:

  • 所以这帮助我解决了这个问题。我做的第一件事是在规范中向:show 发出GET 请求。我做的第二件事是使用before 登录,否则返回 401 错误。
【解决方案2】:

试试:

resource :special_keys, only: [:show]

单数告诉应用程序只有一个。所以它只会生成一个 show 操作,不需要 id 也不需要 indexaction。

【讨论】:

  • 起初,我尝试使用 resources :special_keys, only: [:show],但最终不得不在请求 URL 中添加一个我不需要的 ID(例如 /api/v2/special_keys/1。你的代码让我留下了这个错误:uninitialized constant Api::V2::SpecialKeysController
  • 你有一个控制器文件special_keys_controller.rbapp/controller/api/v2 中定义Api::V2::SpecialKeysController 吗?
  • 不,因为我不需要。
  • 控制器是包含路由指向的动作的“事物”。所以请放心:您确实需要一个。上面是 rails 会寻找它的位置。如果它在其他地方,你必须告诉 Rails 在哪里。
猜你喜欢
  • 1970-01-01
  • 2015-11-26
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
  • 2016-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多