如何测试after_sign_in_path_for(资源)?

Dav*_*ite 17 rspec ruby-on-rails devise rspec2 ruby-on-rails-3

我已经在我的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
Run Code Online (Sandbox Code Playgroud)

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

 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>
Run Code Online (Sandbox Code Playgroud)

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

cai*_*nne 32

奇怪的是,我今天想知道这件事.这就是我想出来的.我创建了一个ApplicationController的匿名子类.在这个匿名子类中,我公开了我想要测试的受保护方法作为公共方法.然后我直接测试了它们.

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
Run Code Online (Sandbox Code Playgroud)