如何使用 get 方法只发送 1 个参数?

How to send only 1 parameter with get method?

我有一个使用这种索引方法的控制器 (app/controllers/api/v1/users_controller.rb)

...
  before_action :find_user, only: [:show, :destroy]

  def index
    @users = User.order('created_at DESC')
  end
...

我有一个观点 (app/view/api/v1/users/index.json.jbuilder)

json.array! @users do |user|
  json.id user.id
  json.name user.name
  json.posts user.posts do |post|
    json.id post.id
    json.title post.title
    json.body post.body
  end
end

当我 运行 服务器工作正常时,访问 localhost:3000/api/v1/users 后它显示预期的输出。 但是当我启动这些 RSpec 测试时 (spec/controllers/api/v1/users_controller_spec.rb)

require 'rails_helper'

RSpec.describe Api::V1::UsersController, type: :controller do
  describe "GET #index" do
    before do
      get :index
    end
    it "returns http success" do
      expect(response).to have_http_status(:success)
    end
  end
end

我收到一个错误 如果我从 get :index 中删除 :index 它会给出相同的错误但是(给定 0,预期为 1)。 如果只有一个参数,为什么 get :index 发送 2 个参数?我如何重写这段代码以便测试通过?

如果我这样重写索引方法

  def index
    @users = User.order('created_at DESC')
    render json: @users, status: 200 
  end

测试会通过,但在这种情况下我不会得到我需要的 JSON 文件(我用 jbuilder 制作的)

您应该将 get 请求移到您的 it 块下

尝试

require 'rails_helper'

RSpec.describe Api::V1::UsersController, type: :controller do
  describe "GET #index" do
    it "returns http success" do
      get :index
      expect(response).to have_http_status(:success)
    end
  end
end

RSpec documentation

我前段时间找到了解决办法。我所要做的就是放置

  gem 'rspec-core', git: 'https://github.com/rspec/rspec-core'
  gem 'rspec-expectations', git: 'https://github.com/rspec/rspec-expectations'
  gem 'rspec-mocks', git: 'https://github.com/rspec/rspec-mocks'
  gem 'rspec-rails', git: 'https://github.com/rspec/rspec-rails'
  gem 'rspec-support', git: 'https://github.com/rspec/rspec-support'
  gem 'rails-controller-testing'

在我的 Gemfile 中。