【问题标题】:How to send only 1 parameter with get method?如何使用 get 方法仅发送 1 个参数?
【发布时间】:2020-01-06 22:30:47
【问题描述】:

我有一个使用这种索引方法的控制器 (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 制作的)

【问题讨论】:

  • 您是否尝试过使用 curl 手动执行 GET 以获得更好的堆栈跟踪?错误(ActionView::Template::Error)和解决方法(不要使用模板)表明您的问题出在 jbuilder 模板中。

标签: ruby ruby-on-rails-5 rspec-rails


【解决方案1】:

您应该将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

【讨论】:

    【解决方案2】:

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

      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 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-16
      • 2020-04-27
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 2020-08-24
      • 1970-01-01
      相关资源
      最近更新 更多