Run all models tests using rake task - ruby-on-rails-3

Trying to use a rake task to run only tests in the test/models directory. Using minitest.
I have a rake task that will run all test
require "rake/testtask"
Rake::TestTask.new(:test => "db:test:prepare") do |t|
t.libs << "test"
t.pattern = "test/**/*_test.rb"
end
task :default => :test
Then, running 'rake' hits the default and runs all tests. I want to write a second rake task that would only run tests in the models directory (test/models/).
I played around with this existing TestTask by simply changing
t.pattern = "test/**/*_test.rb"
to
t.pattern = "test/models/*_test.rb"
but, it seems to still run all the tests...not just models. Strange?
QUESTIONS
How can I accomplish this? How to I need to name a second TestTask that will run only models, and how do I tell rake to run that test instead of the default :test?

The pattern you are looking for is "test/models/**/*_test.rb". The "**" will match subdirectories as well.
If you are using minitest-rails then you have lots of tasks added for you. To run all Model tests run:
rake minitest:models
To see all the rake tasks creates for you, run:
rake -T

As usual, the answer was quite simple. Just took a bit of digging around. Make sure you have the following in your application.rb (inside the module).
config.generators do |g|
g.fixture_replacement :factory_girl # if your using factory_girl
g.test_framework :mini_test, :spec => true, :fixture => false
end
Then you have access to minitests built in commands. The one I was looking for is as simple
rake minitest:models
Booya!

Related

Rails 3.2.11 performance testing issue: Don't know how to build task 'test:benchmark'

I'm following this railscast on performance testing, but I'm immediately running into an issue.
My app is rails 3.2.11, so according to the railscast it should include performance testing, but I don't have a folder called 'test' at all. When I run 'rails generate performance_test homepage' nothing happens or is generated. So I created one manually (to exactly match the railscast source code), but when I run rake test:benchmark I get the error
Don't know how to build task 'test:benchmark'
If I add the 'rails-perftest' gem to my gemfile and run bundle, then again try to generate a performance_test nothing happens, and when I then run rake test:benchmark, it throws a different error of
uninitialized constant Rails::SubTestTask
I've been sure to include the following dependencies in my gem file:
gem 'ruby-prof', group: :test
gem 'test-unit', group: :test
Could anyone help advise me what I'm doing wrong? Thanks!
I am not 100% certain on this, but I am guessing that you might not have your application.rb file configured accordingly. Also check your Gemfile.lock file and run the command bundle install because it could also be something funky going on with your Gems and dependencies.

Rake::TestTask not running minitest files

I'm using minitest for one of my projects, and I can't seem to get the Rake TestTask to actually run the files.
require 'rake'
require 'rake/testtask'
task :mytest do
Rake::TestTask.new do |t|
t.test_files = Dir.glob('test/model/*_test.rb')
t.verbose = true
puts t.inspect
puts '-------------------------------------'
end
end
when I run this task rake mytest, I get the following output :
projects#webdev-local:/home/projects/framework# rake mytest
#<Rake::TestTask:0x00000001775050 #name=:test, #libs=["lib"], #pattern=nil,
#options=nil, #test_files=["test/model/page_model_test.rb",
"test/model/widget_model_test.rb"], #verbose=true, #warning=false, #loader=:rake,
#ruby_opts=[]>
-------------------------------------
As you can see, The task finds the files, but it never actually runs them. How can I get it to run these files?
Using Rails 3.2.8 and ruby 1.9.3
So, two things you might want to check:
1) Make sure you're using the minitest-rails gem
It adds a lot of the test runner tasks we want and need.
https://github.com/blowmage/minitest-rails
2) The contents of your minitest_helper.rb file (a la spec_helper.rb)
You should have some kind of helper file that you're requiring in all your tests. Make sure it looks something like this:
ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require "minitest/autorun"
require "minitest/rails"
class ActiveSupport::TestCase
fixtures :all
end
Now that you have that setup, you can run all the tests as follows:
bundle exec rake test
bundle exec rake minitest # alias for test
bundle exec rake minitest:models
# ... etc ...

