【问题标题】:Rspec Rails error : same route name, different verbRspec Rails错误:相同的路线名称,不同的动词
【发布时间】:2015-12-20 18:18:26
【问题描述】:

在测试我的控制器时,我实际上遇到了一种奇怪的行为。我有一个UsersController,它有两种方法,meupdate_me

class UsersController < ApplicationController
  def me
    # some code
  end

  def update_me
    # some code
  end
end

对应的路线是:

Rails.application.routes.draw do
  get :me, to: 'users#me'
  patch :me, to: 'users#update_me'
end

在测试GET /me 时,一切正常,所有测试均通过:

RSpec.describe Api::V1::UsersController do
  describe '#me' do
    it 'respond with a 200 ok status' do
      get :me, format: :json, access_token: user_token.token
      expect(response.status).to eq 200
    end

    # more tests
  end
end

但是当我尝试向我提出补丁请求时:

RSpec.describe Api::V1::UsersController do
  describe '#update_me' do
    it 'respond with a 200 ok status' do
      patch :me, format: :json, user: attributes, access_token: user_token.token
      expect(response.status).to eq 200
    end

    # more tests
  end
end

RSpec 实际上在UsersController 的第17 行向我显示了一个错误,这实际上是与def me 方法相关的行,它实际上应该是def update_me

所以我在update_me 中添加了一个raise,并意识到这个方法实际上从未被RSpec 调用过。但是,当使用 Postman 测试真实案例场景时,一切正常,我可以正确地 getpatch 用户。

任何帮助将不胜感激。

【问题讨论】:

    标签: rspec ruby-on-rails-4.2


    【解决方案1】:

    getpatch 方法不将路由作为第一个参数,它们采用您正在测试的控制器中的操作名称。您也在 patch 调用中调用 me 方法,这就是它出现的原因。有关详细信息,请参阅RSpec controller test documentation 和底层Rails controller test documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      • 2021-05-29
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多