无法使终点规格通过

时间:2016-03-15 20:20:06

标签: rspec rails-api

我正在尝试测试以下代码

# spec/controllers/api/v1/item_types_controller_spec.rb

let(:valid_session) { {} }

let(:invalid_attributes) {
        { }
}

describe "with invalid params" do
  it "assigns a newly created but unsaved item_type as @item_type" do
    post :create, {type: 'item_types', data: { attributes: invalid_attributes}} , valid_session
    expect(assigns(:item_type)).to be_a_new(ItemType)
  end
end

# app/controllers/api/v1/item_types_controller.rb

module Api
  module V1
    class ItemTypesController < ApplicationController
      def create
        @item_type = ItemType.new(item_type_params)

        if @item_type.save
          render json: @item_type, status: :created, location: api_v1_item_type_url(@item_type)
        else
          render json: @item_type.errors, status: :unprocessable_entity
        end
      end

      private

      def item_type_params
        params.require(:data).permit(attributes: [ :name ] )
      end
    end
  end
end

class ItemType < ApplicationRecord
  validates_presence_of :name
end

我一直收到错误

Failures:

  1) Api::V1::ItemTypesController POST create with invalid params assigns a newly created but unsaved item_type as @item_type
     Failure/Error: post :create, {type: 'item_types', data: { attributes: invalid_attributes}} , valid_session
     ActionController::ParameterMissing:
       param is missing or the value is empty: data

我无法弄清楚发生了什么,因为我的测试显然是使用带有空哈希的属性传递数据。任何关于如何编写测试以使其通过并允许我测试传递无效属性的输入将不胜感激。

当我编辑invalid_params以包含{ name: '' }测试通过时,请注意。我原以为我可以传递一个空哈希?

0 个答案:

没有答案