Why are there no rake tasks in this mongoid Rails 3 project?

https://github.com/memphis518/Garden-Dating-Service
The public repo above is a community coding project we're working on for Austin Community Gardens, and it's a fairly simple project so far, but for some reason rake db:seed doesn't work ("Don't know how to build task db:seed"), and when you run rake -T it reveals no rake tasks at all.
MongoID documentation says it provides most of the usual DB-related rake tasks - I can't figure out why they're not there.
I had the similar problem with Rails 3.X, although the mongoid Gem was included in my Gemfile. I could solve the problem by explicitly requiring the database.rake file from the mongoid gem. I added this 2 lines to my Rakefile:
spec = Gem::Specification.find_by_name 'mongoid'
load "#{spec.gem_dir}/lib/mongoid/railties/database.rake"
That works for me.
Had the exact same issue.
Realized I never added "mongoid" to my Gemfile. This fixes it:
gem 'mongoid'
It will add these rake tasks:
rake db:drop # Drops all the collections for the database for the current Rails.env
rake db:mongoid:create_indexes # Create the indexes defined on your mongoid models
rake db:mongoid:drop # Drops the database for the current Rails.env
rake db:mongoid:remove_indexes # Remove the indexes defined on your mongoid models without questions!
rake db:reseed # Delete data and seed
rake db:seed # Load the seed data from db/seeds.rb
rake db:setup # Create the database, and initialize with the seed data

rspec returns "PG::Error: ERROR: relation "table_name" does not exist"

Environment is REE(2011.12) on rvm, rspec 2.8.0, rails 3.0.6, and pg 0.13.2. Using PostgreSQL 8.3.17 on CentOS 5.6. The db:migrate have work correctly. But rspec have got following error.
1) ApiController articles OK
Failure/Error: Unable to find matching line from backtrace
ActiveRecord::StatementInvalid:
PG::Error: ERROR: relation "table_name" does not exist
: DELETE FROM "table_name"
I'm updating my project from rails 2.3.5 with rspec 1.x series to rails 3.0 with rspec2. Copied all rspec tests, and I have merged old spec_helper.rb and new one(It was generated rails g rspec:install).
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
end
I read similar question about this error.So I tried rake db:test:prepare or rake db:test:load, But It's not resolve. Do you have any idea?
It looks like the test hasn't run on test database... How do I do? :(
I've run into this in two instances (updated 6/13/2012):
First:
I haven't yet migrated my test database...
rake db:migrate
...which you need to do before both db:test:prepare and db:test:load.
When you invoke rspec it should prepare and load your database for you anyway. You shouldn't have to do that by hand.
Second:
A typo in my migration. I accidentally reversed my table and column names in the parameter list.
A migration on a Rails 3.1 project:
def change
add_column :had_import_errors, :studies, :boolean, :default => false
add_column :import_data_cache, :studies, :text
end
...which is wrong, because has_import_errors and import_data_cache are my column names, and they therefore should come second, not first.
The correct migration, with the table name first was:
def change
add_column :studies, :had_import_errors, :boolean, :default => false
add_column :studies, :import_data_cache, :text
end
This usually happens when you have rspec running while migrating (usually via guard). A simple solution is to quit guard, do the migration and restart guard.
It typically indicates that there is another open PostgreSql connection. To bubble up the right error try % rake db:test:prepare
Running test prepare showed the following below and when the open connection (PGAdmin in my case) was closed the issue was resolved.
rake aborted!
PG::Error: ERROR: database "xyz_test" is being accessed by other users
DETAIL: There are 1 other session(s) using the database.
: DROP DATABASE IF EXISTS "xyz_test"
Tasks: TOP => db:test:load => db:test:purge
(See full trace by running task with --trace)
Just hit this same error, nothing worked but dropping and re-creating the database, this fixed it for me.
rake db:drop db:create db:migrate

