[英]RSPEC: How to test that a JSON Web Token is returned by controller action
I am using Devise and JWT's to authenticate users in a project I am writing. 我正在使用Devise和JWT来验证我正在编写的项目中的用户。 I am having a hard time figuring out how to write a useful test to expect a JWT
response.body
(since each is encrypted). 我很难搞清楚如何编写一个有用的测试来期待一个JWT
response.body
因为每个都是加密的。
The only thing I can think of is to test that they are structured as a JWT should be (a 3 segment, '.'
delimited string). 我唯一能想到的就是测试它们的结构是否应该是JWT(一个3段,
'.'
分隔的字符串)。
Has anyone encountered testing random/hashed returns and come up with a better solution? 有没有人遇到测试随机/散列回报并提出更好的解决方案?
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 really depends on what exactly you want to test. 这实际上取决于你想要测试的内容。
If you simply want to test if the returned token exists and is valid you can do the following: 如果您只想测试返回的令牌是否存在且是否有效,则可以执行以下操作:
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
Although it seems much more useful to validate the claims that the token includes: 虽然验证令牌包含的声明似乎更有用:
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
In the latter example you can validate the exact claims you included in the JWT. 在后一个示例中,您可以验证您在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.