Ruby on Rails - run unit tests in subfolder - ruby-on-rails

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

Related

How to use rake with rake tasks outside rails?

I think Rails is very heavy and I'm taking pieces out of my projects and making them standalone. My library of tasks, I would like it to work outside Rails. So there is no application and no config/application.rb, only the lib/ folder that defines tasks. How should I structure my rakefile to include all the tasks defined in lib/tasks/*rake? My non-working attempt is below.
#!/usr/bin/env/rake
d = Dir["#{File.dirname(__FILE__)}/src/tasks/*.rake" ]
d.each do |file|
require "tasks/"+ File.basename(file, File.extname(file))
end
The invocation is something like bundle exec rake -T -Isrc
Put this in your rake file
Dir["#{File.dirname(__FILE__)}/src/tasks/*.rake" ].each{ |rake_file| load rake_file }

rake:test not running custom tests in subdirectory

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

"rake spec" migrates the database every time

When I run any of the rspec tasks via rake, the database seems to be dropped and migrated, but if I run them via script/spec path/to/spec, it doesn't. Is there an option I can set so the rake spec doesn't touch the database?
It shouldn't be running any migrations, only importing db/schema.rb into your test database. This is the expected behavior so your tests use a fresh copy of the database schema before they run. What is your reasoning for not wanting it to refresh the test database?
For what I do I want it off permanently. So with rspec 2.5.0 and rails 3:
Copy rspec.rake to your apps /lib/tasks folder from:
~/.rvm/gems/ruby-1.8.7-p302/gems/rspec-rails-2.5.0/lib/rspec/rails/tasks/rspec.rake
Add this to the top of the file:
Rake::TaskManager.class_eval do
def remove_task(task_name)
#tasks.delete(task_name.to_s)
end
end
def remove_task(task_name)
Rake.application.remove_task(task_name)
end
remove_task 'spec'
Find and edit this line to force a noop:
spec_prereq = :noop #Rails.configuration.generators.options[:rails][:orm] == :active_record ? "db:test:prepare" : :noop
I had this same problem also when running rspec from the command line. In my cases I was working with an legacy database that had no migrations, so the tests would fail because migrations could not be run.
The solution was to edit the spec/spec_helper.rb file and delete the following line:
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)
After that the tests ran without failing.

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