【发布时间】:2016-05-16 20:05:57
【问题描述】:
我正在尝试测试通过嵌套路由访问的控制器,但我不断收到错误消息说“没有路由匹配。
规格
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
config/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
spec/support/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
【问题讨论】:
-
这通常是因为
post/patch的参数是错误的。见guides.rubyonrails.org/…。确保您确实传递了一个哈希(如果这是您想要的)。 -
你为什么要屈服于一个除了运行一个方法来构建哈希之外什么都不做的块?你不能只传递适当的哈希值吗?
-
@engineersmnky 我不确定,该代码不是我自己的
标签: ruby-on-rails ruby json rspec