如何测试 after_sign_in_path_for(resource)? [英] How to test after_sign_in_path_for(resource)?
问题描述
我已经在我的 Rails 应用程序上设计了身份验证和注册.我正在使用 after_sign_in_path_for()
来自定义用户登录时基于各种情况的重定向.
I have devise authentication and registration set up on my Rails app. I'm using after_sign_in_path_for()
to customise the redirect when the user signs in based on various scenarios.
我想问的是如何测试这个方法?似乎很难隔离,因为它会在用户登录时由 Devise 自动调用.我想做这样的事情:
What I'm asking is how to test this method? It seems hard to isolate since it is called automatically by Devise when the user signes in. I want to do something like this:
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
但这显然不是这样做的方法,因为我只是收到一个错误:
but that's obviously not the way to do it because I just get an error:
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>
那么,我该如何测试这种方法?
So, how can I test this method?
推荐答案
奇怪的是,我今天就想知道这个问题.这是我想出的.我创建了 ApplicationController 的匿名子类.在这个匿名子类中,我将要测试的受保护方法公开为公共方法.然后我直接测试了它们.
Oddly, I was wondering this very thing today. Here's what I came up with. I created an anonymous subclass of ApplicationController. In this anonymous subclass, I exposed the protected methods that I wanted to test as public methods. Then I tested them directly.
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
这篇关于如何测试 after_sign_in_path_for(resource)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!