【发布时间】:2020-06-14 03:14:07
【问题描述】:
我正在编写一个 Rails API 并且有命名空间的控制器(和路由)。在尝试为所述控制器编写 RSpec 测试时,我遇到了错误,并且不确定如何纠正我的错误。控制器如下:
module Api
module V1
class BudgetsController < ApplicationController
before_action :authenticate_user!
before_action :set_budget, only: %i[destroy]
def new
@budget = current_user.budget.build
render json: @budget
end
def create
@budget = current_user.budget.build(budget_params)
if @budget.save
render json: @budget, status: 200
else
render json: { errors: @budget.errors.full_messages }, status: 422
end
end
def destroy
@budget.destroy
end
private
def set_budget
@budget = Budget.find(params[:id])
end
def budget_params
params.require(budget).permit(:start_date, :end_date, :income)
end
end
end
end
测试(到目前为止)如下:
require 'spec_helper'
RSpec.describe BudgetsController, type: :controller do
let(:valid_attributes) do
{
start_date: "01-03-2020",
end_date: "31-03-2020",
income: 7000
}
end
let(:invalid_attributes) do
{
start_date: nil,
end_date: nil,
income: nil
}
end
describe "GET #index" do
it "returns a success response" do
get :index, params: {}
expect(response).to be_successful
end
end
end
并且仅供参考,路线设置如下:
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
devise_for :users
resources :users, only: %i[show index]
resources :budgets
resources :budget_totals
end
end
end
我得到的错误如下:
Failure/Error:
RSpec.describe BudgetsController, type: :controller do
let(:valid_attributes) do
{
start_date: "01-03-2020",
end_date: "31-03-2020",
income: 7000
}
end
let(:invalid_attributes) do
NameError:
uninitialized constant BudgetsController
# ./spec/controllers/budgets_controller_spec.rb:3:in `<top (required)>'
No examples found.
Finished in 0.00008 seconds (files took 8.51 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples
附言。控制器位于 app/controllers/api/v1 文件夹中。
【问题讨论】:
标签: ruby-on-rails ruby api rspec rspec-rails