0
votes

I'm having problems to pass a test in rails with rspec. This is what console tells me when I ran the tests.

The fail is ControlsController GET index logged in renders the index template Failure/Error: expect(response). to render_template(:index) expecting <"index"> but rendering with <[]>

And this is my code

require "rails_helper"

RSpec.describe ControlsController, :type => :controller do render_views

describe "GET index" do

let(:user) { 
FactoryGirl.create(:user)  
}

let(:control) {
  FactoryGirl.create(:control, user: user)
}
context "logged in" do
  before :each do
    sign_in :user, user
  end

  it "loads all controls into @controls" do
    get :index, { user_id: user.id}

    expect(assigns(:controls)).to eq([control])
  end

  it "assigns a new control to @control" do
    get :index, { user_id: user.id}
    expect(assigns(:control)).to be_a_new(Control)
  end

  it "renders the index template" do 
    get :index, { user_id: user.id}
    expect(response). to render_template(:index)
  end

  it "a user can't see the controls from other user" do
    new_user = User.create(name: "Juan", 
                           email: "[email protected]", 
                           password: "123456789", 
                           password_confirmation: "123456789")
    get :index, { user_id: new_user.id}
    expect(response).to redirect_to root_path

  end

class ControlsController < ApplicationController

before_action :authenticate_user! 

def index
    @user= current_user
    @control= Control.new
    # @control_last = Control.lastcontrol (current_user.id)
    # @controls_average = Control.controls_average (current_user.id)
    # @controls_average_day = Control.controls_day_average (current_user.id)
    @controls = Control.all
    if params[:user_id] != current_user.id
        redirect_to root_path
    end
end
1
The index method of the Controller is on the bottomDavid Dsr
It looks like you're redirecting, right? Including the controller would help a tonJohn Paul Ashenfelter
Thank you, I've already fixed it.David Dsr
Would be great to include your answer and accept it to close this question.John Paul Ashenfelter

1 Answers

0
votes

The answer is to make a private method and redirect_to user_controls_path current_user.name This is the new code of the controller

controlsController.rb

class ControlsController < ApplicationController

before_action :authenticate_user!
before_action :redirect_if_not_current_user, only: :index

private

def control_params
    params.require(:control).permit(:level, :period, :day)
end

def redirect_if_not_current_user
    if params[:user_id] != current_user.name
        redirect_to user_controls_path current_user.name
    end
end