Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
doc
pkg
*.gem
.treasure_map.rb
.treasure_map.rb
.bundle
Gemfile*.lock
vendor/bundle
49 changes: 49 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2015-09-14 16:20:12 -0400 using RuboCop version 0.34.1.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.

AllCops:
Exclude:
- 'bin/**/*'
- 'vendor/**/*'

# Offense count: 5
Lint/HandleExceptions:
Exclude:
- 'Rakefile'
- 'test/active_record/connection_adapters/unit_record_adapter_test.rb'
- 'test/unit_record/column_test.rb'
- 'test/unit_record/disconnected_active_record_test.rb'
- 'test/unit_record/disconnected_test_case_test.rb'

# Offense count: 2
Lint/NestedMethodDefinition:
Exclude:
- 'lib/unit_record/disconnected_fixtures.rb'

# Offense count: 1
Lint/RescueException:
Exclude:
- 'test/active_record/connection_adapters/unit_record_adapter_test.rb'

# Offense count: 1
Metrics/AbcSize:
Max: 16

# Offense count: 55
# Configuration parameters: AllowURI, URISchemes.
Metrics/LineLength:
Max: 120

# Offense count: 2
# Configuration parameters: CountComments.
Metrics/MethodLength:
Max: 14

# Offense count: 17
Style/Documentation:
Enabled: false
6 changes: 5 additions & 1 deletion CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
*0.10.0

* Rails 3.0 and Rails 3.2 compatibility

*0.9.1* (April 22, 2009)

* Rails 2.3 compatibility
Expand All @@ -13,7 +17,7 @@
ActiveRecord::Base.disconnect! :strategy => :noop
or
ActiveRecord::Base.disconnect! :strategy => :raise

* Implemented as a connection adapter

*0.4.1* (December 10th, 2007)
Expand Down
5 changes: 5 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
source 'https://rubygems.org'

gemspec

gem 'rails', '~> 3.2.0'
5 changes: 5 additions & 0 deletions Gemfile.rails-3.0
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
source 'https://rubygems.org'

gemspec

gem 'rails', '~> 3.0.0'
5 changes: 5 additions & 0 deletions Gemfile.rails-3.1
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
source 'https://rubygems.org'

gemspec

gem 'rails', '~> 3.1.0'
5 changes: 5 additions & 0 deletions Gemfile.rails-3.2
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
source 'https://rubygems.org'

gemspec

