覆盖设计注册控制器时如何编写控制器测试? [英] How to write controller tests when you override devise registration controller?

查看:23
本文介绍了覆盖设计注册控制器时如何编写控制器测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望覆盖 Devise::RegistrationsController 以实现一些自定义功能.为此,我创建了一个新的 RegistrationsController,如下所示:

I wish to override the Devise::RegistrationsController to implement some custom functionalality. To do this, I've created a new RegistrationsController like so:

# /app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  def new
    super
  end
end

并像这样设置我的路线:

and set up my routes like this:

devise_for :users, :controllers => { :registrations => "registrations" }

并尝试像这样测试它:

describe RegistrationsController do
  describe "GET 'new'" do
    it "should be successful" do
      get :new
      response.should be_success
    end
  end
end

但这给了我一个错误:

 1) RegistrationsController GET 'new' should be successful
 Failure/Error: get :new
 AbstractController::ActionNotFound:
   Could not find devise mapping for path "/users/sign_up".
   Maybe you forgot to wrap your route inside the scope block? For example:

       devise_scope :user do
         match "/some/route" => "some_devise_controller"
       end
 # ./spec/controllers/registrations_controller_spec.rb:13:in `block (3 levels) in <top (required)>'

那我做错了什么?

推荐答案

问题是 Devise 无法将路由从测试映射回原始控制器.这意味着,虽然如果您在浏览器中打开您的应用实际上可以正常工作,但您的控制器测试仍然会失败.

The problem is that Devise is unable to map routes from the test back to the original controller. That means that while your app actually works fine if you open it in the browser, your controller tests will still fail.

解决方案是在每次测试之前将设计映射添加到请求中,如下所示:

The solution is to add the devise mapping to the request before each test like so:

before :each do
  request.env['devise.mapping'] = Devise.mappings[:user]
end

这篇关于覆盖设计注册控制器时如何编写控制器测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