Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Ruby unit tests with Rake

Tags:

ruby

rake

I was investigating using the Rake build tool to automate running unit tests. I searched the web, but all the examples were for using rails. I usually just write small command-line programs or simple Sinatra applications.

So I came up with the following (probably bad) solution that just emulates what I would do on the command-line: (I just ran one unit test as an example.)

desc 'Run unit tests'
task :test do
    sh 'ruby -I lib test/test_entry.rb'
end
task :default => :test

It works, but I can't help thinking there must be a better way, just writing require 'test/test_entry.rb' doesn't work. I get require problems, Ruby can't find the lib directory, where all the files are.

like image 344
kmikael Avatar asked Jan 26 '12 11:01

kmikael


People also ask

How do I run a Ruby test?

We can run all of our tests at once by using the bin/rails test command. Or we can run a single test file by passing the bin/rails test command the filename containing the test cases. This will run all test methods from the test case.

What is rake test?

Rake is a popular task runner for Ruby and Rails applications. For example, Rails provides the predefined Rake tasks for creating databases, running migrations, and performing tests. You can also create custom tasks to automate specific actions - run code analysis tools, backup databases, and so on.

What are test cases in Ruby?

Structuring and Organizing Tests Tests for a particular unit of code are grouped together into a test case, which is a subclass of Test::Unit::TestCase. Assertions are gathered in tests, member functions for the test case whose names start with test_.

What are unit tests Rails?

They make sure that a section of an application, or a “unit”, is behaving as intended. In a Rails context, unit tests are what you use to test your models. Although it is possible in Rails to run all tests simultaneously, each unit test case should be tested independently to isolate issues that may arise.


2 Answers

Use Rake::TestTask http://rake.rubyforge.org/classes/Rake/TestTask.html . Put this into your Rake file and then run rake test:

require 'rake/testtask'

Rake::TestTask.new do |t|
  t.libs << "test"
  t.test_files = FileList['test/test*.rb']
  t.verbose = true
end
like image 106
DNNX Avatar answered Oct 04 '22 10:10

DNNX


The problem is that your lib directory is not included into ruby's loading path. You can fix it like that:

$:.unshift 'lib'
require 'test_entry'

or more reliable alternative that adds expanded path of lib directory to the loading path:

$:.unshift File.expand_path(File.join(File.dirname(__FILE__), 'lib'))
require 'test_entry'

Btw, global variable $: has more verbose alias $LOAD_PATH.

like image 44
KL-7 Avatar answered Oct 04 '22 10:10

KL-7