Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise: how to get user password from db

I'm writing cucumber tests for user login.

I have such scenario background, that adds user to database

User.create!(

    :email => email,

    :password => password,

    :password_confirmation => password

    )

So, why in my sequential step, I get @user.password nil?

  @user = User.find_by :email => "[email protected]"

  ...

  fill_in('Email', :with => @user.email)

  fill_in('Password', :with => @user.password)
  ...
like image 485
Andrey Khataev Avatar asked Dec 25 '22 13:12

Andrey Khataev


2 Answers

Devise initially stores the original password by encrypting it. The encrypted_password(field name in your model) gets stored in the database.

Now, when you call User.find_by :email => "[email protected]" the password field is non existing.password is not a field in the model User. Its an instance variable present in the model which is only set when you submit the login/sign up form. In your case, you are trying to access password field before log in hence, the instance variable is not set and you get password as nil.

If you want more details, you can check the actual implementation of Devise password

like image 148
Kirti Thorat Avatar answered Jan 07 '23 22:01

Kirti Thorat


Check out the devise cucumber test wiki page for more info.

As Kirti points out you don't have access to the password as an attribute in the User model, especially not in plain text.

If you're testing the login keep the password field around as a variable or create the user in that test.

Given /^I am a new, authenticated user$/ do
  email = '[email protected]'
  password = 'secretpass'
  User.create!(
    :email => email,
    :password => password,
    :password_confirmation => password
  )

  visit '/users/sign_in'
  fill_in "user_email", :with => email
  fill_in "user_password", :with => password
  click_button "Sign in"

end

If you really need to look up your user later (@user = User.find_by) and fill in the password then you'll need to keep your password as a variable outside the scope of the tests.

like image 36
Bryan Clark Avatar answered Jan 08 '23 00:01

Bryan Clark