Empty response when rendering RABL template with RSPEC
Asked Answered
A

1

5

I'm having a perplexing problem where my controller is working fine. However, when I'm testing it with RSPEC it's returning an empty string as the response body.

Here is the controller:

class Api::UsersController < Api::ApplicationController
  def show
    @user = User.find(params[:id])
    render 'show', status: 200
    # render json: @user
  end
end

And the RABL template I'm rendering:

object @user
attributes :id, :name, :email, :phone_number, :invite_token

Finally here is my spec:

require "spec_helper"

describe Api::UsersController do
  it "returns user attributes" do
    user = FactoryGirl.create(:user, name: "Mark", email: "[email protected]")
    get :show, id: user.id
    expect(response.status).to eq(200)
    output = JSON.parse(response.body)
  end
end

When I use render 'show' to render the RABL template my test fails as the response.body is an empty string. However, if I CURL to that endpoint, the body returns just fine.

When I change the controller to: render json: @user the test passes.

Can anyone tell me what's going on here?

Thanks in advance!

Ashanti answered 1/7, 2014 at 19:37 Comment(0)
I
11

try to add render_views at the top of the tests

describe Api::UsersController do

  render_views

  it "returns user attributes" do
    user = FactoryGirl.create(:user, name: "Mark", email: "[email protected]")
    get :show, id: user.id
    output = JSON.parse(response.body)

    expect(response.status).to eq(200)
    expect(output).to eq(expected_hash)        
  end
end

Possible reason: RSpec do not render views by default to speed up tests.

Iguanodon answered 1/7, 2014 at 21:18 Comment(1)
that was it exactly! Thanks so much for the help. I would have spun around forever before figuring that out.Ashanti

© 2022 - 2024 — McMap. All rights reserved.