测试被覆盖的Devise控制器 - “没有路由匹配”

时间:2015-07-02 12:58:18

标签: ruby-on-rails devise

我跑了rails g devise:controllers users,我的路线看起来像

devise_for :users, controllers: {
  sessions: 'sessions'
}

我想要测试app/controllers/users/sessions_controller。我的路线看起来像:

$ rake routes
              Prefix Verb   URI Pattern                    Controller#Action
    new_user_session GET    /users/sign_in(.:format)       sessions#new
        user_session POST   /users/sign_in(.:format)       sessions#create

我设置了这样的测试:

# test/controllers/users/sessions_controller_test.rb
require 'test_helper'

class SessionsControllerTest < ActionController::TestCase
  tests Users::SessionsController

  test "sign in sanity check" do
    user = users(:one)
    post :create, email: user.email, password: 'password'
    assert_response :success
  end
end

哪个失败并显示错误:

ActionController::UrlGenerationError: No route matches {:action=>"create", :controller=>"users/sessions", :email=>"one@example.com", :password=>"password"}

如何正确发布到我想要的网址?我尝试了各种各样的变化,但我在这里错过了一些神奇的酱汁。

1 个答案:

答案 0 :(得分:0)

将您的routes.rb更改为

devise_for :users, controllers: {
  sessions: 'users/sessions'
}

在你的测试中,确保你有

class SessionsControllerTest < ActionController::TestCase
  tests Users::SessionsController
  include Devise::TestHelpers

  test "sign in sanity check" do
    request.env["devise.mapping"] = Devise.mappings[:user]
    user = users(:one)
    post :create, email: user.email, password: 'password'
    assert_response :success
  end
end

(您可以see how Devise itself does it作为示例。)