Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise Lockable not working in rspec controller tests

We have a custom SessionsController that inherits from the standard Devise::SessionsController and have lockable enabled for the User model. This works when testing manually, but in our controller tests failed_attempts is not incrementing beyond 1. If I reduce maximum_attempts attempts to 1 it will successfully lock the account in testing, but it still will not increment failed_attempts beyond 1.

Below is my test example. Any ideas as to why failed_attempts is not incrementing beyond one 1 controller tests?

it{
  bad_user = create(:user, password: 'passworD1')
  3.times do
    post :create, user: { email: bad_user.email, password: 'asdf' }
  end

  post :create, user: { email: bad_user.email, password: 'asdf' }
  bad_user.reload
  expect(bad_user.failed_attempts).to eq(4)
  expect(bad_user.locked_at).not_to be_blank
}
like image 718
commandantk Avatar asked May 15 '15 17:05

commandantk


2 Answers

I tried this method warden.clear_strategies_cache! after post and I was able to lock the account.

For your example it would look like this:

it{
  bad_user = create(:user, password: 'passworD1')
  3.times do
    post :create, user: { email: bad_user.email, password: 'asdf' }
    warden.clear_strategies_cache!
  end

  post :create, user: { email: bad_user.email, password: 'asdf' }
  bad_user.reload
  expect(bad_user.failed_attempts).to eq(4)
  expect(bad_user.locked_at).not_to be_blank
}

Regards, Ruslan

like image 189
ruslan Avatar answered Sep 30 '22 16:09

ruslan


Per Devise lockable module There is a method lock_access! which locks access. That's one way to test another - brute force. Enter right email and wrong password at new_user_session_path as many time as needed per devise initializer then test new_user_unlock_path.

like image 20
Elkhan Mamedov Avatar answered Sep 30 '22 15:09

Elkhan Mamedov