2017-09-01 61 views
1

我想使用RSpec测试控制器接收这种请求:具有测试具有不同的身体和查询字符串的控制器PARAMS

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 

到目前为止,对于主体参数和首标参数将是有益的。

但是我们应该怎么做也发送查询字符串 param?

回答

0

如果你真的需要这种情况下,你必须使用Rails的URI模式,而不是只在后语句中指定动作的名称,

post '/documents/create_new_doc', params: {same_key: 'value_in_body'} 

注:从耙途径得到确切的URI模式

+0

我知道这一点。 但是我们怎样才能不重写_body_参数(因为它们都有相同的键)? –

+0

是的,我明白你的观点,因为这是一个发布请求。因此,不要使用动作名称,而是使用RUI模式,如'sessions /',您可以从rake路径获取它。 – Mohanraj

+0

RSpec的请求测试使用此模式。 在RSpec控制器测试的上下文中,第一个参数必须是一个操作,而不是路径。 –

相关问题