gpt4 book ai didi

ruby-on-rails - 如何测试 after_sign_in_path_for(resource)?

转载 作者:行者123 更新时间:2023-12-03 01:40:11 28 4
gpt4 key购买 nike

我在 Rails 应用程序上设置了身份验证和注册。我使用 after_sign_in_path_for() 根据各种场景自定义用户登录时的重定向。

我想问的是如何测试这个方法?似乎很难隔离,因为它是在用户登录时由 Devise 自动调用的。我想做这样的事情:

describe ApplicationController do
describe "after_sign_in_path_for" do
before :each do
@user = Factory :user
@listing = Factory :listing
sign_in @user
end

describe "with listing_id on the session" do
before :each do
session[:listing_id] = @listing.id
end

describe "and a user in one team" do
it "should save the listing from the session" do
expect {
ApplicationController.new.after_sign_in_path_for(@user)
}.to change(ListingStore, :count).by(1)
end

it "should return the path to the users team page" do
ApplicationController.new.after_sign_in_path_for(@user).should eq team_path(@user.team)
end
end
end
end
end

但这显然不是这样做的方法,因为我刚刚收到一个错误:

 Failure/Error: ApplicationController.new.after_sign_in_path_for(@user)
RuntimeError:
ActionController::Metal#session delegated to @_request.session, but @_request is nil: #<ApplicationController:0x00000104581c68 @_routes=nil, @_action_has_layout=true, @_view_context_class=nil, @_headers={"Content-Type"=>"text/html"}, @_status=200, @_request=nil, @_response=nil>

那么,我该如何测试这个方法呢?

最佳答案

奇怪的是,我今天就想知道这件事。这就是我的想法。我创建了 ApplicationController 的匿名子类。在这个匿名子类中,我将要测试的 protected 方法公开为公共(public)方法。然后我直接测试了它们。

describe ApplicationController do
controller do
def after_sign_in_path_for(resource)
super resource
end
end

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

describe "After sigin-in" do
it "redirects to the /jobs page" do
controller.after_sign_in_path_for(@user).should == jobs_path
end
end

end

关于ruby-on-rails - 如何测试 after_sign_in_path_for(resource)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6658251/

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