Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails + rspec + devise = undefined method `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

Result:

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

Rails version: 3.1.3

Rspec version: 2.8.0

Devise version: 1.5.3

Note: I also created support/deviser.rb file but that does not help. Any ideas?

like image 788
7elephant Avatar asked Jan 11 '12 12:01

7elephant


4 Answers

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

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

Use this new syntax

  before do
     allow(controller).to receive(:authenticate_user!).and_return(true)
   end
like image 53
Mikhail Nikalyukin Avatar answered Nov 20 '22 00:11

Mikhail Nikalyukin


Is your model name something other than User? If it's e.g. Admin, then you need to change your filter to:

before_filter :authenticate_admin!

This bit me for a while; I started with User as my model, and later decided to add Devise to a model named Member instead, but I left the original :authenticate_user! in my controller and kept getting that error when running RSpec.

like image 33
Jim Stewart Avatar answered Nov 20 '22 01:11

Jim Stewart


Looks like the best way to do this is the following in your spec_helper.rb file:

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end

See the rspec wiki for more details.

like image 3
zkwentz Avatar answered Nov 20 '22 02:11

zkwentz


In my case I had forgotten that I commented out the devise_for line in my routes.rb file.

like image 1
Loren Avatar answered Nov 20 '22 02:11

Loren