Doug Steinberg
Doug Steinberg

Reputation: 1162

Rspec, how do I test if a response renders a template

I'm new to rspec and writing test. I need to write a test for the show action of my VideosController. Here is my test

describe VideosController do
  describe "GET show" do
    it "renders the show template" do
      video = Video.create(title: "Game of Thrones", description: "A very awesome show!")
      get :show, id: video.id
      expect(response).to render_template(:show)
    end
  end
end

When I run this I get this error

 1) VideosController GET show renders the show template
 Failure/Error: expect(response).to render_template(:show)
   expecting <"show"> but rendering with <[]>

What am I missing here?

EDIT: VideosController

class VideosController < ApplicationController

  before_action :require_user

  def show
    @video = Video.find(params[:id])
  end

  def search
    @search_phrase = params[:search_term]
    @search_result = Video.search_by_title(@search_phrase)
  end

  end

Upvotes: 0

Views: 618

Answers (1)

agmcleod
agmcleod

Reputation: 13621

For setting the user, controller tests are meant to be isolated from other aspects of the app. So really you can simply stub the user. Provided you're using a method in your application controller like:

def current_user
  @current_user ||= User.find session[:user_id]
end

Then you can just stub it:

controller.stub(current_user: User.create(email: "[email protected]", password: "abc123", password_confirmation: "abc123"))

Adjust the user params to your need. Also instead of invoking active record directly, have a look at: http://github.com/thoughtbot/factory_girl.

So what happens there is when the controller invokes current_user, it returns the user record.

Upvotes: 1

Related Questions