NoamB/sorcery — Issue #150: Issue testing password change implementation suing FactoryGirl
Author: xlprojects
Created: 2011-11-12 05:34:39+00:00
State: open

Hey there, hope someone can help me.

I've created a change password method for the User model as follow

```ruby
def update_password(current_password, new_password, new_password_confirmation)
if new_password == new_password_confirmation
if !User.authenticate(self.username, current_password).nil?
return self.change_password!(new_password)
else
return false
end
else
return false
end
end
```

Here is my User factory

```ruby
FactoryGirl.define do
factory :user do
first_name "Bob"
last_name "Sinclar"
date_of_birth "03/12/1982"
genre "M"
sequence(:username) { |n| "bsinclar#{n}" }
email { "#{username}@example.com" }
password "secret"
salt "asdasdastr4325234324sdfds"
activation_state "active"
admin false

after_build do |u|
u.crypted_password = Sorcery::CryptoProviders::BCrypt.encrypt(u.password, u.salt)
end

factory :admin_user do
admin true
end
end
end
```

Here are my rspec tests

```ruby
require 'spec_helper'

describe User do
subject { Factory(:user) }

describe :update_password do
let!(:bob) {Factory(:user, password: "password", password_confirmation: "password" )}

it "updates the password if everything is passed correctly" do
bob.update_password("password","new_pass","new_pass").should be_true
end

it "throws an error if you enter the incorrect current password" do
bob.update_password("bad_password","new_pass","new_pass").should be_false
end

it "throws an error if the new password isn't confirmed properly" do
bob.update_password("password","new_pass","bad_new_pass").should be_false
end
end
end
```

I obtain F.. but in fact it seems like even if I try to authentify with the password "password", it complains that the password is not valid.
Using pry, I was able to investigate about the user object in the test (here 'bob') and it seems that the salt gets changed upon user creation... I am not sure why or how... This is what I get with some tryouts:

```ruby
pry(#)> bob
=> #
pry(#)> bob.salt
=> "7a5c5bfa820ba61284e614c6098ea6709eb385bf"
pry(#)> bob.crypted_password
=> "$2a$10$2c6n5H5g7jNpvUX50iXcdeAfOLdaC8TnhcHQddeClkFhpnm9Zr4MC"
pry(#)> Sorcery::CryptoProviders::BCrypt.encrypt("password", bob.salt)
=> "$2a$10$RekZ5aMdXRK8zGKk7N5QQuMXDKzEQ.UGm9LhA2KvQe9jAd58X1RkG"
pry(#)> Sorcery::CryptoProviders::BCrypt.encrypt("password", "asdasdastr4325234324sdfds")
=> "$2a$10$RFsoUOAiernoegn1ibftzuF5w.rlVtXZoyTQ9iwHda8jDQb5FUOcq"
```

I'm quite confused and would appreciate any help to help me debug my test suite... the change password functionality works fine.... I just want it tested thoroughly but FactoryGirl seems to not cope nicely with sorcery... thoughts?