我使用M. Hartl Rails教程創建我的應用程序。所以我有一個User
模型,以及所有current_user
和signed_in_user
方法。登錄用戶似乎無法登錄
我想提出以下測試通過:
describe "submitting a PATCH request to the Users#update action" do
before do
be_signed_in_as FactoryGirl.create(:user)
patch user_path(FactoryGirl.create(:user))
end
specify { expect(response).to redirect_to(root_path) }
end
但測試失敗:
Failure/Error: specify { expect(response).to redirect_to(root_path) }
Expected response to be a redirect to <http://www.example.com/> but was a redirect to <http://www.example.com/signin>.
Expected "http://www.example.com/" to be === "http://www.example.com/signin".
因此,這裏是用戶控制器
class UsersController < ApplicationController
before_action :signed_in_user, only: [:index, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
.
.
.
.
private
def signed_in_user
unless !current_user.nil?
store_url
redirect_to signin_url, notice: t('sign.in.please')
end
end
def correct_user
@user = User.find(params[:id])
redirect_to(root_path) unless current_user?(@user)
end
def admin_user
redirect_to(root_path) unless current_user.admin?
end
end
的一部分如果我刪除before_create :signed_in_user...
行,測試通過。 但是爲什麼呢? be_signed_in_as
spec方法在所有其他測試(〜1k)中工作,所以原因必須在specify { expect(response)
之內。
'除非!current_user.nil?'這幾乎是你可以寫在這種情況下最糟糕的邏輯。是否應該表示'如果current_user.nil?'或'除非current_user.present?'?不過,我認爲修補程序請求不會將會話cookie發送到您的應用程序,所以不需要'current_user' – phoet
我該如何模擬會話cookie? –