1

In my app.rb file i have the following setup for current_user

class Application < Sinatra::Base
    include Pundit
    use JWTAuthorization    
    def current_user
        env[:user]
    end

    delete '/users/:user_id' do
      user = User.find(params[:user_id])
      no_data! unless user

      authorize user, :edit?
      user.destroy
      response = {status: 200, data:'success, user deleted.'}
      json response
    end
end

The problem is I need to setup the current_user for my unit testing. Otherwise the test will throw an error inside authorize user, :edit? or any other Pundit authorization code because current_user will return nill. How can I setup env[:user] inside my spec?

Is there a way i can mock env[:user] with a value using rspec or use rack_env={} to setup?

This is what i tried so far in my spec file without success:

  before(:each) do
    @user = User.create(name: 'Oswaldinho',email: 'waldinho@com.com',role: 'user')
  end

  it 'deletes an existing user ' do
      delete "/users/#{@user.id}", params={}, rack_env={user: @user}
      expect(last_response).to be_ok
  end 
Marcelo Fonseca
  • 1,705
  • 2
  • 19
  • 38
  • Is JWTAuthorization rack middleware? You might want to look at how Warden does testing. You set `Warden.test_mode!` in your `spec_helper.rb` and use `Warden::Test::Helpers#login_as` to set the `current_user` - this avoids leaking the implementation details of the authentication system (which should be covered by some high level integration tests that go through actually logging a user in) into the rest of your tests. – max Mar 13 '20 at 11:38
  • Hi @max yes, it is rack middleware, but it is an authentication based on JWT token, not on warden. Another solution could be to mock a valid JWT token. do you want me to share the middleware code? – Marcelo Fonseca Mar 13 '20 at 13:10
  • 1
    I mentioned it as an example of how testing rack auth middleware can work which I would generally prefer instead of setting up a bunch JWTs and sending them in headers in all your tests. If you want an example of that look at Knock. Hint: Warden can be used for JWTs as well if you just create/find a strategy. – max Mar 13 '20 at 20:48

0 Answers0