问题
I am running Rails 3.2.1 and rails-rspec 2.8.1....When I run the test for resetting a user's password, it seems that reloading the user object doesn't load the new password attribute....
Here is the code for my test:
describe "Reset password page" do
let(:teacher) { FactoryGirl.create(:teacher, :email=>"jane@gmail.com")}
let(:old_password) { teacher.password }
before do
visit reset_password_form_path
fill_in "Email", with: teacher.email
click_button "Reset Password"
end
it { should have_content('Your new password has been emailed to the address you provided.')}
specify { Teacher.find_by_email("jane@gmail.com").password.should_not == old_password }
## specify { teacher.reload.password.should_not == old_password } ##THIS FAILS
end
specify { teacher.reload.password.should_not == old_password } FAILS but specify { Teacher.find_by_email("jane@gmail.com").password.should_not == old_password } PASSES
So this tells me the password is being saved correctly, but not being reloaded...any ideas why? I am using the Rails 3.2.x "has_secure_password" method for rolling the login/password features. This means a password_digest is what gets saved to the database, and password is a virtual attribute (I think).
回答1:
Just understood: let
blocks are not loaded till you summon them.
So, because you didn't use old_password
anywhere before:
teacher.reload.password.should_not == old_password
Is equivalent to:
teacher.reload.password.should_not == teacher.reload.password
That's why it just can't fail!
If you want it to fail correctly:
old_password #because it's triggered, the value is set and won't be set again
teacher.reload.password.should_not == old_password
Edit:
describe "Reset password page" do
let(:teacher) { FactoryGirl.create(:teacher, :email=>"jane@gmail.com")}
before do
@old_password = teacher.password
visit reset_password_form_path
fill_in "Email", with: teacher.email
click_button "Reset Password"
end
specify { teacher.reload.password.should_not == @old_password }
end
来源:https://stackoverflow.com/questions/10626831/rspec-doesnt-reload-changed-password-attribute-why