2014-10-15 12 views
10

Próbuję przetestować mój kontroler dostępu od niezarejestrowanych użytkowników użytkowników. Używam devise (3.3.0) i rspec (3.0.0).Devise and Rspec - niezdefiniowana metoda "authenticate!" dla zero: NilClass

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 

W regulatorze:

dares_controller.rb 

before_action :authenticate_user! 

    def show 

    end 

pojawia się następujący błąd:

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

Próbowałem, dodając

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

do mojego spec_helper/rails_helper ale nie to naprawić problem. Przez kilka godzin szukałem rozwiązań w poszukiwaniu rozwiązań, dzięki czemu wydaje mi się, że pomagają.

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 
+4

Spójrz na to [How-To: -Stub-uwierzytelnianie-w-kontroler-specs] (https://github.com/plataformatec/devise/wiki/How-To:- Specyfikacja uwierzytelniania w kontrolerach) – gotva

+0

To działa, thx! –

+0

Hmm, mam dokładnie ten sam błąd, z wyjątkiem sytuacji, gdy próbuję wyszydzić request.env ['warden'], który zwraca także zerę, więc kończę draniem z metody na zero, a test kończy się niepowodzeniem. – Trejkaz

Odpowiedz

3

zmiana ta linia:

describe DaresController do

do tego:

RSpec.describe DaresController, type: :controller do

Od skonfigurować spec_helper lub rails_helper z:

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

Powinieneś ustawić poprawną specyfikację, aby type działał poprawnie. Jest to zachowanie rspec w rspec ~ 3

+2

Pomogło to rozwiązać mój problem. Dzięki – Cheyne

Powiązane problemy