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?