rake:test not running custom tests in subdirectory - ruby-on-rails

I'm using Rails 4.0.0.beta1. I added two directories: app/services and test/services.
I also added this code, based on reading testing.rake of railties:
namespace :test do
Rake::TestTask.new(services: "test:prepare") do |t|
t.libs << "test"
t.pattern = 'test/services/**/*_test.rb'
end
end
I have found that rake test:services runs the tests in test/services; however, rake test does not run those tests. It looks like it should; here is the code:
Rake::TestTask.new(:all) do |t|
t.libs << "test"
t.pattern = "test/**/*_test.rb"
end
Did I overlook something?

Add a line like this after your test task definition:
Rake::Task[:test].enhance { Rake::Task["test:services"].invoke }
I don't know why they're not automatically getting picked up, but this is the only solution I've found that works for Test::Unit.
I think if you were to run rake test:all it would run your additional tests, but rake test alone won't without the snippet above.

For those using a more recent Rails version (4.1.0 in my case)
Use Rails::TestTask instead of Rake::TestTask and override run task:
namespace :test do
task :run => ['test:units', 'test:functionals', 'test:generators', 'test:integration', 'test:services']
Rails::TestTask.new(services: "test:prepare") do |t|
t.pattern = 'test/services/**/*_test.rb'
end
end

Jim's solution works, however it ends up running the extra test suite as a separate task and not as part of the whole (at least using Rails 4.1 it does). So test stats are run twice rather than aggregated. I don't feel this is the desired behaviour here.
This is how I ended up solving this (using Rails 4.1.1)
# Add additional test suite definitions to the default test task here
namespace :test do
Rails::TestTask.new(extras: "test:prepare") do |t|
t.pattern = 'test/extras/**/*_test.rb'
end
end
Rake::Task[:test].enhance ['test:extras']
This results in exactly expected behaviour by simply including the new test:extras task in the set of tasks executed by rake test and of course the default rake. You can use this approach to add any number of new test suites this way.
If you are using Rails 3 I believe just changing to Rake::TestTask will work for you.

Or simply run rake test:all
If you want to run all tests by default, override test task:
namespace :test do
task run: ['test:all']
end

Related

rake task not running sub-tasks in order specified

In a rails 4.2 app, in Rakefile, I have this:
task(:default).clear
task :default => [:test, 'bundle:audit']
The output, always has bundle:audit running first. Why is that?
I read in some places that rake executes tasks as dependencies arise, but bundle:audit, as far as I can tell, does not depend on test. It is defined here:
https://github.com/rubysec/bundler-audit/blob/master/lib/bundler/audit/task.rb
To quote a comment discussing the same problem in Rake's GitHub repository:
It turns out that your problem is due to the way rails creates its test tasks:
desc "Run tests quickly by merging all types and not resetting db"
Rails::TestTask.new(:all) do |t|
t.pattern = "test/**/*_test.rb"
end
https://github.com/rails/rails/blob/v4.2.7.1/railties/lib/rails/test_unit/testing.rake#L24-L27
Here Rails uses Rails::TestTask for the test:all target which will load all test files.
def define
task #name do
if ENV['TESTOPTS']
ARGV.replace Shellwords.split ENV['TESTOPTS']
end
libs = #libs - $LOAD_PATH
$LOAD_PATH.unshift(*libs)
file_list.each { |fl|
FileList[fl].to_a.each { |f| require File.expand_path f }
}
end
end
https://github.com/rails/rails/blob/v4.2.7.1/railties/lib/rails/test_unit/sub_test_task.rb#L106-L118
But unlike Rake::TestTask, which immediately runs the tests, Rails::TestTask only requires the files necessary to run the tests then relies on the at_exit handler in Minitest to run the tests. This means rake dependencies are completely ignored for running tests.
I updated the links to the source code, because the discussion was about Rails 4.1.8, but the problem still exists the source code of Rails 4.2.7.1.
This problem was reported as an issue to the Rails team on GitHub and it was fixed in this PR.
That said: This problem should be fixed since Rails 5.0.0.

enhancing the global environment task rails

