我想用RSpec测试接收此类请求的控制器:
curl -X POST \
--data "{\"same_key\": \"value_in_body\"}" \
--header "same_key: value_in_header" \
"http://localhost:5000/articles/?same_key=value_in_querystring"
具有:
same_key
same_key
查询字符串中的same_key
以及其中:
request.request_parameters["same_key"]
:"value_in_body"
request.headers["same_key"]
:"value_in_header"
request.query_parameters["same_key"]
:"value_in_querystring"
我写了这个测试:
RSpec.describe ArticlesController, type: :controller do
describe '#create' do
it 'creates an article' do
post :post,
as: :json,
params: { same_key: 'value_in_body' },
headers: { same_key: 'value_in_header' }
expect(response).to have_http_status(:created)
end
end
end
到目前为止,它对 body param和 header param都有好处。
但是我们应该如何发送 querystring param?
答案 0 :(得分:0)
如果您确实需要这种场景,则必须使用Rails URI模式,而不是仅在post语句中指定操作名称,
post '/documents/create_new_doc', params: {same_key: 'value_in_body'}
注意:从 rake routes
获取确切的URI模式答案 1 :(得分:0)
实际上,RSpec Controller测试或请求测试中的request.query_parameters
或request.request_parameters
函数实际上不能同时拥有post
和get
。另一个Stack Overflow答案说明RSpec只能设置一个或另一个:https://stackoverflow.com/a/36715875/2479282
解决方案(由其他答案提出)是改为使用IntegrationTests,a'la:
class CollectionsTest < ActionDispatch::IntegrationTest
test 'foo' do
post collections_path, { collection: { name: 'New Collection' } },
{ "QUERY_STRING" => "api_key=my_api_key" }
# this proves that the parameters are recognized separately in the controller
# (you can test this in you controller as well as here in the test):
puts request.POST.inspect
# => {"collection"=>{"name"=>"New Collection"}}
puts request.GET.inspect
# => {"api_key"=>"my_api_key"}
end
end