【问题标题】:Could not find devise mapping for controller path找不到控制器路径的设计映射
【发布时间】:2016-06-08 20:10:01
【问题描述】:

我知道有很多关于同样问题的问题,但似乎没有一个解决方案适合我的情况。

我已经定义了自己的会话、注册和用户控制器,因为我使用的是带有令牌身份验证的 API,但我似乎无法让我的路由/范围工作正常。

尝试在我的会话控制器(继承自 DeviseController)上运行 Spec 测试时收到以下错误消息

 Failure/Error: post :create,  credentials

 AbstractController::ActionNotFound:
   Could not find devise mapping for path "/api/v1/sessions/create?user_login%5Bemail%5D=rosina%40russel.name&user_login%5Bpassword%5D=12345678".
   This may happen for two reasons:

   1) You forgot to wrap your route inside the scope block. For example:

     devise_scope :user do
       get "/some/route" => "some_devise_controller"
     end

   2) You are testing a Devise controller bypassing the router.
      If so, you can explicitly tell Devise which mapping to use:

      @request.env["devise.mapping"] = Devise.mappings[:user]

我实际上已经根据我读过的其他答案完成了这两件事,但我认为它不适合我的具体情况。

这是我正在尝试运行的规范测试

describe "POST #create" do

before(:each) do
 @user = FactoryGirl.create :user
 @user.skip_confirmation!
 @request.env['devise.mapping'] = Devise.mappings[:user]
end

context "when the credentials are correct" do

  before(:each) do
    credentials = { user_login: { :email => @user.email, :password => "12345678"} }
    post :create,  credentials
  end

  it "returns the user record corresponding to the given credentials" do
    @user.reload
    user_response = JSON.parse(response.body, symbolize_names: true)
    expect(user_response[:auth_token]).to eql @user.auth_token
  end

  it { should respond_with :created }
end
end

如你所见,我指定了我没有指定的内容。

这是我的 routes.rb 在其命名空间中定义我的 API 之前的 sn-p:

namespace :api, defaults: { format: :json } do
  namespace :v1 do
    devise_for :users, skip: [:sessions, :registrations]      

    devise_scope :user do
      post 'sessions', to: 'sessions#create'
      delete 'sessions', to: 'sessions#destroy'
    end

如果有人对此有所了解,请告诉我,我很想测试我的控制器...

是的,我的 session_controller 位于 app/controllers/api/v1/sessions_controller.rb,它被正确定义为 class API::V1::SessionsController < DeviseController

我注意到 devise_for 应该是 SET Devise.mapping 但这似乎根本没有发生!

【问题讨论】:

  • 如果您包含实际运行的规范,而不仅仅是在块之前,这将有所帮助
  • @MilesStanfield 这无关紧要,它甚至不会超过发布请求。测试甚至没有机会运行
  • 它可能无关紧要。但是您要求我们提供帮助,所以让我们决定
  • @MilesStanfield 无法反驳,更新了帖子
  • 这个问题here回答了同样的问题。

标签: ruby-on-rails ruby model-view-controller devise


【解决方案1】:

我应该马上做的。我将 Devise.mappings.inspect 发送到记录器,它读取到映射存储在 :api_v1_user 中,因此映射哈希中的键对应于您编写 devise_for 的命名空间......希望这对其他人有帮助

【讨论】:

    【解决方案2】:

    根据您的路线,API 采用json 格式。所以你需要在发送post方法时指定。这就是为什么我认为 rspec 抱怨该路由不存在,因为它不知道使用 json。尝试更改此设置

    post :create, credentials
    

    到这里

    post :create, credentials, format: :json
    

    【讨论】:

    • 哎呀,忘记了,但我仍然遇到同样的错误..关于我如何定义到控制器的设计路线有些搞砸了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多