我在使用rspec在rails中传递测试时遇到问题。这是控制台在我运行测试时告诉我的。
失败是ControlsController登录的GET索引呈现索引模板 失败/错误:期望(响应)。到render_template(:index) 期待<" index">但使用< []>
进行渲染这是我的代码
require "rails_helper"
RSpec.describe ControlsController,:type => :控制器做 render_views
描述" GET指数"做
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: "juan@gmail.com",
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
答案 0 :(得分:0)
答案是创建一个私有方法并重定向到user_controls_path current_user.name 这是控制器的新代码
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