我有一个使用此索引方法的控制器(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
我收到一个错误如果我从:index
中删除get :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
我前一段时间找到了解决方案。我要做的就是放置
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中。