Set up RSpec to test a gem (not Rails)

It is pretty easy with the added generator of rspec-rails to set up RSpec for testing a Rails application. But how about adding RSpec for testing a gem in development?
I am not using jeweler or such tools. I just used Bundler (bundle gem my_gem) to setup the structure for the new gem and edit the *.gemspec manually.
I also added s.add_development_dependency "rspec", ">= 2.0.0" to gemspec and did a bundle install.
Is there some nice tutorial what to do next to get RSpec working?
I've updated this answer to match current best practices:
Bundler supports gem development perfectly. If you are creating a gem, the only thing you need to have in your Gemfile is the following:
source "https://rubygems.org"
gemspec
This tells Bundler to look inside your gemspec file for the dependencies when you run bundle install.
Next up, make sure that RSpec is a development dependency of your gem. Edit the gemspec so it reads:
spec.add_development_dependency "rspec"
Next, create spec/spec_helper.rb and add something like:
require 'bundler/setup'
Bundler.setup
require 'your_gem_name' # and any other gems you need
RSpec.configure do |config|
# some (optional) config here
end
The first two lines tell Bundler to load only the gems inside your gemspec. When you install your own gem on your own machine, this will force your specs to use your current code, not the version you have installed separately.
Create a spec, for example spec/foobar_spec.rb:
require 'spec_helper'
describe Foobar do
pending "write it"
end
Optional: add a .rspec file for default options and put it in your gem's root path:
--color
--format documentation
Finally: run the specs:
$ rspec spec/foobar_spec.rb
Iain's solution above works great!
If you also want a Rakefile, this is all you need:
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new(:spec)
# If you want to make this the default task
task default: :spec
Check the RDoc for RakeTask for various options that you can optionally pass into the task definition.
You can generate your new gem with rspec by running bundler gem --test=rspec my_gem. No additional Setup!
I always forget this. It's implemented here: https://github.com/bundler/bundler/blob/33d2f67d56fe8bf00b0189c26125d27527ef1516/lib/bundler/cli/gem.rb#L36
Here's a cheap and easy (though not officially recommended) way:
Make a dir in your gem's root called spec, put your specs in there. You probably already have rspec installed, but if you don't, just do a gem install rspec and forget Gemfiles and bundler.
Next, you'll make a spec, and you need to tell it where your app is, where your files are, and include the file you want to test (along with any dependencies it has):
# spec/awesome_gem/awesome.rb
APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))
$: << File.join(APP_ROOT, 'lib/awesome_gem') # so rspec knows where your file could be
require 'some_file_in_the_above_dir' # this loads the class you want to test
describe AwesomeGem::Awesome do
before do
#dog = AwesomeGem::Awesome.new(name: 'woofer!')
end
it 'should have a name' do
#dog.name.should eq 'woofer!'
end
context '#lick_things' do
it 'should return the dog\'s name in a string' do
#dog.lick_things.should include 'woofer!:'
end
end
end
Open up Terminal and run rspec:
~/awesome_gem $ rspec
..
Finished in 0.56 seconds
2 examples, 0 failures
If you want some .rspec options love, go make a .rspec file and put it in your gem's root path. Mine looks like this:
# .rspec
--format documentation --color --debug --fail-fast
Easy, fast, neat!
I like this because you don't have to add any dependencies to your project at all, and the whole thing remains very fast. bundle exec slows things down a little, which is what you'd have to do to make sure you're using the same version of rspec all the time. That 0.56 seconds it took to run two tests was 99% taken up by the time it took my computer to load up rspec. Running hundreds of specs should be extremely fast. The only issue you could run into that I'm aware of is if you change versions of rspec and the new version isn't backwards compatible with some function you used in your test, you might have to re-write some tests.
This is nice if you are doing one-off specs or have some good reason to NOT include rspec in your gemspec, however it's not very good for enabling sharing or enforcing compatibility.