测试失败,未定义的方法`authenticate!'为零:NilClass

时间:2017-02-16 08:10:12

标签: ruby-on-rails ruby rspec devise minitest

我搜索了错误并获得了Rspec的各种解决方案 我正在使用Minitest而无法理解如何在Minitest中实现它。

根据我的理解,我应该通过调用include Devise::TestHelpers

在“test_helper.rb”中登录用户

我正在使用
Ruby 2.1.1p76
Rails 4.2.5.1
耙子11.1.2
MINITEST

我收到以下错误:

LocationsControllerTest#test_should_get_index:
ActionView::Template::Error: undefined method `authenticate' for nil:NilClass
    app/views/layouts/_navbar.html.erb:41:in `_app_views_layouts__navbar_html_erb__1573266900144599421_47382981019560'
    app/views/layouts/application.html.erb:19:in `_app_views_layouts_application_html_erb___1642478743058061304_47382980397060'
    test/controllers/locations_controller_test.rb:9:in `block in <class:LocationsControllerTest>'

_navbar.html.erb:41

<% if current_user %>

test_helpers.rb

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Add more helper methods to be used by all tests here...
end

测试/控制器/ locations_controller_test.rb

require 'test_helper'

class LocationsControllerTest < ActionController::TestCase
  setup do
    @location = locations(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:locations)
  end

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

  test "should create location" do
    assert_difference('Location.count') do
      post :create, location: { long_name: @location.long_name, short_name: @location.short_name }
    end

    assert_redirected_to location_path(assigns(:location))
  end

  test "should show location" do
    get :show, id: @location
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @location
    assert_response :success
  end

  test "should update location" do
    patch :update, id: @location, location: { long_name: @location.long_name, short_name: @location.short_name }
    assert_redirected_to location_path(assigns(:location))
  end

  test "should destroy location" do
    assert_difference('Location.count', -1) do
      delete :destroy, id: @location
    end

    assert_redirected_to locations_path
  end
end

测试/装置/ users.yml里

one:
  email: user_email@som.com
  encrypted_password: abc
  sign_in_count: 2
  current_sign_in_at: Time.now

1 个答案:

答案 0 :(得分:3)

首先需要在test_helper.rb

中添加对Devise minitest帮助者的调用
class ActionController::TestCase
  include Devise::Test::ControllerHelpers
end

或者如果你有旧版本的Devise:

class ActionController::TestCase
  include Devise::TestHelpers
end

然后,您需要在每个用户都应该登录的测试之前添加对sign_in的调用。在您的示例中,将设置更改为:

setup do
  sign_in users(:one)
  @location = locations(:one)
end

正如@Iceman指出的那样,这是documented in the Devise README