ruby-on-rails - 如何使用 RSpec 为 JWT 验证应用程序制定请求规范

标签 ruby-on-rails rspec rspec-rails

我有一个仅限 Rails 5 API 的应用程序,并使用 Knock 进行 JWT 身份验证。

完成模型和模型规范后,我开始做请求规范。

但我不知道如何以正确的方式完成请求规范内的身份验证,

我的用户 Controller ,

module V1
  class UsersController < ApplicationController
    before_action :authenticate_user, except: [:create]
  end
end

应用程序 Controller ,

class ApplicationController < ActionController::API
  include Knock::Authenticable
  include ActionController::Serialization
end

我最愚蠢的解决方案(在其余请求之前调用获取 token 请求以获取 JWT),

context 'when the request contains an authentication header' do
  it 'should return the user info' do
    user  = create(:user)
    post '/user_token', params: {"auth": {"email": user.email, "password": user.password }}
    body = response.body
    puts body # {"jwt":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0ODgxMDgxMDYsInN1YiI6MX0.GDBHPzbivclJfwSTswXhDkV0TCFCybJFDrjBnLIfN3Q"}
    # use the retrieved JWT for future requests
  end
end

如有任何建议,我们将不胜感激。

最佳答案

  def authenticated_header(user)
    token = Knock::AuthToken.new(payload: { sub: user.id }).token
    { 'Authorization': "Bearer #{token}" }
  end

  describe 'GET /users?me=true' do
    URL = '/v1/users?me=true'
    AUTH_URL = '/user_token'

    context 'when the request with NO authentication header' do
      it 'should return unauth for retrieve current user info before login' do
        get URL
        expect(response).to have_http_status(:unauthorized)
      end
    end

    context 'when the request contains an authentication header' do
      it 'should return the user info' do
        user  = create(:user)

        get URL, headers: authenticated_header(user)
        puts response.body
      end
    end
  end

关于ruby-on-rails - 如何使用 RSpec 为 JWT 验证应用程序制定请求规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42326434/

相关文章:

ruby-on-rails - 是否有在 RAILS API Controller 索引操作中应用过滤器哈希的 DRY 方法?

ruby-on-rails - Rspec/FactoryGirl : changes in factory not saving in test database?

ruby-on-rails - 创建对象 FactoryGirl 时未定义方法。

ruby-on-rails - 如何修复 2.99 版的 RSpec 语法?

rspec-rails - Rails/RSpec "it"方法说明和字符串插值

ruby-on-rails - 测试 RSpec 中的默认范围

ruby-on-rails - RSpec & Tire gem:测试 Tire::Results::Collection

ruby-on-rails - Rails ActionController::UnknownFormat 错误与 respond_to

ruby-on-rails - Ruby 中无替换的随机采样

ruby-on-rails - 在 rails 3 skinny 中制作胖 Controller