Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec not sending a Post request in JSON

I'm doing a Rails App that it's mostly an API. I'm trying to test the controllers for my API endpoints. My RSpec Controller tester is as following:

require 'rails_helper'
require 'spec_helper'
require 'rack/test'
require 'devise'

class RoutesControllerTest < ActionController::TestCase

  describe "User with token"
    test "should post route" do  
      params = { route: {  start_lat: 38.7627951, start_long: -9.1532211,
                            end_lat: 38.7483783, end_long: -9.155045,
                            flag_opt: 0.4, city: 1 }
                }

      post '/routes.json' , params.to_json, format: :json
      assert_response :success
    end
  end
end

And My Controller is:

class RoutesController < ApplicationController

  def create
    city = City.find(params[:route][:city])
    user = current_user
    @route = user.routes.new(route_params)
    @results = @route.calc_route(@route.start_long, @route.start_lat, @route.end_long, @route.end_lat, params[:route][:flag_opt], city)
    if @route.save!
      render :template=>"/routes/routes.json.jbuilder", status: 201, :formats => [:json]
    else
      render json: @route.errors
    end
  end

  private

  def route_params
    json_params = ActionController::Parameters.new( JSON.parse(request.body.read) )
    json_params.require(:route).permit(
          :start_lat, 
          :start_long, 
          :end_lat, 
          :end_long,
          :flag_opt
     )
  end
end

But everytime I run the rspec spec/controller I get into the following error:

Failure/Error: json_params = ActionController::Parameters.new(JSON.parse(request.body.read) )

JSON::ParserError:
  757: unexpected token at 'route%5Bcity%5D=24&route%5Bend_lat%5D=41.26171490000001&route%5Bend_long%5D=-8.38193640000001&route%5Bflag_opt%5D=1&route%5Bstart_lat%5D=38.753225&route%5Bstart_long%5D=-9.144376&route%5Buser_id%5D=24'

Which means that the request is not being sent as JSON

like image 542
tvieira Avatar asked Dec 06 '25 08:12

tvieira


2 Answers

I've been struggling with this one too. Sometimes you really just want to test with a real JSON body. I'm not sure if this solution is specific to Rails 5, but after a lot of hunting I was relieved to finally figure this one out.

You can use as: :json instead of format: :json to make RSpec format the request body.

That is, change:

post '/routes.json' , params.to_json, format: :json

to

post '/routes.json' , params.to_json, as: :json
like image 97
nicb Avatar answered Dec 08 '25 21:12

nicb


This worked for me to test a json posted on the body to the controller (RSpec 3.7.0)

post :action, params: { whatever: value }, body: { some_key: value }.to_json, as: :json

And you read your controller with

request.body.read

like image 26
nitrnitr Avatar answered Dec 08 '25 23:12

nitrnitr