ruby on rails - I just can't get my valid password test to pass -


i'm trying valid password test pass. when run it seems password_digest hash different. don't know them match.

i using book "ruby on rails tutorial: learn rails example" michael hartl , seems gets pass.

additionally, application code works expected. can create user , authenticate them in console breaking in tests.

i'm new testing may missing obvious here.

thanks help!

i using bcrypt has_secure_password , here's part relavent user spec code:

describe user    before { @user = user.new(name: "example user", email: "user@example.com", password: "foobar", password_confirmation: "foobar") }    subject { @user }    { should respond_to(:name) }   { should respond_to(:email) }   { should respond_to(:password_digest) }   { should respond_to(:password) }   { should respond_to(:password_confirmation) }   { should respond_to(:authenticate) }    { should be_valid }    describe "return value of authenticate method"     before { @user.save }     let(:found_user) { user.find_by(email: @user.email) }      describe "with valid password"       { should eq found_user.authenticate(@user.password) }     end      describe "with invalid password"       let(:user_for_invalid_password) { found_user.authenticate('invalid') }        { should_not eq user_for_invalid_password }       specify { expect(user_for_invalid_password).to be_false }     end   end end 

and user model

class user < activerecord::base   before_save  { self.email = email.downcase }    validates :name, presence: true, length: { maximum: 50 }    valid_email_regex = /\a[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i   validates :email, presence: true, uniqueness: { case_sensitive: false }, format: { with: valid_email_regex }    has_secure_password   validates :password_confirmation, presence: true   validates :password, length: { minimum: 6 } end 

the problem in before { @user.save }. may not have realized it, before defaults before(:each), means code runs before each example in group. expected default before(:all), runs once, before examples in group.

as mentioned, aren't clearing database after each test. therefore, before each test, calling @user.save. silently fails validation returning false, because trying create user same email address. it's better use #save! validation exceptions thrown, making problems more obvious.

to summarize:

  • explicitly use before(:all) or before(:each)
  • use #save! instead of #save
  • clear database between each test (try out database cleaner)

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -