簡體   English   中英

RSPEC:如何測試控制器操作返回JSON Web令牌

[英]RSPEC: How to test that a JSON Web Token is returned by controller action

我正在使用Devise和JWT來驗證我正在編寫的項目中的用戶。 我很難搞清楚如何編寫一個有用的測試來期待一個JWT response.body因為每個都是加密的。

我唯一能想到的就是測試它們的結構是否應該是JWT(一個3段, '.'分隔的字符串)。

有沒有人遇到測試隨機/散列回報並提出更好的解決方案?

describe SessionTokensController, type: :controller do
  let(:current_user) { FactoryGirl.create(:user) }

  before(:each) do
    sign_in current_user
  end

  describe '#create' do
    it 'responds with a JWT' do
      post :create
      token = JSON.parse(response.body)['token']

      expect(token).to be_kind_of(String)
      segments = token.split('.')
      expect(segments.size).to eql(3)
    end
  end
end

這實際上取決於你想要測試的內容。

如果您只想測試返回的令牌是否存在且是否有效,則可以執行以下操作:

it 'responds with a valid JWT' do
  post :create
  token = JSON.parse(response.body)['token']

  expect { JWT.decode(token, key) }.to_not raise_error(JWT::DecodeError)
end

雖然驗證令牌包含的聲明似乎更有用:

let(:claims) { JWT.decode(JSON.parse(response.body)['token'], key) }

it 'returns a JWT with valid claims' do
  post :create
  expect(claims['user_id']).to eq(123)
end

在后一個示例中,您可以驗證您在JWT中包含的確切聲明。

    let(:user) { create(:user, password: "123456") }

      describe "POST authenticate_user" do
        context "with a valid password" do
          it "authenticates successfully" do
            post :authenticate_user, params:{email: user.email, password: "123456"}, format: :json
            parsed_body = JSON.parse(response.body)
            # binding.pry
            expect(parsed_body.keys).to match_array(["auth_token", "user"])
            expect(parsed_body['user']['email']).to eql("joe@gmail.com")
            expect(parsed_body['user']['id']).to eql(user.id)
          end

          it "authentication fails" do
            post :authenticate_user, params:{email: user.email, password: "123456789"}, format: :json
            parsed_body = JSON.parse(response.body)
            expect(parsed_body['errors'][0]).to eql("Invalid Username/Password")
          end
        end
      end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM