“undefined method `env' for nil:NilClass” in 'setup_controller_for_warden' error when testing Devise using Rspec

后端 未结 10 2009
陌清茗
陌清茗 2020-12-09 14:31

I\'m trying to create a spec for a sign out flow by using factorygirl to create a user and then use Devise\'s sign_in method to authenticate the user, then use

10条回答
  •  失恋的感觉
    2020-12-09 15:20

    Like others have already said, you're including the Devise::TestHelpers. That's for testing controllers. If you'd still like to automatically login a test user in your integration tests, check out the official Devise Instructions on using it with Capybara.


    Using Devise with Capybara

    Basically, what you need to do is first enable Warden's test mode:

    include Warden::Test::Helpers
    Warden.test_mode!
    

    Then, (create and) login your user:

    user = FactoryGirl.create(:user)
    login_as(user, scope: :user)
    

    Example:

    # spec/features/survey_spec.rb
    require 'rails_helper'
    
    feature 'survey app' do
        include Warden::Test::Helpers
    
        let(:user)   { create(:user) }
        let(:survey) { create(:survey_with_questions) }
    
        before do
            # Sign the User in
            Warden.test_mode!
            login_as(user, scope: user)
        end
    
        it 'renders the survey' do
            visit survey_show_path(survey)
            expect(page).to have_content(survey.title)
        end
    end
    

提交回复
热议问题