1

I am trying to test the following code

# 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

I keep getting an error

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

I can't figure out what's happening since my test is clearly passing data with the attributes with an empty hash. Any input to how I can achieve writing my test so that it passes and allows me to test passing in invalid attributes would be appreciated.

Note when I edit invalid_params to include { name: '' } the test passes. I would have thought I could pass an empty hash?

Ryan-Neal Mes
  • 6,003
  • 7
  • 52
  • 77
  • Possible duplicate of [Rails - Strong parameters with empty arrays](http://stackoverflow.com/questions/20164354/rails-strong-parameters-with-empty-arrays) – Dave Schweisguth Mar 16 '16 at 00:33
  • This is not a duplicate as it does not relate to empty arrays, it has to do with an empty hash. After searching more this is an issue with rails - https://github.com/rails/strong_parameters/issues/162 - and the best way to get around it is to use fetch with a default instead of require - `params.fetch(:data, {}).permit(attributes: [ :name ] )` – Ryan-Neal Mes Mar 16 '16 at 07:07

0 Answers0