On the application I am upgrading from Rails 3.2.22.4 to Rails 4.0.13, the following block of code for enhancing the global environment task has become a road-block by not working on the target Rails version:
Rails.application.class.rake_tasks do
Rake::Task["environment"].enhance do
...
end
end
This works fine on 3.2, but fails with Don't know how to build task 'environment' error message in 4.0.
In 3.2, Rails.application.class.rake_tasks returns a Proc object ( [#<Proc:0x007f978602a470#.../lib/rails/application.rb:301>] ) pointing to this line in the rails codebase. On 4.0, it returns an empty array.
The line referred to in the above Proc object seems to be removed in this commit.
What would the preferred way to enhance the environment rake task be in Rails 4.x?
The above piece of code is in the lib/subdomain/rake.rb file, and it is include with the following code in lib/subdomain/engine.rb:
module Subdomain
class Engine < Rails::Engine
...
rake_tasks do |_app|
require 'subdomain/rake'
end
...
end
end
Rake tasks can't be executed as the command fails with this error. rails server|console commands work ok.
Option 1
If I'm understanding the question properly, something like this should work by placing these tasks in a standard location like lib/tasks/environment.rake. Note: None of this is particularly Rails-specific.
# Re-opening the task gives the ability to extend the task
task :environment do
puts "One way to prepend behavior on the :environment rake task..."
end
task custom: :environment do
puts "This is a custom task that depends on :environment..."
end
task :environment_extension do
puts "This is another way to prepend behavior on the :environment rake task..."
end
# You can "enhance" the rake task directly too
Rake::Task[:environment].enhance [:environment_extension]
The output of this would be:
$ rake custom
This is another way to prepend behavior on the :environment rake task...
One way to prepend behavior on the :environment rake task...
This is a custom task that depends on :environment...
Option 2
However, the question remains as to why :environment needed to be extended. If it's to trigger something before, say, a db:migrate, you might be better off just re-opening the task in question and adding another dependency to that particular task. For example:
task custom: :environment do
puts "This is a custom task that depends on :environment..."
end
task :custom_extension do
puts "This is a new dependency..."
end
# Re-opening the task in question allows you to added dependencies
task custom: :custom_extension
The result of this is:
$ rake custom
This is a new dependency on :custom
This is a custom task that depends on :environment...
C-C-C-Combo Breaker!!
Combining everything, the output would look like this:
$ rake custom
This is another way to prepend behavior on the :environment rake task...
One way to prepend behavior on the :environment rake task...
This is a new dependency on :custom
This is a custom task that depends on :environment...

Ruby on Rails - run unit tests in subfolder

Is it possible to run tests only from one subfolder?
Something like this:
ruby -I"lib:test" test/functional/api/*
Thanks
I assume you're trying to find a way to run multiple unit tests in a specific directory and you're not using RSpec...
In that case, you can create a task in a Rakefile and run it from command line. This page Rake::TestTask will tell you how to create such a file. You're file is going to look something like this:
Rake::TestTask.new do |t|
t.libs << "test"
t.test_files = FileList['test/functional/api/*.rb']
t.verbose = true
end
And then run:
rake test
If you use rspec you can do this
rspec ./spec/models/
for a folder
and this
rspec ./spec/models/car_spec.rb
for one file
and this
rspec ./spec/models/car_spec.rb:34
for the test on line 34

Rails: How to test code in the lib/ directory?

I have a model which gets its data from a parser object. I'm thinking that the parser class should live in the lib/ directory (although I could be persuaded that it should live soewhere else). The question is: Where should my unit tests for the parser class be? And how do I ensure that they are run each time I run rake test?
In the Rails application I'm working on, I decided to just place the tests in the test\unit directory. I will also nest them by module/directory as well, for example:
lib/a.rb => test/unit/a_test.rb
lib/b/c.rb => test/unit/b/c_test.rb
For me, this was the path of last resistance, as these tests ran without having to make any other changes.
Here's one way:
Create lib/tasks/test_lib_dir.rake with the following
namespace :test do
desc "Test lib source"
Rake::TestTask.new(:lib) do |t|
t.libs << "test"
t.pattern = 'test/lib/**/*_test.rb'
t.verbose = true
end
end
Mimic the structure of your lib dir under the test dir, replacing lib code with corresponding tests.
Run rake test:lib to run your lib tests.
If you want all tests to run when you invoke rake test, you could add the following to your new rake file.
lib_task = Rake::Task["test:lib"]
test_task = Rake::Task[:test]
test_task.enhance { lib_task.invoke }
I was looking to do the same thing but with rspec & autospec and it took a little digging to figure out just where they were getting the list of directories / file patterns that dictated which test files to run. Ultimately I found this in lib/tasks/rspec.rake:86
[:models, :controllers, :views, :helpers, :lib, :integration].each do |sub|
desc "Run the code examples in spec/#{sub}"
Spec::Rake::SpecTask.new(sub => spec_prereq) do |t|
t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
t.spec_files = FileList["spec/#{sub}/**/*_spec.rb"]
end
end
I had placed my tests in a new spec/libs directory when the rpsec.rake file was configured to look in spec/lib. Simply renaming libs -> lib did the trick!
An easy and clean way is just to create a directory under test/unit/lib. Then create test as test/unit/lib/foo_test.rb corresponding to lib/foo.rb. No new rake tasks required, and you can nest more directories if needed to match the lib directory structure.
As of Rails 4.0:
rake test:all # Run all tests in any subdir of `test` without resetting the DB
rake test:all:db # Same as above and resets the DB
As of Rails 4.1, redefine test:run to include additional tasks when running rake or rake test:
# lib/tasks/test.rake
namespace :test do
Rake::Task["run"].clear
task run: ["test:units", "test:functionals", "test:generators", "test:integration", "test:tasks"]
["tasks"].each do |name|
Rails::TestTask.new(name => "test:prepare") do |t|
t.pattern = "test/#{name}/**/*_test.rb"
end
end
end
This has the added bonus of defining rake test:tasks in the given example.
As of Rails 4.2, test:run includes all subdirs of test including them when running rake test, and thus rake.
To not define additional rake tasks to run tests from the custom defined folders you may also run them with the command rake test:all. Tests folders structure for the lib folder or any other custom folder is up to you. But I prefer to duplicate them in classes: lib is matched to test/lib, app/form_objects to test/form_objects.
Use:
[spring] rake test:all
to run all tests, including the directories you created (like [root]/test/lib/).
Omit [spring] if tou aren't using it.

How do I run Rails integration tests without dropping DB contents?

I've written some integration tests that I'd like to run against a copy of my prod database before I push to production. This lets me test all of my routes are still correct, all of the pages render without errors and some of the multipage workflows work as expected.
When I run the integration tests it drops the database I've loaded and loads the test fixtures (as expected). How can I change this behaviour and keep the copy of my production DB I've loaded?
Integration tests calls db:test:prepare which calls db:test:clone_structure which calls db:structure:dump and db:test:purge
You can write your own task
namespace :your_namespace do
Rake::TestTask.new(:integration => "db:migrate(if you want") do |t|
t.libs << "test"
t.pattern = 'test/integration/**/*_test.rb'
t.verbose = true
end
end
To get this to work I had to specifiy the environment when calling the rake task, otherwise it would run the migrations on the development db and then run the tests on the test db; given the example from above
namespace :dbtest do
Rake::TestTask.new(:integration => "db:migrate") do |t|
...
I had to execute the tests like so
rake environment RAILS_ENV=test dbtest:integration
Setting self.use_transactional_fixtures = true in your integration tests would be useful as well if you don't want to have to reload the production copy between each execution of the test.
Otherwise, the integration test run will splat the data with whatever changes it makes.
I needed to add aivarsak's Rake task
namespace :dbtest do
Rake::TestTask.new(:integration) do |t|
t.libs << "test"
t.pattern = 'test/integration/**/*_test.rb'
t.verbose = true
end
end
and also remove the
fixtures :all
line from the test/test_helper.rb file (or create a new one you reference in your integration test files)

Resources