gatordh7 gatordh7 - 10 months ago 85
JSON Question

rspec controller test for json api : ActionController::RoutingError

just a simple question for a render json call I'm trying to test. I'm still learning rspec, and have tried everything and can't seem to get this to work. I keep getting an ActionController::RoutingError, even though I defined the route and the call to the api itself works.

In my controller I have the method:

class PlacesController < ApplicationController
def objects
@objects = Place.find(params[:id])
render json:

with the render json:, I'm calling the api method in the Object model

class Object
def api
{ id: id,
something: something,
something_else: something_else,
etc: etc,

My routes file:

get "places/:id/objects" => "places#objects"

my rspec: spec/controllers/places_controller_spec.rb

describe "objects" do
it "GET properties" do
m = FactoryGirl.create :object_name, _id: "1", shape: "square"
get "/places/#{m._id}/objects", {}, { "Accept" => "application/json" }

expect(response.status).to eq 200
body = JSON.parse(response.body)
expect(body["shape"]).to eq "square"

I keep getting the error

Failure/Error: get "/places/1/objects", {}, { "Accept" => "application/json" }
No route matches {:controller=>"places", :action=>"/places/1/objects"}

Any help would be much appreciated, thanks.

Answer Source

Because you have the spec in the controllers folder RSpec is assuming it is a controller spec.

With controller specs you don't specify the whole path to the route but the actual controller method.

get "/places/#{m._id}/objects", {}

Should be

get :objects, id: m._id

If you don't want this behaviour you can disable it by setting the config infer_spec_type_from_file_location to false. Or you could override the spec type for this file by declaring the type on the describe

describe "objects", type: :request do - change :request to what you want this spec to be.

Although I recommend using the directory structure to dictate what types of specs you are running.