0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

assert_empty cookies[:remember_token]がうまくいかない件

Last updated at Posted at 2023-07-01

Rails Tutorialで詰まり、原因究明のためにコードを遡りました。

test/integration/users_login_test.rb
test "login without remembering" do
   log_in_as(@user, remember_me: '1')
   delete logout_path
    
   log_in_as(@user, remember_me: '0')
   assert_empty cookies[:remember_token]
end

テストコードのassert_empty cookies[:remember_token]でFalseになってました。
関数を遡っていきます。

test/test_helper.rb
def log_in_as(user, password: 'password', remember_me: '1')
   post login_path, params: { session: { email: user.email,
                                         password: password,
                                         remember_me: remember_me } }
end
config/routes.rb
   post '/login', to: 'sessions#create'
app/controllers/sessions_controller.rb
def create
   user = User.find_by(email: params[:session][:email].downcase)
   if user && user.authenticate(params[:session][:password])
      log_in user
      params[:session][:remember_me] == '1' ? remember(user) : forget(user)
      remember user
      redirect_to user
   else
      flash.now[:danger] = 'invalid email/password combination'
      render 'new'
   end
end
app/helpers/sessions_helper.rb
def forget(user)
   user.forget
   cookies.delete(:user_id)
   cookies.delete(:remember_token)
end

ここまで遡ってみて、特に問題ないなと思いました。
 

app/controllers/sessions_controller.rb
      params[:session][:remember_me] == '1' ? remember(user) : forget(user)
      remember user

よくみると、一度forgetした後に、rememberしてます。これでは常にremember onをオンにしたのと変わりません。remember userを削除すると、テストにクリアしました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?