在rspec中正确地发出put请求

时间:2017-07-27 08:48:30

标签: ruby-on-rails rspec

一切!

我想知道如何从RSpec发出PUT / PATCH请求来测试Rails 5.1.2 API,就像那样:

describe 'PUT /users/:id' do

  context '# check success update' do
    it 'returns status code 204' do
      put 'update',  params: { user: { id: 3, email: 'newmail@ya.ru'} }
      expect(response).to have_http_status(204)
    end
  end
end

出现以下错误:

的ActionController :: UrlGenerationError:

No route matches {:action=>"update", :controller=>"users", :user=>{:id=>3, :email=>"newmail@ya.ru"}}

路线还可以:

Prefix Verb   URI Pattern          Controller#Action
 users GET    /users(.:format)     users#index
       POST   /users(.:format)     users#create
  user GET    /users/:id(.:format) users#show
       PATCH  /users/:id(.:format) users#update
       PUT    /users/:id(.:format) users#update
       DELETE /users/:id(.:format) users#destroy

1 个答案:

答案 0 :(得分:1)

由于Rails 5您需要提供params个选项,id必须在user参数之外:

describe 'PUT /users/:id' do
  context '# check success update' do

    before do
      put 'update', params: { id: 3, user: { email: 'newmail@ya.ru'} }
    end

    it 'returns status code 204' do
      expect(response).to have_http_status(204)
    end
  end
end