gpt4 book ai didi

ruby-on-rails - 使用 before_action 过滤器的 RSPEC 测试索引操作

转载 作者:数据小太阳 更新时间:2023-10-29 07:37:42 25 4
gpt4 key购买 nike

我有一个 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

ActivitiesController.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/".

最佳答案

经过长时间的讨论,我认为测试应该是这样的(没有测试:))

require 'rails_helper'

RSpec.describe ActivitiesController, :type => :controller do

describe "GET index" do

before(:each) do
@activity = FactoryGirl.create(:activity)
end

context 'when user is logged' do

before(:each) do
session[:current_user] = @activity.user_id
end

it "shows all activities for signed in user" do
get :index, {user_id: @activity.user_id}
expect(response).to be_success
end
end

context 'when user is anonymous' do
it "redirects user to root path" do
get :index, {user_id: @activity.user_id}
expect(response).to redirect_to root_path
end
end

end


end

关于ruby-on-rails - 使用 before_action 过滤器的 RSPEC 测试索引操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27705660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com