Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise and Rspec - undefined method `authenticate!' for nil:NilClass

I'm trying to test my controller for access from unregistered users. Im using devise (3.3.0) and rspec (3.0.0).

spec/controllers/dares_controller_spec.rb

require 'rails_helper'

describe DaresController do
  let(:challenger) { create(:user) }
  let(:acceptor) { create(:user) }
  let(:challenge) { create(:challenge) }
  let(:dare) { create(:dare) }
  let(:user) { create(:user) }

  describe 'Guest access to dares' do

    describe 'GET #show' do
      it "redirects to root" do
        get :show, id: dare.id, challenge_id: challenge.id
        expect(response).to require_login
      end
    end
  end
end

In the controller:

dares_controller.rb

before_action :authenticate_user!

  def show

  end

I get the following error:

Failures:

  1) DaresController Guest access to dares GET #show redirects to root
     Failure/Error: get :show, id: dare.id, challenge_id: challenge.id
     NoMethodError:
       undefined method `authenticate!' for nil:NilClass
     # ./spec/controllers/dares_controller_spec.rb:16:in `block (4 levels) in <top (required)>'

I tried adding

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

to my spec_helper / rails_helper but it didnt fix the problem. I googled for solutions for a few hours, bothing seems to help.

Matcher - require_login

RSpec::Matchers.define :require_login do |expected|
  match do |actual|
    expect(actual).to redirect_to Rails.application.routes.url_helpers.new_user_session_path
  end

  failure_message do |actual|
    "expected to require login to access the method"
  end

  failure_message_when_negated do |actual|
    "expected not to require login to access the method"
  end

  description do
    "redirect to the login form"
  end
end
like image 698
Szymon Borucki Avatar asked Oct 15 '14 23:10

Szymon Borucki


1 Answers

change this line:

describe DaresController do

to this one:

RSpec.describe DaresController, type: :controller do

Since you configure the spec_helper or rails_helper with:

config.include Devise::TestHelpers, type: :controller

You should set the correct spec type to works properly. It's a rspec behavior in rspec~3

like image 77
lucianosousa Avatar answered Oct 05 '22 22:10

lucianosousa