【发布时间】:2023-04-09 00:05:01
【问题描述】:
我正在使用 Devise gem 进行身份验证,我也指定了
before_filter :authenticate_contact!
在我的ApplicationController。所以用户在访问应用程序之前需要login。如果他在没有登录的情况下错误输入url,它将要求用户进行身份验证,一旦他登录,它将重定向到他给定的url而不是仪表板,我使用了以下代码
def after_sign_in_path_for(resource)
flash[:notice] = "Welcome #{current_contact.first_name} #{current_contact.last_name}, #{current_contact.company.genre}."
session[:announcements] = true
sign_in_url = new_contact_session_url
if request.referer == sign_in_url
super
else
stored_location_for(resource) || request.referer || root_path
end
end
这工作正常。我的下一步是编写 RSpec 规范:
在我的 spec/controller/application_controller_spec.rb 中
require 'spec_helper'
describe ApplicationController do
controller do
def after_sign_in_path_for(resource)
sign_in_url = new_contact_session_url
if request.referer == sign_in_url
super
else
stored_location_for(resource) || request.referer || root_path
end
end
end
before (:each) do
@user = FactoryGirl.create(:contact_owner, email: 'owner@test.com')
end
describe "After sigin-in" do
it "redirects to the root path" do
controller.after_sign_in_path_for(@user).should == root_path
end
end
end
此规范正在通过,它是第一个场景,即用户进入应用程序登录并获取root_path。但是我在测试第二个条件时遇到了困难,即如果用户在没有身份验证的情况下键入 url,它将要求身份验证,登录后,它应该重定向到他的路径而不是 root_path。
describe CompaniesController do
before do
@user = FactoryGirl.create(:contact_owner, email: "test@test.com")
end
context "when logged in redirect to path" do
before { sign_out @user }
after { sign_in @user } #after this how can i proceed, here user is trying companies/index without login. once he logs in it should redirect_to(companies_path)
it { get :index }
end
end
【问题讨论】:
标签: ruby-on-rails rspec devise rspec-rails