在 rspec 中正确发出放置请求

fer*_*301 0 rspec ruby-on-rails

全部!

我想知道如何从 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
Run Code Online (Sandbox Code Playgroud)

得到以下错误:

ActionController::UrlGenerationError:

No route matches {:action=>"update", :controller=>"users", :user=>{:id=>3, :email=>"newmail@ya.ru"}}
Run Code Online (Sandbox Code Playgroud)

路线没问题:

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
Run Code Online (Sandbox Code Playgroud)

Igo*_*dov 8

Since Rails 5 you'll need to provide params options and id must be outside of the user params:

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
Run Code Online (Sandbox Code Playgroud)