How to create fixtures (for a Devise user) as a yml.erb in rails (4.1.5)?

Since all of these answers were fairly confusing or out of date, the newest answer is that you need to use Devise::Encryptor.digest to create the encrypted_password.

Example:

# ../fixtures/users.yml.erb
user1:
  email: [email protected]
  name: user1
  encrypted_password: <%= Devise::Encryptor.digest(User, 'password') %>
  admin: true

user2:
  email: [email protected]
  name: user2
  encrypted_password: <%= Devise::Encryptor.digest(User, 'password') %>
  admin: false

Hope that helps!


<% 100.times do |n| %>
user_<%= n %>:
  email: <%= "user#{n}@example.com" %>
  encrypted_password: <%= Devise.bcrypt(User, 'password') %>
<% end %>

It's an alternative way to do the same thing, you don't have to new an instance.

# lib/devise/models/database_authenticatable.rb:147
def password_digest(password)
  Devise.bcrypt(self.class, password)
end

edit:

Thank @sixty4bit for pointing out deprecated usage, the updated answer would be:

<% 100.times do |n| %>
user_<%= n %>:
  email: <%= "user#{n}@example.com" %>
  encrypted_password: <%= Devise::Encryptor.digest(User, 'password') %>
<% end %>

You should pass the password in plain text too. I am sure there is a User model validation errors preventing your fixture users from being created. Here's an example from my users fixture which works:

tom:
  first_name: Tom
  last_name: Test
  email: [email protected]
  password: 123greetings
  encrypted_password: <%= User.new.send(:password_digest, '123greetings') %>

If it still fails, please check the log/test.log file for errors and check for missing required fields or other validation rules you set in your User model.

Update: It turns out that author found the issue himself - used .yml.erb file extension rather than .yml which made rails bypass that fixtures file. ERB works in yml fixtures as rails runs the fixture file through ERB before parsing it.