From 9e849de0f7c2778a3256a77e6cf2e84a47524824 Mon Sep 17 00:00:00 2001 From: Andrey Chernih Date: Mon, 7 Jul 2014 12:15:28 +0400 Subject: [PATCH] Add task to generate test data --- Gemfile | 1 + Gemfile.lock | 3 +++ lib/tasks/fake_data.rake | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 lib/tasks/fake_data.rake diff --git a/Gemfile b/Gemfile index d90afe8..6f41a63 100644 --- a/Gemfile +++ b/Gemfile @@ -42,4 +42,5 @@ group :test, :development do gem "rspec-rails", "~> 2.6" gem "machinist" gem "sqlite3" + gem "faker" end diff --git a/Gemfile.lock b/Gemfile.lock index 461db86..2925601 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -34,6 +34,8 @@ GEM exception_notification (2.6.1) actionmailer (>= 3.0.4) execjs (2.0.2) + faker (1.4.1) + i18n (~> 0.5) hike (1.2.3) htmlentities (4.3.1) i18n (0.6.9) @@ -126,6 +128,7 @@ DEPENDENCIES bcrypt-ruby (~> 3.1.2) dynamic_form exception_notification (= 2.6.1) + faker htmlentities jquery-rails machinist diff --git a/lib/tasks/fake_data.rake b/lib/tasks/fake_data.rake new file mode 100644 index 0000000..1f6ccff --- /dev/null +++ b/lib/tasks/fake_data.rake @@ -0,0 +1,39 @@ +class FakeDataGenerator + def initialize(users_count, stories_count) + @users_count = users_count + @stories_count = stories_count + end + + def generate + users = 0.upto(@users_count).map do |i| + name = Faker::Name.name + password = Faker::Internet.password + user_name = Faker::Internet.user_name(name, %w(_)) + User.create! email: Faker::Internet.email(name), + password: password, + password_confirmation: password, + username: user_name + end + + @stories_count.times do + user = users[Random.rand(users.length-1)] + title = Faker::Lorem.sentence(3) + tag = Tag.find_or_create_by! tag: title.split(' ').first.downcase + Story.create! user: user, title: title, url: Faker::Internet.url, tags_a: [tag.tag] + end + end +end + +desc 'Generates fake data for testing purposes' +task fake_data: :environment do + fail "It's not intended to be run outside development environment" unless Rails.env.development? + unless (User.count + Tag.count + Story.count) == 0 + fail "Please ensure that you're running it on clean database because it will destroy all data" + end + + User.destroy_all + Tag.destroy_all + Story.destroy_all + + FakeDataGenerator.new(10, 1_000).generate +end