【问题标题】:Use Patch with rspec tests将补丁与 rspec 测试一起使用
【发布时间】:2020-05-03 08:54:42
【问题描述】:

我正在尝试使用 Rspec 测试用于设计用户信息的补丁,更新 url 看起来像这样 # 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">} 有意义,url 应该是update/id

【问题讨论】:

    标签: ruby-on-rails rspec devise


    【解决方案1】:

    你不应该在补丁之后加上“更新”,因为 补丁它自己会自动路由更新到用户控制器

    这是错误消息通知您给出 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
    

    【讨论】:

    • 我无法使用这条路线api/user 它一直给我No route matches {:action=>"/api/users/227794811", :controller=>"api/users", :format=>:json, :user=>{:password=>"newPassword"}} 即使路线存在于 api/user_controller
    • 我刚刚更新了我上面的答案,你可以自定义检查你的 config/routes.rb 的设置
    猜你喜欢
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 2023-03-09
    • 2018-06-25
    • 1970-01-01
    相关资源
    最近更新 更多