Reputation: 495
I'm using the jsonapi-serializers gem and am having some trouble with figuring out how to test a post request with rspec and a json payload. I know it works because I can use postman and send json and it successfully creates the new object, but I'm not sure why I can't get the rspec test to work.
Here's the api controller method:
def create
@sections = @survey.sections.all
if @sections.save
render json: serialize_model(@section), status: :created
else
render json: @section.errors, status: :unproccessable_entity
end
end
The serialize_model
is just a helper for JSONAPI::Serializer.serialize
Here's my current rspec tests for that controller:
describe 'POST #create' do
before :each do
@section_params = { section: { title: 'Section 1', position: 'top', instructions: 'fill it out' } }
post '/surveys/1/sections', @section_params.to_json, format: :json
end
it 'responds successfully with an HTTP 201 status code' do
expect(response).to be_success
expect(response).to have_http_status(201)
end
end
I've tried a few different things and can't figure out how to fix this. If I make a post the that url with Postman and that exact json payload, it successfully creates the new section.
The get request tests are working fine, I'm just not sure how to handle the json request data with rspec and the jsonapi-serializer.
Upvotes: 0
Views: 723
Reputation: 4639
Try this. Substitute YourApiController
for whatever you named yours
describe YourApiController, type: :controller do
context "#create" do
it 'responds successfully with an HTTP 201 status code' do
params = { section: { title: 'Section 1', position: 'top', instructions: 'fill it out' } }
survey = double(:survey, sections: [])
sections = double(:sections)
section = double(:section)
expect(survey).to receive(:sections).and_return(sections)
expect(sections).to receive(:all).and_return(sections)
expect(sections).to receive(:save).and_return(true)
expect(controller).to receive(:serialize_model).with(section)
post :create, params, format: :json
expect(response).to be_success
expect(response).to have_http_status(201)
expect(assigns(:sections)).to eq sections
end
end
end
Upvotes: 1