获取请求调用实际上 运行 控制器操作吗?

Does a get request call actually run the controller action?

我在 Rails 中有一个非常简单的用例 - 点击端点 /users/show/:id 会将用户的状态更新为 'accepted' 并向他们展示他们的应用程序。

控制器规范

class UsersController < ApplicationController
  def show
    User.find(params[:id]).update_all(status: 'pending')
    @some_variable = 'blahblah'
  end
end

测试

require "spec_helper"

RSpec.describe UsersController do
  describe "GET show" do
    it "should set user to accepted status" do
      get :show, { id: 1, foo: 'bar' }
      expect(User.find(1).status).to eq('accepted')
    end
  end
end

问题

以上对我来说失败了,这告诉我更新状态的控制器代码实际上从来没有 运行ning。

get() 是否真正命中路由 和 运行 控制器操作 ,还是只是发出模拟请求?我尝试在控制器中放置一些 puts 语句,但没有看到它们的输出,这让我进一步相信控制器逻辑永远不会被调用。

如果是后者,我怎样才能真正调用我的控制器操作?

谢谢!

是的。为了说明,您可以这样简化您的控制器:

class UsersController < ApplicationController
  def show
  end
end

然后像这样测试它:

describe "GET show" do
    it "should return 200 status" do
      get :show, { id: 1, foo: 'bar' }
      expect(response.status).to eq(200)
    end
end

供您参考:https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs

我怀疑,你的表演动作应该是这样的,

class UsersController < ApplicationController
  def show
    User.find(params[:id]).update_all({stauts: 'approved'},{ status: 'pending'})
    @some_variable = 'blahblah'
  end
end