Rails 3: Generate Fake Data to Populate DB - ruby-on-rails

I am using faker to generate sample data. I have this as follows:
require 'faker'
namespace :db do
desc "Fill database with sample data"
task :populate => :environment do
Rake::Task['db:reset'].invoke
User.create!(:name => "rails",
:email => "example#railstutorial.org",
:password => "foobar",
:password_confirmation => "foobar")
99.times do |n|
#name = Faker::Name.name
name = "rails#{n+1}"
email = "example-#{n+1}#railstutorial.org"
password = "password"
user = User.create!(:name => name,
:email => email,
:password => password,
:password_confirmation => password)
end
end
end
The problem is that I have a couple of after_save callbacks that are not being called when the User is created. Why is that? Thanks
The methods:
after_save :create_profile
def create_profile
self.build_profile()
end

In all my reading, it seems that save! bypasses any custom before_save, on_save or after_save filters you have defined. The source code for create! reveals that it invokes save!. Unless you absolutely NEED the bang version, why are you using it? Try removing all your bang methods and just invoking the non-bang versions:
[1..100].each do |n|
name = "rails#{n+1}"
email = "example-#{n+1}#railstutorial.org"
password = "password"
user = User.new(:name => name, :email => email, :password => password, :password_confirmation => password)
if !user.save
puts "There was an error while making #{user.inspect}"
end
end

Related

Encrypt User's password in seed file

I need to seed an user with encrypted password and I'm not using Devise. So I tried this :
user = UserManager::User.new({ :name => 'a', :surname => 'a', :email => 'a', :active => true, :password_hash => 'password', :password_salt => 'password'})
user.save
But this is not right to put password_hash and password_salt like this and I found that I have to put password and password_confirmation instead
user = UserManager::User.new({ :name => 'a', :surname => 'a', :email => 'a', :active => true, :password => 'password', :password_confirmation => 'password'})
user.save
But these 2 fields are unknow because they are not in the database, so how can I do to encrypt the password with seed ?
EDIT
User model
attr_accessor :password
has_secure_password
before_save :encrypt_password
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
You don't need the attribute accessor for password. You get that for free when you use has_secure_password.
To seed users, I would recommend using Hartl's approach from his tutorial.
User model
Add a method for generating the password digest manually:
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
Seed file
User.create!(name: 'foo',
email: 'foo#bar.com',
password_digest: #{User.digest('foobar')} )
In your model:
class User < ApplicationRecord
has_secure_password
end
In the seeds.rb file:
User.create(username: "username",
...
password_digest: BCrypt::Password.create('Your_Password'))
You can create a hash of password something like following:
require 'digest/sha1'
encrypted_password= Digest::SHA1.hexdigest(password)
You can use this code in your seeds.rb file to encrypt the password. But it seems that you have already written a method encrypt_password. Now, you can call this method in before_save callback. So each time, a user is about to be saved in database, encrypt_password will be called.

can't populate db using rake db:populate

I am trying to populate my db using rake db:populate. I am on chapter 10.3.2 on michael hartl's book.
Even though I don't get any error messages the DB doesn't seem to be populating.
This is the sample_data.rake file I created:
namespace :db do desc "Fill database with sample data" task populate: :environment do
User.create!(:name => "Example User",
:email => "example#railstutorial.org",
:password => "foobar",
:password_confirmation => "foobar")
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}#railstutorial.org"
password = "password"
User.create!(:name => name,
:email => email,
:password => password,
:password_confirmation => password)
end
end
end
Stopping your server before resetting and repopulating your db should work.

How to login with declarative_authorization in my rspec tests without going through the interface

At present, the following works when I call it from my Rspec tests:
def login_as(role)
#role = Role.create! :name => role
#virginia = User.create!(
:username => "Virginia",
:password => "password",
:password_confirmation => "password",
:email => "example#example.com")
#assignment = Assignment.create! user_id: #virginia.id, role_id: #role.id
visit login_path
fill_in "user_session_username", :with => #virginia.username
fill_in "user_session_password", :with => #virginia.password
click_on "submit_user_session"
end
Given that I've tested the interface already, I thought it might speed things up to not hit the interface hundreds of times just because many of my examples only make sense when a user has a role and is logged in. So, I tried this:
def login_as(role)
#role = Role.create! :name => role
#virginia = User.create!(
:username => "Virginia",
:password => "password",
:password_confirmation => "password",
:email => "example#example.com")
#assignment = Assignment.create! user_id: #virginia.id, role_id: #role.id
#user_session = UserSession.create! :username => #virginia.username, :password => #virginia.password
end
However, that version is not logging me in. Any thoughts?
To be clear, I'm not asking how to test declarative_authorization. I'm asking how to quickly login when I'm testing something else. For example, I use login_as(role) to test product#delete (an action only accessible to admins) like this:
login_as "admin"
visit product_path(#search)
click_link "delete_product"
page.current_path.should == products_path
page.should_not have_content "Retail Site Search"

Unable to create user model in Rspec

When I run the following spec:
require 'spec_helper'
describe User do
before :each do
#user = User.new :email => "foo#bar.com", :password => "foobar", :password_confirmation => "foobar"
end
it "should be valid" do
#user.should be_valid
end
end
I get this error:
1) User should be valid
Failure/Error: #user = User.new :email => "foo#bar.com", :password => "foobar", :password_confirmation => "foobar"
ActiveRecord::UnknownAttributeError:
unknown attribute: email
# ./spec/models/user_spec.rb:5:in `new'
However, when I go in to console and run
user = User.new :email => "foo#bar.com", :password => "foobar", :password_confirmation => "foobar"
user.valid?
It returns true. For some reason, in my test, I am unable to create a User instance, saying that the email attribute is inaccessible.
Console uses the development database, but specs use the test database. Make sure email is defined in both.

Railstutorial: db:populate vs. factory girl

In the railstutorial, why does the author choose to use this (Listing 10.25):
http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users
namespace :db do
desc "Fill database with sample data"
task :populate => :environment do
Rake::Task['db:reset'].invoke
User.create!(:name => "Example User",
:email => "example#railstutorial.org",
:password => "foobar",
:password_confirmation => "foobar")
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}#railstutorial.org"
password = "password"
User.create!(:name => name,
:email => email,
:password => password,
:password_confirmation => password)
end
end
end
to populate the database with fake users, and also (Listing 7.16)
http://ruby.railstutorial.org/chapters/modeling-and-viewing-users-two
Factory.define :user do |user|
user.name "Michael Hartl"
user.email "mhartl#example.com"
user.password "foobar"
user.password_confirmation "foobar"
end
It appears that both ways creates users in the database right (does factory girl create users in the database)? What is the reason for the two different ways of creating test users, and how are they different? When is one method more suitable than the other?
Faker and Factory Girl are being used in those examples for two different purposes.
A rake task is created using Faker to easily let you populate a database, typically the development database. This lets you browse around your app with lots of populated, fake data.
The factory definition makes tests convenient to write. For example, in your RSpec tests you can write:
before(:each) do
#user = Factory(:user)
end
Then #user is available in the tests that follow. It will write these changes to the test database, but remember that these are cleared each time you run tests.

Resources