ruby-on-rails – Rails rspec devise =未定义的方法`authenticate_user!’

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails rspec devise =未定义的方法`authenticate_user!’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
ApplicationController中:
class ApplicationController < ActionController::Base
  before_filter :authenticate_user!

  protect_from_forgery
end

DashboardsController:

class DashboardsController < ApplicationController
  def index
  end

end

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

结果:

Failure/Error: get 'index'
     NoMethodError:
       undefined method `authenticate_user!' for #<DashboardsController:0x007fef81f2efb8>

Rails版本:3.1.3

Rspec版本:2.8.0

设计版本:1.5.3

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

解决方法

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

更新:

使用上述语法和最新的rspec将给出以下警告

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)>'.

使用这种新语法

before do
     allow(controller).to receive(:authenticate_user!).and_return(true)
   end

猜你在找的Ruby相关文章