- items_spec.rb
it "分页" do
user1 = User.create email: '1@qq.com'
user2 = User.create email: '2@qq.com'
11.times { Item.create amount: 100, user_id: user1.id }
11.times { Item.create amount: 100, user_id: user2.id }
+ post '/api/v1/session', params: {email: user1.email, code: '123456'}
+ json = JSON.parse response.body
+ jwt = json['jwt']
+ get '/api/v1/items', headers: {'Authorization': "Bearer #{jwt}"}
expect(response).to have_http_status 200
json = JSON.parse(response.body)
expect(json['resources'].size).to eq 10
get '/api/v1/items?page=2', headers: {'Authorization': "Bearer #{jwt}"}
expect(response).to have_http_status 200
json = JSON.parse(response.body)
expect(json['resources'].size).to eq 1
end
- items_controller.rb
def index
+ current_user_id = request.env['current_user_id']
+ return head :unauthorized if current_user_id.nil?
+ items = Item.where({user_id: current_user_id})
.where({created_at: params[:created_after]..params[:created_before]})
.page(params[:page])
上面添加的几行代码,我们每次测试的时候都要写,我们可以把请求 session 和设置请求头单独封装一个方法
方法1:
- spec/spec_helper.rb
+ module RequestTestHelper
+ def sign_in(user)
+ post '/api/v1/session', params: {email: user.email, code: '123456'}
+ json = JSON.parse response.body
+ {Authorization: "Bearer #{json['jwt']}"}
+ end
+ end
RSpec.configure do |config|
+ config.include RequestTestHelper, type: :request
使用
it "分页" do
user1 = User.create email: '1@qq.com'
user2 = User.create email: '2@qq.com'
11.times { Item.create amount: 100, user_id: user1.id }
11.times { Item.create amount: 100, user_id: user2.id }
- post '/api/v1/session', params: {email: user1.email, code: '123456'}
- json = JSON.parse response.body
- jwt = json['jwt']
- get '/api/v1/items', headers: {'Authorization': "Bearer #{jwt}"}
+ headers = sign_in user1
+ get '/api/v1/items', headers: headers
方法2:
- app/models/user.rb
class User < ApplicationRecord
validates :email, presence: true
+ def generate_jwt
+ payload = { user_id: self.id }
+ JWT.encode payload, Rails.application.credentials.hmac_secret, 'HS256'
+ end
+ def generate_auth_header
+ {Authorization: "Bearer #{self.generate_jwt}"}
+ end
end
- app/controllers/api/v1/sessions_controller.rb
else
# 私钥
- hmac_secret = Rails.application.credentials.hmac_secret
- payload = { user_id: user.id }
- token = JWT.encode payload, hmac_secret, 'HS256'
- render status: 200, json: {
- jwt: token
- }
+ render status: :ok, json: { jwt: user.generate_jwt }
end
使用
- spec/requests/items_spec.rb
- headers = sign_in user1
- get '/api/v1/items', headers: headers
+ get '/api/v1/items', headers: user1.generate_auth_header
网友评论