使用password_digest的rspec失败

时间:2014-01-08 09:47:33

标签: ruby-on-rails-4 railstutorial.org

我正在关注Michael Hartl的教程。我无法让我的rspec测试工作。看起来密码的加密值不一致,导致失败。这令人费解,因为结果不一致。有时,当我回滚迁移,重新迁移,rake测试:准备并再次运行测试时,会通过测试。有时他们仍然失败。这是有原因还是我错误地实现了它?

以下是 user_spec.rb 的特定代码段:

describe "return value of authenticate method" do
    before do
        @user.save
    end
    let(:found_user) { User.find_by(email: @user.email) } #found_user should be the user fetched from the database

    describe "with valid password" do
        it { found_user.authenticate(@user.password).should eq @user }
    end

    describe "with invalid password" do
        let(:user_for_invalid_password) { found_user.authenticate("mismatch") }

        it { should_not eq user_for_invalid_password }
        specify { expect(user_for_invalid_password).to be_false }
    end
end

我收到的示例错误消息:

$ rspec spec/
.........F...................
Failures:

1) User return value of authenticate method with valid password 
 Failure/Error: it { found_user.authenticate(@user.password).should eq @user }

   expected: #<User id: nil, name: "Example User", email: "user@example.com", created_at: nil, updated_at: nil, password_digest: "$2a$04$ZSegpX1GY1RIcqvDmM4FteBQ.HXzHM2pZtj0mwobetfs...">
        got: #<User id: 1, name: "Example User", email: "user@example.com", created_at: "2014-01-08 09:35:31", updated_at: "2014-01-08 09:35:31", password_digest: "$2a$04$qO1QSOwTEYtioSSmNObKKOgc5K3SQyU4dDk.APqN1egI...">

   (compared using ==)

   Diff:
   @@ -1,2 +1,2 @@
   -#<User id: nil, name: "Example User", email: "user@example.com", created_at: nil, updated_at: nil, password_digest: "$2a$04$ZSegpX1GY1RIcqvDmM4FteBQ.HXzHM2pZtj0mwobetfs...">
   +#<User id: 1, name: "Example User", email: "user@example.com", created_at: "2014-01-08 09:35:31", updated_at: "2014-01-08 09:35:31", password_digest: "$2a$04$qO1QSOwTEYtioSSmNObKKOgc5K3SQyU4dDk.APqN1egI...">

 # ./spec/models/user_spec.rb:82:in `block (4 levels) in <top (required)>'

Finished in 0.38035 seconds
29 examples, 1 failure

Failed examples:

rspec ./spec/models/user_spec.rb:82 # User return value of authenticate method with valid password 

Randomized with seed 23961

有时,在回滚,迁移和重置测试数据库之后,测试通过。有时它仍然失败。谢谢你的时间。

更新 - 这是我初始化@user:

的方法
before do
    @user = User.new(name: "Example User", email: "user@example.com", password: "foobar2", password_confirmation: "foobar2")
end
subject{user}

使用rake:reset似乎无法解决问题,测试有时仍会失败。

2 个答案:

答案 0 :(得分:0)

rake db:migrate:status shows?

我建议您完全删除数据库,然后尝试迁移。在我看来,在您的数据库中,已经存储的用户密码不会被完全删除,

rake db:reset

然后运行

rake db:migrate

答案 1 :(得分:0)

您应该尝试subject { @user }而不是subject { user }