加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 02:07:32 所属栏目:百科 来源:网络整理
导读:我有一个before_action过滤器,并希望测试只有在用户登录时才执行索引操作.简单地说,我不知道如何执行此操作.我正在使用我自己的简单身份验证,我知道我可以使用CanCan或类似的但是对于我自己的学习我正在努力做到这一点! ApplicationController.rb helper_me
我有一个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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读