【发布时间】:2014-12-30 12:39:01
【问题描述】:
我有一个before_action 过滤器并想测试索引操作是否仅在用户登录时执行。简单地说,我不知道该怎么做。我正在使用我自己的简单身份验证,我知道我可以使用 CanCan 或类似的,但为了我自己的学习,我正在努力做到这一点!
ApplicationController.rb
helper_method :logged_in
helper_method :current_user
def current_user
@current_user ||= User.find_by_id(session[:current_user]) if session[:current_user]
end
def logged_in
unless current_user
redirect_to root_path
end
end
ActivityController.rb
before_action :logged_in
def index
@activities = Activity.all.where(user_id: @current_user)
end
Activities_Controller_spec.rb
require 'rails_helper'
RSpec.describe ActivitiesController, :type => :controller do
describe "GET index" do
before(:each) do
@activity = FactoryGirl.create(:activity)
session[:current_user] = @activity.user_id
@current_user = User.find_by_id(session[:current_user]) if session[:current_user]
end
it "shows all activities for signed in user" do
get :index, {user_id: @activity.user_id}
expect(response).to redirect_to user_activities_path
end
end
end
activities.rb(工厂)
FactoryGirl.define do
factory :activity do
association :user
title { Faker::App.name }
activity_begin { Faker::Date.forward(10) }
activity_end { Faker::Date.forward(24) }
end
end
我收到以下错误:
Failure/Error: expect(response).to redirect_to user_activities_path
Expected response to be a redirect to <http://test.host/users/1/activities> but was a redirect to <http://test.host/>.
Expected "http://test.host/users/1/activities" to be === "http://test.host/".
【问题讨论】:
-
你可以测试重定向(见this)
-
是的,谢谢,我实际上已更改为重定向,但出现错误。我会更新问题
-
当然:您将
response与user_activities_path(它是一个URL 或只是一个字符串)进行比较。小心你应该写expect(response).to eq(...)(你错过了eq) -
我实际上得到了以下信息:
expect(response).to redirect_to user_activities_path这就是产生错误的原因 -
当我认为您想使用返回变量
@current_user的方法current_user时,您的助手logged_in使用@current_user。logged_in@current_user中的其他词总是为零(未定义)
标签: ruby-on-rails ruby ruby-on-rails-4 rspec before-filter