gem 'rails', '~> 3.2.0'
105 changes: 63 additions & 42 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,53 +10,62 @@ Rationale: [http://www.dcmanges.com/blog/rails-unit-record-test-without-the-data

One of the biggest benefits to disconnecting unit tests from the database is having a faster test suite. Here is the benchmark from one of my current projects:

Finished in 19.302702 seconds.
4920 tests, 7878 assertions, 0 failures, 0 errors
```
Finished in 19.302702 seconds.
4920 tests, 7878 assertions, 0 failures, 0 errors
```

4 seconds per 1,000 tests is a good guideline.

Installation
------------

gem install unit_record
```
gem install unit_record
```

Usage
-----

Restructuring the Rails Test Directory
--------------------------------------

The Rails test directory typically places testing for models under <tt>test/unit</tt> and tests for controllers under <tt>test/functional</tt>. However, we need to change the definition of unit and functional. Controllers can be unit tested (mocking out models and not rendering the view). Models can be functionally tested (hitting the database). Also, each type of test needs its own test\_helper. I recommend restructuring your test directory like this:

test
test_helper.rb
unit
unit_test_helper.rb
controllers
models
functional
functional_test_helper.rb
controllers
models
The Rails test directory typically places testing for models under `test/unit` and tests for controllers under `test/functional`. However, we need to change the definition of unit and functional. Controllers can be unit tested (mocking out models and not rendering the view). Models can be functionally tested (hitting the database). Also, each type of test needs its own test\_helper. I recommend restructuring your test directory like this:

```
test
test_helper.rb
unit
unit_test_helper.rb
controllers
models
functional
functional_test_helper.rb
controllers
models
```

You should move existing functional tests into functional/controllers. You will also need to change the require line at the top of those tests to require the functional\_test\_helper.rb file instead of the test\_helper.rb file.

The <tt>functional_test_helper.rb</tt> file only needs to require <tt>test_helper.rb</tt>:
The `functional_test_helper.rb` file only needs to `require test_helper.rb`:

require File.dirname(__FILE__) + "/../test_helper"
```ruby
require File.dirname(__FILE__) + "/../test_helper"
```

For moving unit tests, you have a few options. I recommend moving them to unit/models and then disconnecting your unit tests from the database. Any tests that fail should then be modified to not hit the database or moved to functional/models.

Usage
-----

In the <tt>test/unit/unit\_test\_helper.rb</tt> file you created when restructuring your test directory, you should add these lines:
In the `test/unit/unit\_test\_helper.rb` file you created when restructuring your test directory, you should add these lines:

require File.dirname(__FILE__) + "/../test_helper"
require "unit_record"
ActiveRecord::Base.disconnect!
```ruby
require File.dirname(__FILE__) + "/../test_helper"
require "unit_record"
ActiveRecord::Base.disconnect!
```

The <tt>disconnect!</tt> method will do everything necessary to run your unit tests without hitting the database.
The `disconnect!` method will do everything necessary to run your unit tests without hitting the database.

Strategy
--------
Expand All @@ -65,46 +74,58 @@ There are two options for what should happen if you hit the database. You can ei

If you want to raise an exception:

ActiveRecord::Base.disconnect! :strategy => :raise
```ruby
ActiveRecord::Base.disconnect! :strategy => :raise

Person.find(:all)
#=> RuntimeError: ActiveRecord is disconnected; database access is unavailable in unit tests.
Person.find(:all)
#=> RuntimeError: ActiveRecord is disconnected; database access is unavailable in unit tests.
```

If you want to no-op:

ActiveRecord::Base.disconnect! :strategy => :noop
```ruby
ActiveRecord::Base.disconnect! :strategy => :noop

Person.find(:all)
#=> []
Person.find(:all)
#=> []
```

You can also change strategies within a block:

ActiveRecord::Base.connection.change_strategy(:raise) do
Person.find(:all)
#=> RuntimeError: ActiveRecord is disconnected; database access is unavailable in unit tests.
end
```ruby
ActiveRecord::Base.connection.change_strategy(:raise) do
Person.find(:all)
#=> RuntimeError: ActiveRecord is disconnected; database access is unavailable in unit tests.
end

ActiveRecord::Base.connection.change_strategy(:noop) do
Person.find(:all)
#=> []
end
ActiveRecord::Base.connection.change_strategy(:noop) do
Person.find(:all)
#=> []
end
```

Association Stubbing
--------------------

One painful aspect of unit testing ActiveRecord classes is setting associations. Because Rails does type checking when setting an association, you'll receive an exception if you try to use a stub in place of the expected class.

Pet.new :owner => stub("person")
#=> ActiveRecord::AssociationTypeMismatch: Person(#16620740) expected, got Mocha::Mock(#11567340)
```ruby
Pet.new :owner => stub("person")
#=> ActiveRecord::AssociationTypeMismatch: Person(#16620740) expected, got Mocha::Mock(#11567340)
```

If you're using mocha, you can have UnitRecord stub associations. To enable association stubbing:

ActiveRecord::Base.disconnect! :stub_associations => true
```ruby
ActiveRecord::Base.disconnect! :stub_associations => true
```

The above example would no longer raise an exception. It would be the equivalent of:

pet = Pet.new
pet.stubs(:owner).returns(stub("person"))
```ruby
pet = Pet.new
pet.stubs(:owner).returns(stub("person"))
```

Note that using this approach, the setter for the association will not work for that instance.

Expand Down
95 changes: 26 additions & 69 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -1,95 +1,52 @@
require 'rake'
require 'rake/testtask'
require 'spec/rake/spectask'
require 'rubocop/rake_task'

desc "Default: run tests"
task :default => %w[test:multi_verbose spec]
desc 'Default: run tests'
task default: %w(rubocop test)

Rake::TestTask.new("test") do |t|
t.pattern = "test/**/*_test.rb"
RuboCop::RakeTask.new(:rubocop)

Rake::TestTask.new('test') do |t|
t.pattern = 'test/**/*_test.rb'
t.verbose = true
end

Spec::Rake::SpecTask.new(:spec) do |t|
t.spec_files = %w(test/sample_spec.rb)
end

begin
require "rcov/rcovtask"
desc "run tests with rcov"
require 'rcov/rcovtask'
desc 'run tests with rcov'
Rcov::RcovTask.new do |t|
t.pattern = "test/**/*_test.rb"
t.rcov_opts << ["--no-html", "--exclude 'Library,#{Gem.path.join(',')}'"]
t.pattern = 'test/**/*_test.rb'
t.rcov_opts << ['--no-html', "--exclude 'Library,#{Gem.path.join(',')}'"]
t.verbose = true
end
rescue LoadError
end

require "date"

gem_spec = Gem::Specification.new do |s|
s.name = "unit_record"
s.summary = "UnitRecord enables unit testing without hitting the database."
s.version = "0.9.1"
s.author = "Dan Manges"
s.description = "UnitRecord enables unit testing without hitting the database."
s.email = "daniel.manges@gmail.com"
s.homepage = "http://unit-test-ar.rubyforge.org"
s.rubyforge_project = "unit-test-ar"

s.has_rdoc = false

s.autorequire = "unit_record"
s.files = FileList['{lib,test,vendor}/**/*.rb', 'CHANGELOG', 'LICENSE', 'README.markdown', 'Rakefile'].to_a
end

task :gem => %w[test:multi] do
Gem::Builder.new(gem_spec).build
end

namespace :gemspec do
desc "generates unit-record.gemspec"
desc 'generates unit-record.gemspec'
task :generate do
File.open("unit-record.gemspec", "w") do |f|
f.puts "# this file is generated by rake gemspec:generate for github"
File.open('unit-record.gemspec', 'w') do |f|
f.puts '# this file is generated by rake gemspec:generate for github'
f.write gem_spec.to_ruby
end
end
end

task :readme do
require "rubygems"; gem "BlueCloth"; require "BlueCloth"; require 'tmpdir'
require 'rubygems'
gem 'BlueCloth'
require 'BlueCloth'
require 'tmpdir'
file = "#{Dir.tmpdir}/readme.html"
File.open(file, "w") { |f| f.write BlueCloth.new(File.read("README.markdown")).to_html }
File.open(file, 'w') { |f| f.write BlueCloth.new(File.read('README.markdown')).to_html }
sh "open #{file}"
end

RAILS_VERSIONS = %w[1.2.6 2.0.2 2.1.0 2.1.1 2.2.2 2.3.1]

namespace :test do
desc "test with multiple versions of rails"
task :multi do
RAILS_VERSIONS.each do |rails_version|
puts "Testing with Rails #{rails_version}"
sh "RAILS_VERSION='#{rails_version}' rake test > /dev/null 2>&1"
end
end

task :multi_verbose do
(RAILS_VERSIONS - %w[]).each do |rails_version|
task = defined?(Rcov) ? "rcov" : "test"
puts "Testing with Rails #{rails_version}"
sh "RAILS_VERSION='#{rails_version}' rake #{task}"
end
end
end

begin
gem "rspec"
require "spec/rake/spectask"
Spec::Rake::SpecTask.new(:spec) do |t|
t.spec_files = %w[test/sample_spec.rb]
end
rescue LoadError
task :spec do
puts "== RSpec failed to load"
end
end

desc "pre-commit task"
task :pc => %w[test:multi spec gemspec:generate]
desc 'pre-commit task'
task pc: %w(test:multi spec gemspec:generate)
Loading