vendredi 29 mars 2019

Controller testing Rspec -Unauthorized request after user login - expected the response to have a success status code (2xx) but it was 401

I got unauthorized request after user login (get request on :index). Here is a simple example of users test, I can't see what I'm doing wrong.

In controller current_user exists and is signed in, but request is unauthorized. Why is that?

module ControllerMacros

  def login_user
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      user = FactoryBot.create(:user, company: FactoryBot.create(:company))
      sign_in user
    end
  end

end

rspec_helper.rb:

require 'spec_helper'
require 'devise'
require 'support/controller_macros'

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
  config.include Devise::Test::ControllerHelpers, type: :controller
  config.extend ControllerMacros, type: :controller
end

Users test:

require 'rails_helper'

RSpec.describe Api::V1::UsersController do
  include Devise::Test::ControllerHelpers

  describe "GET /api/v1/users" do
    login_user

    it "should get list of users" do
      get 'index'
      expect(response).to have_http_status(:success)
    end

  end
end

This tests are passing and working fine:

   it "should have a current_user" do
      expect(subject.current_user).to_not eq(nil)
    end

    it "should be signed in" do
      expect(subject.user_signed_in?).to be true
    end

Aucun commentaire:

Enregistrer un commentaire