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.
Related
A developer had authority to drop a DB but not re-create it. While working on a rake tasks, he accidentally ran the entire rake suite, which included destroying the development DB but without the proper authority to re-create and populate it.
How can I ensure this doesn't happen again? Is there someway in the Rails app to override running rake so that it does NOT execute a bunch of unspecified tasks?
The developer was looking for a list of tasks and figured that running rake would provide that listing, similarly to how running rails by itself puts out instructions.
I know there's a binstub for rake, but I really do not know what happens if I mess with things in there.
Are there any good solutions to a situation like this?
Set the default task? IIRC, outside of a namespace block:
task :default => "something_that_doesnt_destroy_the_world"
Taking a note from Dave's answer and another SO question (couldn't find link again), here is how you can override the default rake tasks in Rails 4.
# lib/tasks/default.rake (name is not important)
namespace :override do
task :default do
puts "This is now the default rake task executed via 'rake'"
end
end
# Remove default task and switch to above (still in same file)
task(:default).clear.enhance ["override:default"]
At the terminal:
$ rake
/lib/tasks/default.rake: this is now the default 'rake' task
If there is a "cleaner" or more "conventional" Rails way, anyone's welcome to shout it out. This is the "cleanest" solution I could find.
I'm running a custom rake task...
namespace :import do
desc "Import terms of service as HTML from stdin"
task :terms => :environment do
html = STDIN.read
settings = ApplicationWideSetting.first
settings.terms_and_conditions = html
if settings.save
puts "Updated terms of service"
else
puts "There was an error updating terms of service"
end
end
end
The model ApplicationWideSetting is reported as undefined when running the task in the production environment. However, when running the task on other environments (ie. development, staging, test.) the task runs fine.
Running the process in rails console, in all environments, completes ok.
Does anyone know what's going on, things I could check?
note: I ran the task with
puts Rails.env
To check the shell environment var RAILS_ENV was getting set/read correctly. I've also tried both with and without the square brackets around the :environment dependency declaration.
additional info: Rails v3.2.14
further info: I've setup a completely fresh rails app, and the script works fine in any environment. Since the install in question is a real production environment, I'll have to setup another deploy and check it thoroughly. More info as I find it.
In a nutshell, Rails doesn't eager load models (or anything else) when running rake tasks on Production.
The simplest way to work with a model is to require it when you begin the rake task, and it should work as expected, in this case:
# explicitly require model
require 'application_wide_setting'
It's possible to eager load the entire rails app with:
Rails.application.eager_load!
However, you may have issues with some initializers (ie. devise)
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
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.
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.