您好我正在使用ruby-2.5.0和Rails 5处理RoR项目。我正在使用rspec来测试我的代码。我有一个控制器,我使用before_action来验证用户的令牌,如下所示: -
abc_controller.rb
class ParserController < ApplicationController
before_action :validate_token
def create
store_name,reciept = StoreParserInteractor.find_store(parser_params,@user_id)
if reciept.present?
render json: JSONAPI::Serializer.serialize(reciept),
status: :ok
elsif store_name.present?
render json: {'error': 'date / time on receipt not found'},
status: 400
else
render json: {'error': 'store name not found'},
status: 400
end
rescue StandardError
render json: {}, status: 500
end
private
def parser_params
params.require(:data)
.permit!
.transform_keys(&:underscore)
end
end
我的应用程序控制器如下: -
class ApplicationController < ActionController::API
attr_accessor :user_id
def validate_token
auth_interactor = AuthenticationInteractor.new(request.headers['login-token'])
@user_id = auth_interactor.user_from_token&.id
render status: 401 unless @user_id
end
end
在rspec里面如何在标题中发送auth-token?我的rspec如下: -
describe ParserController do
describe 'POST create' do
subject { post :create, params: params }
context 'when store is found' do
let(:params) do
{
"Lines": [{
"Words": [{
"WordText": "WELCOME",
"Left": 655,
"Top": 442,
"Height": 23,
"Width": 91
}],
"MaxHeight": 23,
"MinTop": 442
},
{
"Words": [{
"WordText": "FOR",
"Left": 620,
"Top": 1785,
"Height": 22,
"Width": 37
},
{
"WordText": "CUSTOM",
"Left": 738,
"Top": 1785,
"Height": 22,
"Width": 79
}
],
"MaxHeight": 22,
"MinTop": 1785
},
{
"Words": [{
"WordText": "rpos",
"Left": 477,
"Top": 1915,
"Height": 22,
"Width": 48
}],
"MaxHeight": 22,
"MinTop": 1915
},
{
"Words": [{
"WordText": "402!",
"Left": 479,
"Top": 2209,
"Height": 22,
"Width": 46
},
{
"WordText": ".28",
"Left": 597,
"Top": 2208,
"Height": 23,
"Width": 37
}
],
"MaxHeight": 23,
"MinTop": 2208
}
],
"HasOverlay": true,
"Message": "Total lines: 42"
}
end
before do
allow(controller).to receive(:validate_token).and_return(true)
end
it { is_expected.to have_http_status(400) }
end
end
end
我必须在头文件中传递auth-token。请帮助我如何创建用户并在标头内传递该令牌。提前谢谢。
答案 0 :(得分:0)
您可以在:headers
方法中将post
作为选项传递:
it "date / time on receipt not found" do
my_params = {}
my_user_token = user.generate_api_token
post :create, params, headers: { "login-token" => my_user_token }
# post parsers_path, my_params, headers: { "login-token" => my_user_token }
expect(response.status).to eq 400
end