Rails + rspec + devise =未定义的方法`authenticate_user!'

7el*_*ant 8 rspec ruby-on-rails devise

ApplicationController中:

class ApplicationController < ActionController::Base
  before_filter :authenticate_user!

  protect_from_forgery
end
Run Code Online (Sandbox Code Playgroud)

DashboardsController:

class DashboardsController < ApplicationController
  def index
  end

end
Run Code Online (Sandbox Code Playgroud)

DashboardsControllerSpec:

require 'spec_helper'
describe DashboardsController do
  include Devise::TestHelpers

  describe "GET 'index'" do
    it "returns http success" do
      get 'index'
      response.should be_success
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

结果:

Failure/Error: get 'index'
     NoMethodError:
       undefined method `authenticate_user!' for #<DashboardsController:0x007fef81f2efb8>
Run Code Online (Sandbox Code Playgroud)

Rails版本:3.1.3

Rspec版本:2.8.0

设计版本:1.5.3

注意:我还创建了support/deviser.rb文件,但这没有帮助.有任何想法吗?

Mik*_*kin 12

require 'spec_helper'
describe DashboardsController do
  before { controller.stub(:authenticate_user!).and_return true }
  describe "GET 'index'" do
    it "returns http success" do
      get 'index'
      response.should be_success
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

Update:

Using above syntax with latest rspec will give below warning

Using `stub` from rspec-mocks' old `:should` syntax without explicitly enabling the syntax is deprecated. Use the new `:expect` syntax or explicitly enable `:should` instead. Called from  `block (2 levels) in <top (required)>'.
Run Code Online (Sandbox Code Playgroud)

Use this new syntax

  before do
     allow(controller).to receive(:authenticate_user!).and_return(true)
   end
Run Code Online (Sandbox Code Playgroud)


Jim*_*art 7

您的型号名称是除User之外的其他名称吗?如果它是例如Admin,那么您需要将过滤器更改为:

before_filter :authenticate_admin!
Run Code Online (Sandbox Code Playgroud)

我咬了一会儿; 我开始使用User作为我的模型,后来决定将Devise添加到名为Member的模型中,但是我将原始文件:authenticate_user!保留在我的控制器中并在运行RSpec时不断收到错误.