我正在测试我们的API的JSON请求,它将使用JSON进行响应。 似乎JSON中的所有整数都转换为字符串,因为我们将它们发布到控制器考虑操作。
def consider
binding.pry # binding no# 2 used to check the params after post from test.
if ParametersValidator.is_valid?(params)
application_handler = ApplicationHandler.new(request_interactor)
render json: application_handler.result
else
render json: ParametersValidator.failed_params(params).to_json
end
end
ParamaterValidator
验证进入的数据的结构和类型。
render_views
let(:json) { JSON.parse(response.body) }
..
..
it 'returns the result in the correct format for the AUTOMATIC APPROVE decision' do
automatic_approve_params = relative_json_file(relative_file('automatic_approve_params'))
expected_approve_params = {
"status" => "accepted",
"automated" => true,
"rate" => 6,
"amount" => 30000,
"term" => 10,
"pre_approved_amount" => 2500,
"comments" => ""
}
@request.headers['HTTP_X_AUTH_SIG'] = Rails.application.secrets['authorization']['token']
request.env["HTTP_ACCEPT"] = 'application/json'
binding.pry # binding no# 1 to inspect the params before post
post :consider, automatic_approve_params, format: :json
expect(json).to eq(expected_approve_params)
end
{
"student_id"=>1,
"age"=>22,
"name"=>"John",
"age_range"=>"22-25",
"criminal_record"=>false,
"declared_bankrupt"=>false,
"declared_insolvent"=>false,
"declared_sequestrated"=>false,
"defaulted_on_loan"=>false,
"post_study_salary"=>100000000,
"first_nationality"=>"PL",
"second_nationality"=>"",
"citizenship"=>"PL",
}
{
"student_id"=>"1",
"age"=>"22",
"name"=>"John",
"age_range"=>"22-25",
"criminal_record"=>false,
"declared_bankrupt"=>false,
"declared_insolvent"=>false,
"declared_sequestrated"=>false,
"defaulted_on_loan"=>false,
"post_study_salary"=>"100000000",
"first_nationality"=>"PL",
"second_nationality"=>"",
"citizenship"=>"PL",
}
测试日志显示请求
Processing by Api::V1::CreditApplicationsController#consider as JSON
在发布动作之前检查请求你会看到params很好,然后在我运行任何东西之前在控制器中检查params并且它们都是字符串。
使用邮递员测试带有JSON的API按预期工作但似乎rspec在发布到考虑操作时会将所有参数转换为字符串。我已经阅读了几十篇帖子,通过将format: :json
添加到帖子操作中来声明它会解决这个问题,但是我没有这样的运气。
我显然做错了什么,但我已经尝试了很多我知道的事情。
答案 0 :(得分:15)
在复制了您遇到的问题之后,我设法使用以下方法在控制器规范中解决它:
post :consider, automatic_approve_params.merge(format: :json)
在我的本地测试中,我删除了
request.env["HTTP_ACCEPT"] = 'application/json'
它仍然按照您的预期运作。希望它有所帮助。
答案 1 :(得分:7)
在 Rails 5 中,使用 as: :json
而不是 format: :json
,例如post :consider, params: automatic_approve_params, as: :json
答案 2 :(得分:0)
我们可以尝试
post 'orders.json', JSON.dump(order: {boolean: true, integer: 123}), "CONTENT_TYPE" => "application/json"