Rspec Rails error : same route name, different verb
Rspec Rails error : same route name, different verb
我在测试我的控制器时遇到了一个奇怪的行为。我有一个 UsersController
有 2 种方法,me
和 update_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 测试真实案例场景时,一切正常,我可以 get
和 patch
一个用户正确。
任何帮助将不胜感激。
get
和 patch
方法不将路由作为第一个参数,它们采用您正在测试的控制器中的操作名称。您也在 patch
调用中调用了 me
方法,这就是它去那里的原因。有关详细信息,请参阅 RSpec controller test documentation and the underlying Rails controller test documentation。
我在测试我的控制器时遇到了一个奇怪的行为。我有一个 UsersController
有 2 种方法,me
和 update_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 测试真实案例场景时,一切正常,我可以 get
和 patch
一个用户正确。
任何帮助将不胜感激。
get
和 patch
方法不将路由作为第一个参数,它们采用您正在测试的控制器中的操作名称。您也在 patch
调用中调用了 me
方法,这就是它去那里的原因。有关详细信息,请参阅 RSpec controller test documentation and the underlying Rails controller test documentation。