Rails 自动生成密码测试

Rails test for auto-generating password

我的应用程序允许教师为他们的学生开设帐户。为了避免让老师为学生想密码的负担,我编写了一个自动生成密码的方法。该功能在开发和生产中正常工作。我正在尝试编写测试以确保此功能继续工作,但结果不是我所期望的。

我的直觉是我的错误在测试中:

students_controller_test.rb

test "Auto Password" do
    post students_path, params: { student: { first_name:  "Ren",
                                         last_name: "Stimpy",
                                        studentNum: 13},
                                 aula: { seminar_id: @seminar.id } }
    student = assigns(:student)
    assert_equal "rs13", student.username
    assert_equal Student.digest('rs13'), student.password_digest
end

结果:

 FAIL["test_Auto_Password", StudentsControllerTest, 2.0619301088154316]
 test_Auto_Password#StudentsControllerTest (2.06s)
        --- expected
        +++ actual
        @@ -1,2 +1 @@
        -# encoding: ASCII-8BIT
        -"aFfqltU9B7yawIs7Z4GWLe9eaaVhFxdPvF9Vg2UWUbYxwqQ5j/9Dm"
        +"a$CuN1BLKhI/Fx9ueB4QAskOl9Ik.og26TJeeDDF5tdur1erILzjj7W"
        test/controllers/students_controller_test.rb:91:in `block in <class:StudentsControllerTest>'

我可能对密码消化的工作方式有一些误解。学生的密码应该是"rs13"。所以我预计 Student.digest('rs13') 应该等于 student.password_digest。显然,他们不是。

顺便说一句,密码 "rs13" 来自我 students_controller 中的一个方法,该方法通过连接学生的姓名首字母和学号自动创建用户名。密码也等于这个

提前感谢您的任何见解!

问题是 BCrypt::Password will generate the digest with different salt,所以创建密码和检查的盐不同,这就是你的测试失败的原因。

检查this,然后可以使用运算符==检查潜在凭证是否正确:

assert_equal 'rs13', student.password_digest

assert_equal实际上是用运算符==compare

后来我意识到 "authenticate" 方法是实现我所尝试的目标的最佳方法。只需将测试的最后一行替换为:

assert student.authenticate("rs13")