如何测试成功更改密码?

eno*_*com 2 rspec ruby-on-rails rspec-rails ruby-on-rails-3 railstutorial.org

我使用bcrypt-ruby和组合了一个用户身份验证的基本应用程序has_secure_password.结果基本上是Rails教程中应用程序的准系统版本.换句话说,我有一个RESTful用户模型以及登录和注销功能.

作为编辑用户信息的测试的一部分,我编写了一个更改密码的测试.虽然更改密码在浏览器中工作正常,但我的测试不会通过.

subject { page }

describe "successful password change"
  let(:new_password) { "foobaz" }
  before do
    fill_in "Password",               with: new_password
    fill_in "Password Confirmation",  with: new_password
    click_button "Save changes"
  end

  specify { user.reload.password.should == new_password }
end
Run Code Online (Sandbox Code Playgroud)

显然,我在这里误解了一些基本细节.

简而言之:

1)为什么上面的代码无法正常工作?更改密码功能在浏览器中有效.同时,rspec继续在上面的最后一行重新加载旧密码.然后测试失败了.

2)测试密码更改的更好方法是什么?

编辑:

将初始密码设置为foobar,错误消息为:

Failure/Error: specify { user.reload.password.should == new_password }
   expected: "foobaz"
        got: "foobar" (using ==)
Run Code Online (Sandbox Code Playgroud)

基本上,看起来before块实际上并没有保存新密码.

作为参考,相关的控制器动作如下:

def update
  @user = User.find(params[:id])
  if @user.update_attributes(params[:user])
    flash[:success] = "Profile Updated"
    sign_in @user
    redirect_to root_path
  else
    render 'edit'
  end
end
Run Code Online (Sandbox Code Playgroud)

Fra*_* Yu 6

对于Devise用户,请#valid_password?改用:

expect(user.valid_password?('correct_password')).to be(true)
Run Code Online (Sandbox Code Playgroud)

图片来源:Ryan Bigg