在测试自定义设计控制器时,获取@controller是nil运行时:错误

时间:2016-02-05 07:58:00

标签: ruby-on-rails ruby testing devise

我使用控制台命令rails generate devise:controllers users设计了为用户生成控制器,当我尝试为registrations_controller.rb运行简单测试时,我的控制台输出错误:

  

RuntimeError:@controller是nil:确保在测试中设置它   设置方法。

我是新手,但一切看起来都很简单,所以我不明白为什么这不起作用。

这是app / controllers / users / registrations_controller.rb:

class RegistrationsController < Devise::RegistrationsController

  # GET /resource/sign_up
  def new
    super
    @user = User.new
  end
end

这是config / routes.rb:

Rails.application.routes.draw do
  devise_for :users, controllers: { registrations: 'users/registrations'}
  devise_scope :users do
    root                'users/registrations#new'
    get "sign_up", to: "users/registrations#new"
  end
end

这是test / controllers / registrations_controller_test.rb

require 'test_helper'


class RegistrationsControllerTest < ActionController::TestCase
include Devise::TestHelpers


    def setup 
            @user = users(:user1)
    end

    test "should get new" do
        get :new
        assert_response :success
    end
end

非常感谢您提供的任何帮助!

1 个答案:

答案 0 :(得分:2)

根据Devise文档:“如果您正在测试Devise内部控制器或继承自Devise的控制器,您需要告诉Devise在请求之前应该使用哪个映射。” https://github.com/plataformatec/devise#test-helpers

class RegistrationsControllerTest < ActionController::TestCase
  include Devise::TestHelpers

  def setup
    request.env['devise.mapping'] = Devise.mappings[:user]

    @user = users(:user1)
  end

  test "should get new" do
    get :new
    assert_response :success
  end
end

您可能还需要为测试类添加前缀,如下所示:

class Users::RegistrationsControllerTest < ActionController::TestCase
    ...
end