Rails Fixtures with BCrypt

血红的双手。 提交于 2020-01-03 08:07:09

问题


I'm having a problem with fixtures for BCrypt password: my User model is both setup with has_secure_password and validates_presence_of :password.

The point is that BCrypt uses password and password_confirmation but in the schema there is only the password_digest field.

The fixture is complaining that the password field does not exists.

How can I avoid this?

Thank you


回答1:


Seems that fixtures are being pushed to the database directly. That means that instead of password: you need password_digest: in your fixtures:

test_user:
  email: "tester@testing.net"
  password_digest: <%= BCrypt::Password.create('testpassword', cost: 5) %>

when using bcrypt based passwords with has_secure_password. As mentioned in the comments cost argument is optional. If you don't use it a sensible default will be used.




回答2:


I solved this problem with setup function on model test. We can define objects in setup and use it through the test file.

def setup
    @user = User.new
    @user.name = 'Brunoid'
    @user.email = 'brunoid@localhost'
    @user.phone = '(01)2345-6789'
    @user.cpf = '123.456.789-10'
    @user.password = 'segamastersystem'
    @user.password_confirmation = 'segamastersystem'
    @user.card = Card.first
end

test 'must validate' do
    assert @user.valid?
end
...


来源:https://stackoverflow.com/questions/30894771/rails-fixtures-with-bcrypt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!