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

后端 未结 10 2019
陌清茗
陌清茗 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:04

    I was having this problem when trying to sign_in a user in a before hook:

    before(:context) do
      create(:skill, name: 'Google Maps API'.downcase)
      user = create(:user)
      sign_in user
    end
    

    Placing sign_in inside the before hook leads to:

    Failure/Error: sign_in user
    
     NoMethodError:
       undefined method `env' for nil:NilClass
    

    But placing it inside an example works fine:

    shared_examples_for('an authenticated resource.') do
      describe 'An authenticated request' do
        it "responds with HTTP status OK" do
          user = create(:user)
          sign_in user
          make_request
          expect(response).to have_http_status(:ok)
        end
      end
    end
    

    But this can be improved, placing the sign_in into a before(:example) that will also work:

    context 'allow search by keyword' do
      let!(:skill){ create(:skill, name: 'Google Maps API'.downcase) }
      let!(:user) { create(:user) }
    
      before(:example) { sign_in user }
    
      it 'finds matching records' do
        get :search, name: "Google Maps API", format: :json
        expect(assigns(:skills).size).to be(1)
      end
      it 'finds records that start with keyword'
      it 'finds records that end with keyword'
      it 'finds records that contains keyword'
    end
    

提交回复
热议问题