Best way to fill development db in rails - ruby-on-rails

I need to fill the test development database with data, for example from factorygirl, but I'd like to use it from rails console.
How I put example data in db so I can fetch it from console and do some test there?

Faker is also a good solution.
Here's how my lib/tasks/sample_data.rake looks like. I run it with rake db:populate.
Creates 50 entries with random info.
require 'faker'
namespace :db do
desc "Fill database with sample data"
task :populate => :environment do
Rake::Task['db:reset'].invoke
50.times do |n|
name = Faker::Company.name
year = 1900+rand(111)
rating = 1+rand(10)
watched = (1 == rand(2) ? true : false)
imdb_id = rand(1000000)
Movie.create!(:name => name,
:year => year,
:rating => rating,
:watched => watched,
:imdb_id => imdb_id)
end
end
end

I've made a gem test_dummy that works like Factory Girl to define lots of fake data. When properly configured you can do things like this:
# Create 100 fake companies
100.times { Company.create_dummy }
# Create a single fake company on-demand
fake_company = Company.create_dummy
The alternative is to use the db/seeds.rb facility or to load in your fixtures into your development environment.

Michael Hartl provides an excellent introduction to this topic as part of the railstutorial.org program.
He uses a gem called Factory Girl, which is designed to ease the process of populating a database with sample data.
E.G.
http://ruby.railstutorial.org/chapters/user-microposts#sec:sample_microposts
https://github.com/railstutorial/sample_app/blob/master/lib/tasks/sample_data.rake

Is it just in the Rails console or just 'from the console'?
I like to use a Thor or Rake task to do that. Instead of Factory Girl I use Machinist.
You may want to check this answer
Rails: Good Rspec2 example usage? (Also: Cucumber, Pickle, Capybara)

Related

Rails Rspec test with carrierwave image

I wrote an API which can return latest 5 Newsletter and its image, but I am stuck at writing its rspec test.
First of all, here is the relationship between model.
Newsletter has_many NewsletterImages
NewsletterImage belong_to Newsletter
Secondly, I thought that I need to create some data in test database, so I wrote following code in rspec file.
7.times do |i|
n = Newsletter.create(title: "Test#{i}", content: "TestContents#{i}")
2.times do |i|
ni = NewsletterImage.create(newsletter_id: n.id, order: i)
ni.image = File.open('xxx.png')
ni.save
end
end
So, I need to upload file in very test? Is there a better way to generate data and test?
Better to use Factory Girl to make your test data. That way, you can write clean tests like
# /spec/factories/newsletter_factory.rb
FactoryGirl.define do
factory :newsletter do
title "My newsletter"
content "Some content"
end
end
# /spec/factories/newsletter_image_factory.rb
FactoryGirl.define do
factory :newsletter_image do
newsletter
image fixture_file_upload( Rails.root + 'spec/fixtures/images/example.jpg', "image/jpg")
end
end
# spec/models/newsletter_spec.rb
image = create :newsletter_image
expect(image.newsletter.title).to eq 'My Newsletter'
With all of the details of how the models are created hidden in the factory definition files, it's then easy to share the code across many tests.
For more detail about adding carrierwave files to Factory Girl definitions, look for other answers such as this one: https://stackoverflow.com/a/9952914/693349

How can I test my SQLite database via script in a Rails console?

On the Rails console my Class User looks like this:
irb(main):005:0> User
=> User(id: integer, name: string, created_at: datetime, updated_at: datetime)
I can generate an instance of User using
irb(main):006:0> User.create(:name => "user0")
What I want to do is test my database by creating a number X of instances of User. I thought about writing a Ruby script in which I cycle through a loop - something like (not real Ruby code!)
for i in 1..X do
User.create(:name => "name"+i)
end
But I don't know how to access my Class in Ruby and how to "tell" the console to generate actual objects.
Thanks for an answer!
You have a few options here. The best option is to learn how to write unit tests, either using Rails's default Test::Unit, or RSpec, or some other alternative. This is the right way, and in fact Rails comes all wired up with tests by default. You've got a test directory, and rake test and other testing tasks. If you use Rails generators (rails g model Foo), it'll even create the test files for you. You just need to fill them out.
If you're not ready to learn the testing frameworks, then you can put your code above into a file (let's call it test_user.rb) and run it through rails runner. That will bootstrap the Rails environment before executing your code, and you'll have access to the model:
rails runner test_user.rb
It seems like you're trying to create some seed data for your database. Why not run your code in Rails console directly? Or you could create a Rake task, and run the seeding from there.
I would also recommend using Faker, this will give you some real-looking data:
require 'faker'
for i in 1..X do
u = User.new
u.first_name = Faker::Name.first_name
u.last_name = Faker::Name.last_name
u.email = Faker::Internet.email
u.notes = Faker::Lorem.paragraph
u.cell_phone = Faker::PhoneNumber.cell_phone
u.home_phone = Faker::PhoneNumber.phone_number
u.save
end

