将补丁与rspec测试一起使用

时间:2020-05-03 08:54:42

标签: ruby-on-rails rspec devise

我正在尝试使用Rspec来测试用于设计用户信息的补丁,更新网址看起来像这样# PATCH/PUT /api/users/1,但在以下所有情况下都遇到此错误

错误ArgumentError: wrong number of arguments (given 2, expected 1)

我尝试过的情况

patch :update, {'id'=> @api_user['user']['id'], 'user' => attributes_for(:normal_user)}

patch :update, 'id'=> @api_user['user']['id'], 'user' => attributes_for(:normal_user)

patch :update, 'id'=> @api_user['user']['id'], :params => {'user' => attributes_for(:normal_user)}

我尝试了这个 patch :update, :params => {'user' => create(:normal_user)}。 #这个ID在其中

但是给出了这个错误

No route matches {:action=>"update", :controller=>"api/users", :user=>#<User id: 227794695, email: "test11@example.com", created_at: "2020-05-03 08:51:55", updated_at: "2020-05-03 08:51:55", is_admin: nil, first_name: "test", last_name: "test">},网址应为update/id

1 个答案:

答案 0 :(得分:0)

您不应在补丁后放置“更新”,因为 自行修补程序将自动路由以更新到用户控制器

这是给您2个错误消息的原因,预期有1个参数

以下是示例,供您参考

require 'rails_helper'

RSpec.describe 'User request', type: :request do
  it 'should update user email' do
    patch "/api/users/#{@api_user['user']['id']}",
          params: {
            user: {
              email: 'new_email_address@gmail.com'
            }
          },
          as: :json
    expect(response).to have_http_status(:success)
  end
end

这是/config/routes.rb的示例,供您参考以更新用户

Rails.application.routes.draw do
  namespace :api, defaults: { format: :json } do
    resources :users, only: [:create, :update, :destroy]
  end
end