Как проверить after_sign_in_path_for (ресурс)?
Я разработал аутентификацию и регистрацию, настроенные в моем приложении 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>
Итак, как я могу проверить этот метод?
Ответы
Ответ 1
Как ни странно, сегодня мне было интересно это. Вот что я придумал. Я создал анонимный подкласс 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
Ответ 2
Аналогичным образом - если вы хотите протестировать перенаправление после регистрации, у вас есть два варианта.
Во-первых, вы можете следовать шаблону, аналогичному приведенному выше, и очень непосредственно протестировать метод в RegistrationsController:
require 'spec_helper'
describe RegistrationsController do
controller(RegistrationsController) do
def after_sign_up_path_for(resource)
super resource
end
end
describe "After sign-up" do
it "redirects to the /organizations/new page" do
@user = FactoryGirl.build(:user)
controller.after_sign_up_path_for(@user).should == new_organization_path
end
end
end
Или вы можете использовать более простой подход к интеграции и тестированию:
require 'spec_helper'
describe RegistrationsController do
describe "After successfully completing the sign-up form" do
before do
@request.env["devise.mapping"] = Devise.mappings[:user]
end
it "redirects to the new organization page" do
post :create, :user => {"name" => "Test User", "email" => "[email protected]", "password" => "please"}
response.should redirect_to(new_organization_path)
end
end
end
Ответ 3
context "without previous page" do
before do
Factory.create(:user, email: "[email protected]", password: "123456", password_confirmation: "123456")
request.env["devise.mapping"] = Devise.mappings[:user]
post :create, user: { email: "[email protected]", password: "123456" }
end
end
it { response.should redirect_to(root_path) }
context "with previous page" do
before do
Factory.create(:user, email: "[email protected]", password: "123456", password_confirmation: "123456")
request.env["devise.mapping"] = Devise.mappings[:user]
request.env['HTTP_REFERER'] = 'http://test.com/restaurants'
post :create, user: { email: "[email protected]", password: "123456" }
end
it { response.should redirect_to("http://test.com/restaurants") }
end
Ответ 4
Для новичков я бы порекомендовал сделать так:
RSpec.describe ApplicationController, type: :controller do
let(:user) { create :user }
describe "After sing-in" do
it "redirects to the /yourpath/ home page" do
expect(subject.after_sign_in_path_for(user)).to eq(yourpath_root_path)
end
end
end