Generating Paperclip image uploads with fake data - Ruby on Rails Populator / Faker Gems

I am currently trying to populate a development database on a project with a bunch of fake data, to simulate how it will look and operate with hundreds of articles / users. I looked into different gems to do the task - such as Factory Girl, but documentation was very lacking and I didn't get it - but ended up using the Populator and Faker gems and did the following rake task...
namespace :db do
desc "Testing populator"
task :populate => :environment do
require "populator"
require "faker"
User.populate 3 do |user|
name = Faker::Internet.user_name
user.name = name
user.cached_slug = name
user.email = Faker::Internet.email
user.created_at = 4.years.ago..Time.now
end
end
end
Works great...for text based data. However, all users have an avatar that can be uploaded via Paperclip attachment, as well as all regular content have thumbnail attachments in the same manner.
I understand the Populator gem simply does a straight population to the database and not necessarily running through ActiveRecord validations to do so..therefor I would assume Paperclip can't run to generate all the different thumbnails and needed (and uploaded to the proper directory) for the avatar if I just filled the field with a filepath in the rake task above.
Is there a way to populate fake images, via Populator or another way? Or perhaps a way to point the rake task at a directory of stock images on my hard drive to autogenerate random thumbnails for each record? Took a hunt on Google for a way, but have not turned up much information on the subject.
UPDATE
The final solution, based on pwnfactory's line of thinking...
namespace :db do
desc "Testing populator"
task :populate => :environment do
require "populator"
require "faker"
User.populate 3 do |user|
name = Faker::Internet.user_name
user.name = name
user.cached_slug = name
user.email = Faker::Internet.email
user.created_at = 4.years.ago..Time.now
end
User.all.each { |user| user.avatar = File.open(Dir.glob(File.join(Rails.root, 'sampleimages', '*')).sample); user.save! }
end
end
It basically loops back around and uploaded avatars from the sampleimages directory on all the records.
To associate a random image in your task, you could try the following:
user.avatar = File.open(Dir.glob(File.join(Rails.root, 'sampleimages', '*')).sample)
where sampleimages is a directory containing avatars to be associated at random
user.avatar = File.open(Dir['app/assets/images/*.jpg'].sample)
One way I get around this is to put a conditional in my views.
Let's say your model is "user", and it has an avatar. Then you can do the following:
<% if product.avatar.exists? %>
... show the attached photo
<% else %>
.. show a default photo
<% end %>
This works for me with Paperclip, and I use it in my dev database all the time rather than worrying about having all the image attached to all the users.

How to populate lookup tables in Rails tests

I am using Cucumber, RSpec, and Factory Girl for the testing of my Rails application. But I have several lookup tables that contain mostly static data. So I'm trying to figure out the best way to populate these when testing. Doing them individually in FactoryGirl seems tedious and I'd like to stay away from fixtures. For development and production, I populate them in my seeds.rb file.
Thanks!
Use Factory Girl .sequence, Populator and Faker and you'll never run out of lab rats!
Factory.define(:model) do |m|
m.sequence(:title) { |n| "model-#{n}" }
m.author Faker::Name.name
m.short Populator.words(5)
m.long Populator.paragraphs(1..3)
end
Then maybe in a before :each block
#models = []
15.times { #models << Factory.create(:model) }
Or you can use only Populator to fill your database before tests.
Maybe something like
rake RAILS_ENV=test db:seed
in your test helper file?

Getting started with the Friendly ORM

I'm following this tutorial: http://friendlyorm.com/
I'm using InstantRails to run MySQL locally. To run Ruby and Rails, I'm using normal Windows installations.
When I run Friendly.create_tables! I only get an empty Array returned: => [] and no tables are created in my 'friendly_development' database.
Author of Friendly here.
You'll have to require all of your models before calling Friendly.create_tables! Otherwise, there's no way for Friendly to know which models exist. In a future revision, I'll automatically preload all your models.
I have a rake task, with help from a guy called Sutto, that will load in all your models and then call Friendly.create_tables! and print out all the tables involved.
namespace :friends do
desc "load in all the models and create the tables"
task :create => :environment do
puts "-----------------------------------------------"
Dir[Rails.root.join("app", "models", "*.rb")].each { |f|File.basename(f, ".rb").classify.constantize }
tables = Friendly.create_tables!
tables.each do |table|
puts "Table '#{table}'"
end
puts "-----------------------------------------------"
end
end
rake friends:create
not much to go on here. My guess is that it can't find your model file that you are creating in the path?

Resources