Jul 20, 2011

Rails 3 Madness

I have been struggling with Rails 3 testing framework for a few days now.

This is a madness. There are so many gems to install:

gem 'rspec', :group => [:development, :test]

gem 'rspec-rails', :group => [:development, :test]
gem 'database_cleaner', :group => :test
gem 'factory_girl_rails', :group => :test
gem 'mongoid-rspec', :group => :test

gem 'cucumber-rails', :group => :test
gem 'capybara', :group => :test

gem 'win32-process', :group => :test
gem 'spork', :git => "https://github.com/timcharper/spork.git", :group => :test


rspec-rails is obvious. It is RSpec for Rails.
database_cleaner is for truncate database. It supports Mongoid. That's why I use it.
factory_girl_rails is a mocking library for Rails. It's so simple.
mongoid-rspec is an adapter of RSpec to Mongoid.
cucumber-rails is a BDD testing framework for Rails.
capybara is for testing AJAX and javascript. It can fire an event click on a button or check if the result HTML contains some specific values.
Spork preloads the Rails environment, so that the testing runs faster.

Now you'll need to install RSpec

rails generate rspec:install


Before you run spork, you'll have to make some changes to application.rb in order to make Spork automatically reload any changes


class Application < Rails::Application
.
.
.

if Rails.env.test?
initializer :after => :initialize_dependency_mechanism do
ActiveSupport::Dependencies.mechanism = :load
end
end

end


And in spec_helper.rb, we put this line at the bottom of Spork.prefork block:


ActiveSupport::Dependencies.clear


And in Spork.each_run block, we put in these lines:


load "#{Rails.root}/config/routes.rb"
Dir["#{Rails.root}/app/**/*.rb"].each { |f| load f }


Now you can start Spork

bundle exec spork --bootstrap

bundle exec spork



Related links: https://github.com/RailsApps/rails3-mongoid-devise/wiki/Tutorial