Rspec失败,"没有路由匹配"对于嵌套路由

时间:2016-05-16 20:05:58

标签: ruby-on-rails ruby json rspec

我试图测试通过嵌套路由访问的控制器,但我不断收到错误说"没有路由匹配。

规范

require 'rails_helper'

module V1
  module Forms
    RSpec.describe SectionsController, type: :controller do
      before(:all) do
        attributes = attributes_for(:form)
        @form = Form.make(attributes)
      end

      context 'CRUD' do
        it 'create' do
          post :create, json_api_format { attributes_for(:section) }, form_id: @form[:id]
          expect(response).to be_successful
          expect(json_data).to include(:type, :attributes)
        end

        it 'update' do
          section = create(:section)
          patch :update, id: section[:id], form_id: @form[:id], data: attributes_for(:section, title: 'New Title')
          expect(response.status).to eq(200)
          expect(json_data).to include(:id, :type, :attributes)
        end
      end
    end
  end
end

配置/ routes.rb中

resources :forms, only: [:index, :create, :update, :show] do
  resources :sections, only: [:create, :update] do
    resources :element, only: [:create, :update]
  end
end

sections_controller.rb

module V1
  module Forms
    class SectionsController < ApiController
      def create
        form = Form.find(form_id)
        section = form.sections.create(section_params)
        render json: section, include: '*', status: :created
      end

      def update
        form = Form.find(form_id)
        section = form.sections.find(section_id)
        section.update(section_params)
        render json: section, include: '*', status: :ok
      end

      private

      def section_params
        ActiveModelSerializers::Deserialization.jsonapi_parse(params, only: %i(form_id, title, step))
      end

      def form_id
        params[:form_id]
      end

      def section_id
        params[:id]
      end
    end
  end
end

规格/支持/ json.rb

def json_data
  data = JSON.parse(response.body)['data']
  case data
  when Array
    data
  else
    data.with_indifferent_access
  end
end

def json_api_format(id = nil)
  case id
  when Hash
    { id.keys.first => id.values.first.id, data: { attributes: yield.delete_if { |key, _| key == 'id' } } }
  when Integer
    { id: id, data: { attributes: yield.delete_if { |key, _| key == 'id' } } }
  else
    { data: { attributes: yield } }
  end
end

2 个答案:

答案 0 :(得分:2)

您的路线不代表您尝试使用的2个模块(V1和表格),您需要将这些路线包含在名称空间中,例如:

namespace :V1 do
  namespace :forms do
    resources :sections, only: [:create, :update] do
    resources :element, only: [:create, :update]
  end
end

答案 1 :(得分:1)

update的{​​{1}}行动中似乎有拼写错误。您的方法名为sections_controller.rb,而不是updated