2014-10-15 17 views
10

Tôi đang cố gắng kiểm tra bộ điều khiển của mình để truy cập từ người dùng chưa đăng ký. Im sử dụng devise (3.3.0) và rspec (3.0.0).Devise và Rspec - phương thức không xác định `xác thực! ' cho nil: 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 

Trong bộ điều khiển:

dares_controller.rb 

before_action :authenticate_user! 

    def show 

    end 

tôi nhận được lỗi sau:

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

Tôi đã cố gắng thêm

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

để spec_helper tôi/rails_helper nhưng nó didnt sửa chữa vấn đề. Tôi googled cho các giải pháp cho một vài giờ, bothing dường như giúp đỡ.

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

xem xét [Cách thực hiện: -Stub-authentication-in-controller-specs] (https://github.com/plataformatec/devise/wiki/How-To:- Stub-authentication-in-controller-specs) – gotva

+0

Hoạt động, thx! –

+0

Hmm, tôi có lỗi chính xác tương tự, ngoại trừ khi tôi cố gắng thử request.env ['warden'], trả về nil quá, vì vậy tôi sẽ kết thúc một phương thức trên nil và kiểm tra thất bại. – Trejkaz

Trả lời

3

thay đổi dòng này:

describe DaresController do

này một:

RSpec.describe DaresController, type: :controller do

Vì bạn cấu hình spec_helper hoặc rails_helper với:

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

Bạn nên đặt thông số chính xác type để hoạt động bình thường. Đó là hành vi rspec trong rspec ~ 3

+2

Điều này đã giúp giải quyết vấn đề của tôi. Cảm ơn – Cheyne

Các vấn đề liên quan