【问题标题】:Testing Namespaced Controller测试命名空间控制器
【发布时间】: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


【解决方案1】:

在描述控制器时使用命名空间,这样做

RSpec.describe Api::V1::BudgetsController, type: :controller do

建议

您应该更好地使用请求规范来涵盖 API

有关请求规格的更多信息 - https://relishapp.com/rspec/rspec-rails/docs/request-specs/request-spec

试一试!

【讨论】:

  • 当我尝试这个时,错误变为:``` NameError: uninitialized constant Api # ./spec/controllers/budgets_controller_spec.rb:3:in `' `` `
猜你喜欢
  • 1970-01-01
  • 2013-02-23
  • 1970-01-01
  • 2014-05-19
  • 2011-07-16
  • 1970-01-01
  • 2012-07-08
  • 2023-04-04
  • 2023-03-11
相关资源
最近更新 更多